This page documents how the Partners Portal (apps/partners, served at partners.matters.ai) decides who gets in, what they get to see, and how every protected surface is guarded.
It covers the three ordered layers (identity, admission, authorization), the Clerk integration, the middleware chain, the sign-in / sign-up / onboarding flow, the organization model, and the mechanics of the server-side gate functions. It does not re-derive the account-type capability matrix — that lives on a separate page:
/approval screen, the approval saga, and what a super-admin chooses.The short version: Clerk owns identity (who you are). partner_sessions (a Neon/Postgres table, hydrated from Salesforce) owns partner standing (are you an active partner). The account-type model owns internal privilege (are you internal / admin / super-admin). Three different gate tiers read these three facts.
The portal's auth is three ordered layers. Each makes exactly one decision and hands off. They are ordered so that nobody is asked to do something they are not yet allowed to do.
| # | Layer | Decides | Owned by | Grants |
|---|---|---|---|---|
| 1 | Identity | Who are you? | Clerk — real self-service sign-up at /sign-up | Nothing. Creating an account is not admission. |
| 2 | Admission | May this account reach the portal at all? | admissionFor() + middleware + requirePartnerSession() | A route into the portal, or a hold at /approval. |
| 3 | Authorization | What may an admitted account do? | account_type → capability matrix (lib/auth/account-type.ts) | Capabilities. Unchanged by the admission work. |
The old path conflated identity, admission and authorization, with four concrete defects:
orgId to /select-organization first; only afterwards did requirePartnerSession() consult portalAdmission and send them to /pending or /access-denied. A brand-new unapproved person was asked to join or create a workspace before anyone told them they had no access./pending and /access-denied were dead ends — public routes with no sign-out and no route back into the flow.partner and always created a brand-new Clerk org.Underneath all four: there was no single, early, authoritative "is this person admitted?" decision. Every screen re-derived it, and they disagreed.
admissionFor()#lib/auth/admission.ts is a pure module with no I/O, so Edge middleware, server components and the test suite all import the same function and cannot disagree about who is admitted:
export type Admission = "admitted" | "blocked";
export const BLOCKED_ROUTE = "/approval";
export function admissionFor(type: AccountType): Admission {
return portalAdmission(type) === "admit" ? "admitted" : "blocked";
}
It collapses portalAdmission's three-way result (admit / pending / deny) into two outcomes. The old pending vs deny split is now presentation only: /approval resolves the reason (awaiting, rejected, no request) from the request row itself. A signed-in user with no verified email resolves to pending and is therefore blocked too (getAccountSession() returns NO_VERIFIED_IDENTITY_TYPE for them, and writes nothing, so the real derivation still runs cleanly once they verify).
| Admission | Account types | Destination |
|---|---|---|
admitted | partner, prospect, and the internal tiers | their portal, or the redirect_url they arrived with |
blocked | pending, rejected, or no verified email | /approval — nothing else is reachable |
admitted, no active org | (as above) | /select-organization — reachable only by an admitted user |
Middleware runs on every request, and getAccountSession() does Clerk and Postgres work that does not belong on that path. So middleware reads one short-lived signed cookie instead of the database.
pp_adm (ADMISSION_COOKIE), 60 seconds (ADMISSION_TTL_MS). httpOnly, sameSite: "lax", secure in production.{ sub, adm, exp } — the Clerk user id, "admitted" | "blocked", and an absolute expiry in epoch milliseconds. Signed with HMAC-SHA-256 keyed on CLERK_SECRET_KEY (lib/auth/admission-cookie.ts). It uses Web Crypto, not node:crypto, because middleware runs on the Edge runtime where the node builtin does not exist. Signature comparison is constant-time.verifyAdmission) returns the claim only if the signature verifies and it has not expired. It never throws: a malformed cookie is indistinguishable from no cookie.requirePartnerSession() (lib/auth/gate.ts) calls writeAdmissionCookie() (lib/auth/admission-session.ts) after it resolves admission for real. The write is never fatal: Next.js can refuse cookie writes in some render contexts, and this is a cache warm-up, not a security control, so any failure is swallowed at debug level. A missing CLERK_SECRET_KEY yields a zero-length HMAC key, which signAdmission rejects — the write is skipped, i.e. no cookie.The rule middleware follows is deliberately asymmetric:
if (claim?.sub === userId && claim.adm === "blocked" && !isBlockedRoute) {
// redirect to /approval
}
blocked claim, and only when claim.sub === userId (a claim minted for one account cannot be replayed into another session).admitted claim never grants anything. There is no code path in middleware where a cookie causes a user to be let in. An absent, expired, malformed or admitted cookie all do the same thing: fall through to the route, where the authoritative check runs.requirePartnerSession(). It resolves admission for real on every gated render (getAccountSession() → admissionFor()), re-mints the cookie, and redirect(BLOCKED_ROUTE)s if blocked.Do not "optimise" this. The cookie looks like a cache that could also short-circuit the
admittedcase ("skip the database when the cookie says admitted"). That would turn an advisory accelerator into a bearer credential: anything that can forge, replay or extend a cookie — a stale cookie after a revocation, a leaked secret, a bug in the signing code — would become portal access. As built, the worst a stale or forged cookie can do is cost one redirect, because the server re-checks on every gated render. The 60-second TTL is only the outer bound on a claim's life; in practice ablockedclaim is spent far sooner (next section).
clearAdmissionCookie() (lib/auth/admission-cookie.ts) expires the cookie (maxAge: 0, with the same path / secure / sameSite attributes as the write, because a delete only matches when they agree). It is called from exactly two places:
blocked claim. A blocked claim causes at most one redirect. The cookie is cleared on that very response, so the next request falls through to the authoritative gate.GET /api/approval/status, when the payload state is approved. The grant has just landed, so any blocked cookie the browser still holds is stale. This is a Route Handler, where cookie writes are reliable (unlike the best-effort write in the RSC gate). The /approval client then does its full navigation to /dashboard cookie-free: middleware falls through and requirePartnerSession() re-decides from the database and re-mints.Why clearing is safe. Absence of a cookie can never admit anyone. Middleware never admits on a cookie, so removing one can only move the decision toward requirePartnerSession(), which decides from the database. Clearing therefore costs at most one extra authoritative evaluation and can never grant access. The status route deliberately clears rather than minting an admitted cookie: an admitted claim buys nothing and only adds a second way to be wrong.
Rationale: the redirect loop this fixes. Originally a blocked claim lived for its whole TTL.
/approvalhas no portal layout, so it never reaches the gate that would correct a stale decision. A user approved after the cookie was minted would navigate to/dashboard, be bounced by middleware to/approval, which bounces an admitted user back to the portal, and so on until the TTL expired. The lesson is cross-cutting: any new cookie writer needs a corresponding clear, and any cached block must be bounded to one use, because the screen that block sends people to cannot refresh it. Do not add a second writer ofpp_admwithout deciding where it is cleared.
Admission fails closed. Anything that goes wrong resolving admission lands on the blocking side, never inside the portal: no verified email → pending → blocked; an exception while resolving the session propagates out of requirePartnerSession() rather than returning a session; the polling endpoint's own fallback is awaiting (which never forwards anyone into the portal); and a missing signing secret just means no cookie, so the authoritative check runs.
| Route | Before | After |
|---|---|---|
/sign-in | Clerk sign-in; "Sign up" link pointed at /request-access | Unchanged route; "Sign up" link points at /sign-up; always lands on /dashboard |
/sign-up | Disabled | New. Real self-service Clerk sign-up (PartnerSignUp, forceRedirectUrl="/approval"). Public. |
/approval | — | New. The single blocking screen, four states (see Access Requests). Authenticated, not public. |
/post-auth | Neutral post-sign-in router (public) | Deleted. Sign-in lands on /dashboard; middleware routes the unadmitted to /approval; /admin has its own gate. |
/request-access | Anonymous public access-request form | Deleted. Folded into /approval state no_request. |
/pending | Dead-end interstitial (public) | Deleted. State awaiting of /approval. |
/access-denied | Dead-end interstitial (public), "Request Access" button | Deleted. State rejected of /approval, with re-apply. |
/select-organization | Reached by anyone with no org, before admission | Reached only by an admitted user with no org |
/accept-invite | Org-invite landing | Unchanged (still used by the legacy invite path) |
/api/approval/status | — | New. Own-row, session-keyed poll endpoint |
Five newcomer routes became one.
account_type is the one authorization axis#Everything authorizes off account_type (partner_sessions.accountType, DB + Clerk mirror). The 7-type ladder — pending · rejected · prospect · partner · internal_team_member · admin · super_admin — drives both the partner-facing app (via portalAdmission) and the internal admin zone (via the tier gates).
| Surface | Gate | Admits |
|---|---|---|
Partner app (/dashboard, opportunities, MDF, enablement) | requirePartnerSession() → portalAdmission(account_type) | partner / prospect / internal tiers |
Internal admin zone (/admin/*) | requireInternalReadSession / requireAdminSession / requireAdminWriteSession | internal tiers (read vs write) |
| Super-Admin surfaces (approvals, account-type assignment, feature-access) | requireSuperAdminSession | super_admin only |
Historical note: admission used to key off a second axis — the SF-derived
partner_sessions.partnerStatus. That was disjoint fromaccount_type, so admin grants never reached the gate.partnerStatusis now display metadata only (tier / partner type / SF ids); it is never an authorization input.
Identity is fully delegated to Clerk. The portal uses @clerk/nextjs (App Router) with the standard <ClerkProvider> at the root and Clerk's hosted-component <SignIn> widget.
| Variable | Purpose |
|---|---|
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY | Client-side Clerk SDK key (browser). |
CLERK_SECRET_KEY | Server-side key. Used by @clerk/nextjs/server and by the raw Backend REST helper in lib/clerk-admin.ts (Bearer token). Never logged or thrown in an error message. |
CLERK_WEBHOOK_SECRET | Svix signing secret for the /api/webhooks/clerk endpoint. |
MATTERS_CLERK_ORG_ID | The Clerk org id of the internal Matters.AI team. Drives the internal bypass + the super-admin bootstrap floor. |
SUPER_ADMIN_EMAILS | Comma-separated allowlist of super-admin emails. Defaults to eshank@matters.ai if unset. |
NEXT_PUBLIC_APP_URL | Base URL for invitation redirect_url (defaults to https://partners.matters.ai). |
NEXT_PUBLIC_MULTI_ACCOUNT_ENABLED | Master flag for multi-session account switching. Default off (single-account behaviour). |
components/auth/PartnerSignIn.tsx renders Clerk's <SignIn> and components/auth/PartnerSignUp.tsx renders <SignUp>, both themed via useClerkAppearance() from lib/theme/clerkAppearance.ts (wired through the portal's own pm-* theme rather than left raw).
// PartnerSignIn
<SignIn forceRedirectUrl="/dashboard" signUpUrl="/sign-up" appearance={appearance} />
// PartnerSignUp
<SignUp forceRedirectUrl="/approval" signInUrl="/sign-in" appearance={appearance} />
/dashboard. There is no neutral post-auth router any more: middleware sends anyone not yet admitted to /approval, and the admin zone has its own gate. This holds with the multi-account flag on or off.account_type = pending and lands on /approval. Creating an account grants nothing./api/webhooks/clerk)#A Svix-signed webhook keeps Neon in step with Clerk lifecycle events. The signature is verified with CLERK_WEBHOOK_SECRET; an invalid signature returns 400.
| Clerk event | Action |
|---|---|
organizationMembership.created | Fire-and-forget getOrRefreshPartnerStatus(userId, orgId, email) — warms the partner_sessions cache so the partner's first dashboard load is already resolved. Does not block the webhook ack on Salesforce latency. |
user.deleted | Hard-delete the user's partner_sessions row and their opportunity_notes (GDPR-style cleanup). |
lib/clerk-admin.ts)#Admin-driven org/membership provisioning uses the documented Clerk Backend REST surface at https://api.clerk.com/v1 with a Bearer CLERK_SECRET_KEY — intentionally not @clerk/backend. It is server-only (only imported from "use server" actions) and exposes:
createOrgWithAdminInvite({ orgName, inviterEmail, inviteeEmail }) — the legacy path: find-or-create a Clerk org, then either add an existing user as org:admin or send an org invitation whose redirect_url is ${NEXT_PUBLIC_APP_URL}/accept-invite. Idempotent and safe to retry. Only used for access requests with no clerk_user_id.addUserToOrg(orgId, userId, role) — idempotent direct membership; returns true only if it created the membership (false if the user was already a member, and it never downgrades an admin). Approval uses this for applicants who already have a Clerk account.createOrganizationForUser(name, userId) — creates an org with userId as creator and admin.inviteToExistingOrg({ orgId, inviterEmail, inviteeEmail }) — invitation into an existing org, for legacy requests with no Clerk user.removeUserFromOrg(orgId, userId) — saga compensation for a membership the approval added; a no-op when already absent.revokeOrgInvite(orgId, invitationId, requestingUserId) — best-effort saga compensation; never throws (DB is the source of truth).setUserPrivateMetadata(clerkUserId, patch) — merges into Clerk privateMetadata (never the session JWT). Used to mirror the authoritative accountType.This helper is the back end of the access-request approval flow — see /partners/access-requests.
Partner companies are modeled as Clerk organizations. A partner user belongs to exactly one (or, under multi-account, may switch between) Clerk org; their orgRole (org:admin vs org:member) is read from the Clerk session. isOrgAdmin(session) in lib/auth/gate.ts is simply session.orgRole === "org:admin".
One Clerk org is special: the internal Matters.AI team org, whose id is MATTERS_CLERK_ORG_ID. Membership in that org (as org:admin) is one of the two bootstrap paths to super-admin (the other being the SUPER_ADMIN_EMAILS allowlist).
Partner users must be in an org. The middleware enforces this — but only after admission: an admitted user with no org is routed to /select-organization, the domain-based workspace chooser, not bounced to sign-in. A user who is not admitted never sees the chooser. In practice an approved applicant already has a membership (approval adds them directly), so they skip it.
/select-organization)#Orgs are no longer self-service (that caused every signup to spawn its own Clerk org). Instead, an admitted signed-in user without an active org lands on /select-organization, driven by lib/actions/org-onboarding.ts:
joinDomainOrg(orgId) only permits an org tied to the caller's domain — the security boundary that stops joining arbitrary orgs.createDomainOrg(name), capped at MAX_ORGS_PER_DOMAIN (5) per email domain.@matters.ai users are auto-added to MATTERS_CLERK_ORG_ID (autoJoinInternalOrg).Ops dependency: disable member org-creation in the Clerk Dashboard (so the capped server action is the only create path) and enable multi-session. Tracked on WEB-48.
apps/partners/middleware.ts runs Clerk's clerkMiddleware() on every request except static assets (matcher excludes _next/static, _next/image, favicon.ico). Each request is stamped with a fresh X-Request-ID. The chain, in order:
request
│
├─ 1. Host allowlist check ─────────► not allowed → 404 (noindex,nofollow)
│
├─ 2. Public route? ───────────────► yes → NextResponse.next() (no auth)
│
├─ 3. auth() → userId? ─────────────► no → 307 /sign-in?redirect_url=<safe path>
│
├─ 4. ADMISSION: valid pp_adm cookie, sub === userId, adm === "blocked",
│ and not already on /approval ─► yes → 307 /approval + clear the cookie (single use)
│
├─ 5. orgId? (skip for /api, /admin, /select-organization, /approval)
│ ─► no → 307 /select-organization
│
└─ 6. NextResponse.next() (pass to the page; gates run server-side)
The admission branch (4) sits above the org check (5). That ordering is the fix for defect 1: a non-admitted user is turned around before they can be asked to pick a workspace.
isAllowedHost() admits the hosts in ALLOWED_HOSTS (default partners.matters.ai,partners-portal.matters.ai, overridable via the ALLOWED_HOSTS env var), plus localhost / 127.0.0.1 / ::1 (dev), plus *.vercel.app outside production only (preview deployments). Anything else gets a 404 with X-Robots-Tag: noindex,nofollow, so the portal is never exposed or indexed on a stray host.
isPublicRoute (via createRouteMatcher) bypasses auth for the sign-in/sign-up flows and machine endpoints:
/sign-in(.*) /sign-up(.*) /accept-invite(.*)
/directory /api/sf/callout /api/webhooks/clerk
/api/health /api/csp-report /api/cron/(.*)
/approval is not public — it requires a signed-in user, which is the point: an unapproved person must have an account first. /pending, /access-denied, /request-access and /post-auth are no longer routes at all. The cron endpoints self-authenticate with Bearer CRON_SECRET.
auth() yields { userId, orgId }. No userId → redirect to /sign-in with a redirect_url set to the originally requested path (validated to start with a single /, falling back to /dashboard to block open-redirects). Under multi-account, the redirect also gets no-store / Vary: Cookie cache headers so Back/Forward never restores a prior account's page.
Middleware verifies the pp_adm cookie and redirects to /approval only for a validly signed, unexpired, blocked claim whose sub equals the current userId, on a path other than /approval. The claim is single-use: the redirect response clears the cookie (clearAdmissionCookie), so a stale block can bounce a user at most once. Everything else falls through. See the admission cookie for why middleware never acts on an admitted claim.
If authenticated but no orgId, redirect to /select-organization — unless the path is under /api, matches isAdminRoute (/admin, /admin/(.*)), is the chooser itself (loop guard), or is /approval. Admin routes deliberately do not require org membership, because internal Matters.AI users have no partner org; the @matters.ai gate for /admin is enforced server-side by requireAdminSession(), not by the middleware.
The middleware is a coarse gate (authenticated + advisory block + has-an-org). The real authorization — admission, account type, privilege tier — happens in the server-side gate functions the pages call. The middleware never reads partner_sessions or Salesforce.
requirePartnerSession() — the partner gate#lib/auth/gate.ts exports the gate every partner-facing server component / action calls. It returns a typed PartnerSession or redirect()s. Admission is decided by account_type — the same field the admin panel and domain auto-derivation control — so an admin grant or an approval actually lets the partner in. partnerStatus (SF/CSV) is only display metadata on the returned session.
const account = await getAccountSession();
if (!account) redirect("/sign-in?reason=unauthenticated");
const { clerkUserId, email, accountType } = account;
const { orgId, orgRole } = await auth();
getAccountSession() resolves (and on first login auto-derives) the caller's accountType — see Account-type resolution.
If isInternalTier(accountType) (internal_team_member / admin / super_admin), the function returns a synthetic session (partnerType: "internal", null SF ids) — keyed off the account type, not the org id, so internal staff are admitted regardless of which org is active. It never touches partner_sessions or Salesforce.
admissionFor)#The gate calls admissionFor(accountType) (lib/auth/admission.ts, which wraps the pure portalAdmission in lib/auth/account-type.ts — admit iff portal.read). It then calls writeAdmissionCookie(clerkUserId, admission) to re-mint the advisory cookie for middleware, whichever way the decision went.
account_type | portalAdmission | admissionFor | Outcome |
|---|---|---|---|
partner, prospect, internal tiers | admit | admitted | continue (org + metadata step below) |
pending | pending | blocked | redirect("/approval") |
rejected (and anything without portal.read) | deny | blocked | redirect("/approval") |
Both former dead ends are now states of the one /approval screen, which resolves the reason itself from the request row.
An admitted external partner still needs an active org to scope their data. If orgId is absent, redirect("/select-organization") (the organization chooser). Otherwise the gate best-effort-refreshes SF metadata (getOrRefreshPartnerStatus — non-gating, so an SF outage never locks out an admitted partner) and returns the PartnerSession: clerkUserId, clerkOrgId, email, partnerRole, partnerType, partnerTier, sfAccountId, sfContactId, orgRole. isOrgAdmin(session) gates org-admin-only affordances.
Feature-access gate. On top of admission, individual pages can require a feature audience via
requireFeature(key)(lib/auth/feature-gate.ts) — a code-only config (lib/feature-access.ts) mapping each feature to"all"or a set of account types, surfaced read-only at/admin/feature-access. Currently Content Library, Agreements, Tier Benefits, and Public Directory aresuper_admin-only for internal testing.
The internal/admin gates read a different fact: the user's account type. lib/auth/account-gate.ts#getAccountSession() is the non-redirecting resolver they all build on.
A privilege decision is only ever made from a Clerk verified primary email:
const verifiedEmail =
primaryEmail?.verification?.status === "verified"
? (primaryEmail.emailAddress ?? "").toLowerCase()
: "";
An unverified address can populate the session's display email, but it can never satisfy the @matters.ai domain check or the SUPER_ADMIN_EMAILS allowlist. This blocks "set my email to admin@matters.ai" privilege-escalation attempts — an attacker would have to actually control the mailbox to verify it.
getAccountSession() computes whether the caller is an allowlisted super-admin before resolving:
const isAllowlistedSuperAdmin =
(!!mattersOrgId && orgId === mattersOrgId && orgRole === "org:admin") ||
(verifiedEmail.length > 0 && superAdminEmails().includes(verifiedEmail));
It then calls resolveAccountType() (in lib/auth/account-type-store.ts). The resolver always floors an allowlisted user to super_admin, regardless of any DB or Clerk state — so the portal can never lock itself out of approvals. (Type resolution, the Clerk-privateMetadata mirror, self-healing, and first-login auto-derivation are detailed on /partners/rbac.)
getSuperAdminClearance() is the non-redirecting form (returns { ok, userId, orgId, email }) used by shared chrome to decide whether to render admin navigation without bouncing the page.
There is a small, explicit ladder of gate functions. Each is a thin policy on top of the resolvers above; each redirect()s on failure so callers can treat the return value as a proof of access.
| Gate function | Tier / capability | Resolves on | On failure | Guards |
|---|---|---|---|---|
requirePartnerSession() | Portal admission | portalAdmission(account_type) = admit (partner/prospect/internal) | /approval, /select-organization, /sign-in?reason=… | All partner-facing surfaces: /dashboard, opportunity registration, MDF, enablement content. |
requireInternalReadSession() | admin.read capability | account type ∈ super_admin | /dashboard (no internal access) → or /sign-in if unauthenticated | Internal read-only surfaces (the AccountSession-typed callers). |
requireAdminSession() | Admin read tier | wraps requireInternalReadSession(); returns { userId, email } | /dashboard / /sign-in | Read-only /admin/* pages. Signature preserved so existing call sites compile unchanged. |
requireAdminWriteSession() | Admin write tier | admin.write capability (admin or super_admin; internal_team_member is read-only) | /admin?reason=read_only / /sign-in | Mutating admin actions — uploads, edits, deletes. |
requireSuperAdminSession() | super_admin only | account type === "super_admin" (incl. bootstrap floor) | /sign-in?reason=unauthorized (logs a warn) / /sign-in?reason=unauthenticated | Super-Admin-only surfaces: access-request approval, account-type assignment. |
Notes:
account_type. requirePartnerSession() admits via portalAdmission(account_type); the account-type gates check specific tiers/capabilities. The legacy partnerStatus is metadata only, never a gate. The middleware's /admin org-skip exists so the account-type gates can run for org-less internal users.requireProspectOrAbove does not exist as a standalone gate in the codebase — prospect/partner-level differentiation is expressed through the capabilities (portal.read, portal.write, content.read) on the account-type matrix and checked with can(type, capability), not via a dedicated gate function. See the matrix on /partners/rbac.requireAdminSession() returning { userId, email } (not the full AccountSession) is intentional API stability for the pre-existing /admin/* call sites.These live under the (auth) route group with a dedicated full-bleed layout (app/(auth)/layout.tsx). /sign-in, /sign-up and /accept-invite are on the public-route allowlist; /approval and /select-organization require a signed-in user.
/sign-in#Hosts the Clerk <SignIn> widget. It reads a reason query param and renders a contextual message above the widget. The reason → copy map:
reason | Message |
|---|---|
unauthenticated | "Please sign in to access the partner portal." |
no_org | "Your account is not linked to a partner organisation. Contact your partner admin." |
no_email | "Your Clerk account has no verified email address. Please add one and try again." |
sf_error | "We could not verify your partner status with Salesforce. Please try again or contact support or wait for account approval." |
inactive | "Your account is not currently active in our partner program. Please contact your Matters.AI partner manager." |
pending | "Your partner account is pending activation. You will receive an email once approved." |
not_provisioned | "Your account could not be provisioned. Please contact your Matters.AI partner manager." |
unauthorized | No dedicated unauthorized key on sign-in — a Super-Admin denial falls through to the generic "Access Restricted" card with a Sign Out / Switch Account button. |
If the user is already signed in and arrives with a non-unauthenticated reason, the page renders an "Access Restricted" card with a Sign Out / Switch Account button instead of the sign-in widget. In single-account mode, a signed-in internal @matters.ai user is redirected straight to /admin (rescuing them from the org-less bounce); multi-account mode skips this so the account chooser still works.
/sign-up#Hosts the Clerk <SignUp> widget (PartnerSignUp). Open and self-service; completing it lands on /approval. Grants nothing by itself — see the three layers.
/approval#The one screen a non-admitted user can reach, with four states (no_request, awaiting, approved, rejected) and a 5-second poll of /api/approval/status. It has a sign-out affordance — the dead ends it replaced had none. Fully documented, including the polling contract and why that endpoint cannot be used to enumerate other people's applications, on Access Requests & Approval.
/accept-invite#The landing page for the Clerk org invitation redirect_url sent by the legacy invite path (createOrgWithAdminInvite() / inviteToExistingOrg()). It renders PartnerOrganizationList so the invitee can accept membership and enter the portal; a brand-new invitee carrying a __clerk_ticket gets the themed <SignUp> in ticket mode instead. Approvals of requests filed from /approval do not use this page — those applicants are added to the org directly.
1. User hits partners.matters.ai/dashboard
2. middleware: host OK → not public → no userId → /sign-in?redirect_url=/dashboard
3. New user chooses "Sign up" → /sign-up (Clerk) → verifies email → lands on /approval
(returning user signs in → forceRedirectUrl=/dashboard)
4. middleware: userId ✓ → no usable blocked cookie yet → falls through
5. /dashboard server component calls requirePartnerSession()
├─ getAccountSession() → resolve/auto-derive account_type
│ (partner-domain email → auto "partner"; unknown domain → "pending")
├─ isInternalTier? → synthetic internal session (no SF)
└─ admissionFor(account_type), cookie re-minted:
admitted → has org? yes → render dashboard
│ no → /select-organization (join company org / create, cap 5)
blocked → /approval (once the cookie write succeeds, later requests are turned
around by middleware without reaching the gate)
6. On /approval: "Ask for approval" → requestApproval → request row (pending)
7. Super-admin approves at /admin/access-requests (picks company + role)
→ Clerk membership + one transaction → account_type = partner | prospect
8. The open /approval poll sees `approved` within ~5s → window.location.assign("/dashboard")
→ requirePartnerSession() now admits; the applicant already has an org → dashboard renders
An internal user hits the internal-tier bypass at step 5 (or is routed to /admin from /sign-in) and never touches Salesforce; /select-organization auto-joins them to the Matters org.
| Property | How it's enforced |
|---|---|
| Privilege decisions trust only real identity | Verified-email-only check in getAccountSession(); bootstrap floor requires either verified allowlist email or verified @matters.ai org-admin membership. |
| No lockout of approvals | resolveAccountType() always floors allowlisted users to super_admin, independent of DB/Clerk state. |
| Salesforce outage doesn't break active partners | First-visit SF failure with an existing cached row is allowed through; CSV mode runs entirely without SF. |
| No open redirects | redirect_url is validated to start with a single /, else falls back to /dashboard. |
| No host spoofing / preview-host exposure | Strict host allowlist → 404 + noindex for anything but partners.matters.ai (and localhost). |
| Webhook integrity | Svix signature verified against CLERK_WEBHOOK_SECRET; bad signature → 400. |
| Unapproved users cannot reach the portal | Layer 2: requirePartnerSession() is the authority; middleware turns a signed blocked claim around early; the admitted claim never grants access; failures resolve to blocked. |
| Approval status cannot be enumerated | /api/approval/status is keyed off the caller's session, never an id in the request. |
| Secrets never leak | lib/clerk-admin.ts never logs or throws CLERK_SECRET_KEY; account-type mirror lives in privateMetadata, never the session JWT. |
| Multi-account isolation | No-store + Vary: Cookie on authenticated responses; every account transition is a hard full-document navigation; admission is re-checked server-side on each gated render. |
See /partners/rbac for the account-type capability matrix, /partners/access-requests for the /approval screen and approval saga, and /partners/salesforce for status resolution.