From 70706baa78f78105d2c0dae32e00d680628e2f74 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:41:34 +0000 Subject: [PATCH 01/26] feat(email): deliver-only template values never reach the stored mail row Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugins/plugin-email/src/email-service.ts | 27 ++++- .../send-template-deliver-only-34257.test.ts | 107 ++++++++++++++++++ packages/spec/src/contracts/email-service.ts | 17 +++ 3 files changed, 148 insertions(+), 3 deletions(-) create mode 100644 packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts diff --git a/packages/plugins/plugin-email/src/email-service.ts b/packages/plugins/plugin-email/src/email-service.ts index 43914f4da38..a5ad24035df 100644 --- a/packages/plugins/plugin-email/src/email-service.ts +++ b/packages/plugins/plugin-email/src/email-service.ts @@ -963,7 +963,18 @@ export class EmailService implements IEmailService { return this.sendInternal(input, false); } - private async sendInternal(input: SendEmailInput, allowQueue: boolean): Promise { + /** + * `delivered`, when given, holds the faces the recipient receives in place + * of the stored row's (`SendTemplateInput.deliverOnly`): the row is written + * from `input`, the transport is handed `delivered`, and the send is inline, + * because the queue delivers from the row. + */ + private async sendInternal( + input: SendEmailInput, + allowQueue: boolean, + delivered?: RenderTemplateResult, + ): Promise { + if (delivered) allowQueue = false; let normalized: NormalizedEmailMessage; try { assertIdentityMailCarriesNoOrganization(input); @@ -1141,7 +1152,10 @@ export class EmailService implements IEmailService { // failed, or queue mode is off for this send): the in-memory message is // still whole, so the mail goes out — and the content still has to be // reclaimed afterwards, which is why the keys travel with the delivery. - return await this.deliverNormalized(id, normalized, undefined, storageKeys, object); + const outgoing: NormalizedEmailMessage = delivered + ? { ...normalized, subject: delivered.subject, html: delivered.html, text: delivered.text } + : normalized; + return await this.deliverNormalized(id, outgoing, undefined, storageKeys, object); } finally { // Release EXACTLY what was reserved above — the one id, and only here. // Here and not earlier: the reservation has to outlive the whole body, @@ -1837,6 +1851,13 @@ export class EmailService implements IEmailService { async sendTemplate(input: SendTemplateInput): Promise { const { row, rendered } = await this.resolveAndRenderTemplate(input); const { subject, html, text } = rendered; + // Deliver-only values reach the recipient and never the stored row: the + // row is written from the faces rendered above, from `data` alone, and the + // transport gets the faces rendered from `data` overlaid with them. + const deliverOnly = input.deliverOnly; + const delivered = deliverOnly && Object.keys(deliverOnly).length > 0 + ? (await this.resolveAndRenderTemplate({ ...input, data: { ...(input.data || {}), ...deliverOnly } })).rendered + : undefined; const from: EmailAddress | undefined = input.from ?? (row.from_address @@ -1866,6 +1887,6 @@ export class EmailService implements IEmailService { // `sys_identity_email`. `send()` refuses the two together. ...(input.identityMail ? { identityMail: true } : {}), }; - return this.send(sendInput); + return delivered ? this.sendInternal(sendInput, false, delivered) : this.send(sendInput); } } diff --git a/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts b/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts new file mode 100644 index 00000000000..8abaa4c5b85 --- /dev/null +++ b/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts @@ -0,0 +1,107 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// `SendTemplateInput.deliverOnly`: values delivered with the message and never +// written to the stored mail row. + +import { describe, it, expect } from 'vitest'; +import type { IQueueService, NormalizedEmailMessage, TransportSendResult } from '@objectstack/spec/contracts'; +import { EmailService, type EmailTemplateRow, type TemplateLoader } from './email-service.js'; + +const TEMPLATE: EmailTemplateRow = { + name: 'auth.invitation', + locale: 'en-US', + subject: 'Join {{orgName}}', + body_html: '

Join {{orgName}}: accept

', + body_text: 'Join {{orgName}}: {{acceptUrl}}', + active: true, + variables_json: JSON.stringify([{ name: 'acceptUrl', required: true }]), +}; + +const PLAIN_URL = 'https://app.example.com/accept-invitation/inv_1'; +const DELIVERED_URL = `${PLAIN_URL}#proof=DELIVERONLYVALUE`; + +function loader(): TemplateLoader { + return { async load(name) { return name === TEMPLATE.name ? TEMPLATE : null; } }; +} + +function setup(withQueue = false) { + const sent: NormalizedEmailMessage[] = []; + const rows = new Map>(); + const published: unknown[] = []; + const queue = { + async publish(_q: string, data: unknown) { published.push(data); return 'job-1'; }, + async subscribe() {}, + async unsubscribe() {}, + } as unknown as IQueueService; + const svc = new EmailService({ + transport: { + async send(message: NormalizedEmailMessage): Promise { + sent.push(message); + return { messageId: `m-${sent.length}` }; + }, + }, + defaultFrom: { address: 'no-reply@example.com' }, + templateLoader: loader(), + persistence: { + async insert(row) { rows.set(row.id, { ...row }); return { id: row.id }; }, + async update(id, patch) { const cur = rows.get(id); if (cur) rows.set(id, { ...cur, ...patch }); }, + }, + ...(withQueue + ? { queueDelivery: { resolve: () => queue, maxAttempts: 1, backoff: { type: 'exponential' as const, delayMs: 1000, maxDelayMs: 1000 } } } + : {}), + }); + return { svc, sent, rows, published }; +} + +const storedText = (row: Record | undefined) => + JSON.stringify({ subject: row?.subject, body_text: row?.body_text, body_html: row?.body_html }); + +describe('deliver-only template values (#34257)', () => { + it('the recipient receives the deliver-only values and the stored mail row never holds them', async () => { + const { svc, sent, rows } = setup(); + const res = await svc.sendTemplate({ + template: 'auth.invitation', + to: 'invitee@example.com', + data: { orgName: 'Acme', acceptUrl: PLAIN_URL }, + deliverOnly: { acceptUrl: DELIVERED_URL }, + }); + + expect(res.status).toBe('sent'); + expect(sent).toHaveLength(1); + expect(sent[0]!.text).toContain(DELIVERED_URL); + expect(sent[0]!.html).toContain(DELIVERED_URL); + + const row = rows.get(res.id); + expect(row?.status).toBe('sent'); + expect(row?.body_text).toContain(PLAIN_URL); + expect(storedText(row)).not.toContain('DELIVERONLYVALUE'); + }); + + it('a send carrying deliver-only values is delivered inline even when queue delivery is wired', async () => { + const { svc, sent, rows, published } = setup(true); + const res = await svc.sendTemplate({ + template: 'auth.invitation', + to: 'invitee@example.com', + data: { orgName: 'Acme', acceptUrl: PLAIN_URL }, + deliverOnly: { acceptUrl: DELIVERED_URL }, + }); + + expect(res.status).toBe('sent'); + expect(published).toHaveLength(0); + expect(sent[0]!.text).toContain(DELIVERED_URL); + expect(storedText(rows.get(res.id))).not.toContain('DELIVERONLYVALUE'); + }); + + it('a send without deliver-only values keeps its delivery mode and records what it delivered', async () => { + const { svc, rows, published } = setup(true); + const res = await svc.sendTemplate({ + template: 'auth.invitation', + to: 'invitee@example.com', + data: { orgName: 'Acme', acceptUrl: PLAIN_URL }, + }); + + expect(res.status).toBe('queued'); + expect(published).toHaveLength(1); + expect(rows.get(res.id)?.body_text).toContain(PLAIN_URL); + }); +}); diff --git a/packages/spec/src/contracts/email-service.ts b/packages/spec/src/contracts/email-service.ts index 378fdb20d74..3418b40c750 100644 --- a/packages/spec/src/contracts/email-service.ts +++ b/packages/spec/src/contracts/email-service.ts @@ -191,6 +191,23 @@ export interface SendTemplateInput { to: EmailAddress | EmailAddress[]; /** Render context — placeholders in subject/body are resolved against this object. */ data?: Record; + /** + * Deliver-only render values: delivered with the message and never written + * to the stored mail row. + * + * The message the recipient receives renders `data` overlaid with these + * values. The stored row (`sys_email` / `sys_identity_email`) records the + * message rendered from `data` alone, so a hole present in both reads the + * `data` value in the row. A send carrying any deliver-only value is + * delivered inline, never through the durable queue: the queue delivers + * from the stored row, which does not hold them. A message re-delivered from + * its stored row carries the row's faces. + * + * Only this server-side template send declares it; the caller-facing mail + * doors (`POST /email/send`, a script body's `ctx.email.send`) take a + * {@link SendEmailInput}, which has no such member. + */ + deliverOnly?: Record; /** * Preferred BCP-47 locale (e.g. user's locale). * From cca46794ac73800429eab0e1b45f1e385aaea607 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:55:09 +0000 Subject: [PATCH 02/26] feat(auth): the invitation mail carries a mailbox proof that one door redeems in one step Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/auth-manager-before-hook.ts | 4 +- .../src/auth-manager-organization-plugin.ts | 30 ++ .../src/auth-manager-plugin-list.ts | 25 ++ .../plugins/plugin-auth/src/auth-manager.ts | 3 + .../plugins/plugin-auth/src/auth-plugin.ts | 1 + .../plugin-auth/src/auth-route-ledger.ts | 2 + .../src/invitation-mailbox-proof.ts | 351 ++++++++++++++++++ 7 files changed, 415 insertions(+), 1 deletion(-) create mode 100644 packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index e54b5de9f1e..de6e1dbe145 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -58,6 +58,7 @@ * Nothing re-exports this module, so the published surface does not move. */ +import { ACCEPT_INVITATION_WITH_PROOF_PATH } from './invitation-mailbox-proof.js'; import { isCloudManaged } from '@objectstack/core'; import { VENDOR_ROLE_SCALAR_ADMIN_PATHS } from './admin-impersonate-endpoint.js'; import { setAuthActorResolver } from './auth-actor-attribution.js'; @@ -335,7 +336,8 @@ export async function globalBeforeHook( if ( ctx?.path === '/sign-up/email' || ctx?.path === '/reset-password' || - ctx?.path === '/change-password' + ctx?.path === '/change-password' || + ctx?.path === ACCEPT_INVITATION_WITH_PROOF_PATH ) { const candidate = (typeof ctx?.body?.password === 'string' && ctx.body.password) || diff --git a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts index ab8982aff05..3ea7ea644dd 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts @@ -60,6 +60,7 @@ * Nothing re-exports this module, so the published surface does not move. */ +import { mintInvitationProof, withInvitationProof } from './invitation-mailbox-proof.js'; import type { OrganizationOptions } from 'better-auth/plugins/organization'; import { isCloudManaged } from '@objectstack/core'; import { MEMBERSHIP_ROLE_DELEGATED_ADMIN, MEMBERSHIP_ROLE_EXTERNAL } from '@objectstack/spec'; @@ -647,11 +648,18 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { if (this.config.logger) this.config.logger.warn(msg, meta); else console.warn(msg, meta); } + // [#34257] The mail's link carries the invitation's mailbox proof; the + // copied link and the stored mail row never do. Minted only for a send + // that goes out; one that cannot be minted goes out as today's link. + const proof = expiry.expiresAt === undefined + ? undefined + : await mintProofForSend({ id: String(invitation.id), email: recipientEmail, expiresAt: invitation.expiresAt }); try { await emailService.sendTemplate({ template: 'auth.invitation', to: recipientEmail, ...mailLocale, + ...(proof ? { deliverOnly: { acceptUrl: withInvitationProof(acceptUrl, proof) } } : {}), data: { inviter: { name: inviter?.user?.name ?? inviter?.user?.email ?? 'A teammate', @@ -736,6 +744,28 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { * than rendered as `Invalid Date`; the template declares the variable * required, so that send is refused rather than sent with a dangling sentence. */ +/** + * Mint the invitation's mailbox proof through the verification store of the + * request that sends the mail (better-auth calls `sendInvitationEmail` inside + * invite-member, a resend included). No endpoint context, or a store that + * refuses the write: no proof, and the mail carries today's link. + */ +async function mintProofForSend(invitation: { id: string; email: string; expiresAt: unknown }): Promise { + try { + const { getCurrentAuthEndpointContext } = await import('@better-auth/core/context'); + const ctx: any = getCurrentAuthEndpointContext(); + const store = ctx?.context?.internalAdapter; + if (!store) return undefined; + return await mintInvitationProof(store, invitation); + } catch (err: any) { + console.warn( + `[AuthManager] invitation mail: no mailbox proof for invitation '${invitation.id}' (${err?.message ?? err}); ` + + 'the mail carries the accept link without it', + ); + return undefined; + } +} + function invitationExpiryArg(expiresAt: unknown): { expiresAt?: string } { if (!(expiresAt instanceof Date) && typeof expiresAt !== 'string' && typeof expiresAt !== 'number') return {}; const instant = new Date(expiresAt); diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index 9761d0ccf1a..09d6cf3c4a8 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -64,6 +64,7 @@ import { resolveUserAuthzGrants } from '@objectstack/core'; import { applyPlatformAdminImpersonation } from './admin-impersonate-endpoint.js'; import { requireSecondFactorAtCodeAndLinkDoors } from './second-factor-code-and-link-doors.js'; import { buildOrganizationPlugin, type OrganizationPluginHost } from './auth-manager-organization-plugin.js'; +import { ACCEPT_INVITATION_WITH_PROOF_PATH, buildInvitationProofDoorPlugin } from './invitation-mailbox-proof.js'; import { OAUTH_ORGANIZATION_CLAIM, assertScimAdminCoherence, @@ -121,7 +122,9 @@ export interface PluginListHost { getDataEngine: AuthManager['getDataEngine']; getEmailService: AuthManager['getEmailService']; getMcpResourceUrl: AuthManager['getMcpResourceUrl']; + getApi: AuthManager['getApi']; isPlatformAdminUserId: AuthManager['isPlatformAdminUserId']; + isSsoOnlyMode: AuthManager['isSsoOnlyMode']; jwtSigningFailureReported: AuthManager['jwtSigningFailureReported']; multiOrgPostureEffective: AuthManager['multiOrgPostureEffective']; orgRolesMap: AuthManager['orgRolesMap']; @@ -130,6 +133,7 @@ export interface PluginListHost { resolveMembershipRole: AuthManager['resolveMembershipRole']; resolveTwoFactorAccountLockout: AuthManager['resolveTwoFactorAccountLockout']; storedRecipientLocale: AuthManager['storedRecipientLocale']; + validateAudienceAdmission: AuthManager['validateAudienceAdmission']; } /** @@ -276,6 +280,15 @@ export async function buildPluginList(this: PluginListHost): Promise { }; return buildOrganizationPlugin.call(host); }); + // [#34257] The one-step acceptance door for the invitation mail's mailbox + // proof (`invitation-mailbox-proof.ts`), beside the plugin it accepts through. + plugins.push(await buildInvitationProofDoorPlugin({ + getApi: () => this.getApi(), + validateAudienceAdmission: (...a) => this.validateAudienceAdmission(...(a as Parameters)), + isSsoOnlyMode: () => this.isSsoOnlyMode(), + getDataEngine: () => this.getDataEngine(), + counterStore: () => this.config.sharedCounterStore?.() ?? Promise.reject(new Error('no shared counter store')), + })); } if (enabled.twoFactor) { @@ -301,6 +314,18 @@ export async function buildPluginList(this: PluginListHost): Promise { if (enabled.passwordRejectBreached) { const { haveIBeenPwned } = await import('better-auth/plugins/haveibeenpwned'); plugins.push(haveIBeenPwned({ + // The plugin's own default doors, plus the invitation proof door, which + // sets a password too. + paths: [ + '/sign-up/email', + '/change-password', + '/reset-password', + '/email-otp/reset-password', + '/phone-number/reset-password', + '/admin/create-user', + '/admin/set-user-password', + ACCEPT_INVITATION_WITH_PROOF_PATH, + ], customPasswordCompromisedMessage: 'This password has appeared in a known data breach. Please choose a different one.', })); diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 26461f3f794..00ea36e6260 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -2436,7 +2436,9 @@ export class AuthManager { getDataEngine: (...a) => this.getDataEngine(...a), getEmailService: (...a) => this.getEmailService(...a), getMcpResourceUrl: (...a) => this.getMcpResourceUrl(...a), + getApi: (...a) => this.getApi(...a), isPlatformAdminUserId: (...a) => this.isPlatformAdminUserId(...a), + isSsoOnlyMode: (...a) => this.isSsoOnlyMode(...a), get jwtSigningFailureReported() { return readJwtSigningFailureReported(); }, set jwtSigningFailureReported(v) { writeJwtSigningFailureReported(v); }, multiOrgPostureEffective: (...a) => this.multiOrgPostureEffective(...a), @@ -2447,6 +2449,7 @@ export class AuthManager { resolveMembershipRole: (...a) => this.resolveMembershipRole(...a), resolveTwoFactorAccountLockout: (...a) => this.resolveTwoFactorAccountLockout(...a), storedRecipientLocale: (...a) => this.storedRecipientLocale(...a), + validateAudienceAdmission: (...a) => this.validateAudienceAdmission(...a), }; return buildPluginList.call(host); } diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index ea11e122e3d..fd77a75ba04 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -2760,6 +2760,7 @@ export class AuthPlugin implements Plugin { '/sign-up/email': { window, max }, '/request-password-reset': { window, max }, '/reset-password': { window, max }, + '/organization/accept-invitation-with-proof': { window, max }, // #2780 — OTP endpoints cost an SMS per hit (pumping abuse); // the per-number cooldown (otp-send-guard.ts) is always on, // this adds the operator-tuned per-IP dimension. The plugin diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 3e1d13fe2b4..57e647010a0 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -299,6 +299,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ { route: 'POST /api/v1/auth/sys-oauth-application/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application create action posts it directly; session-required self-service wrapper over better-auth /oauth2/create-client that splits the Console\'s newline-separated redirect-URL textarea into the redirect_uris array the vendor schema requires' }, { route: 'POST /api/v1/auth/sys-session/revoke', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_session revoke_session row action posts it directly with the row id; the server resolves the session from the id, so the session token never travels to or from the console. The session owner is re-dispatched to better-auth /revoke-session; another user\'s session is revocable by a platform admin only (ADR-0068 D2), tombstoned with reason admin (ADR-0069 D4)' }, { route: 'POST /api/v1/auth/organization/accept-invitation', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.invitations.accept', requires: 'organization' }, + { route: 'POST /api/v1/auth/organization/accept-invitation-with-proof', family: 'organization', source: 'better-auth', disposition: 'public', requires: 'organization', note: 'the one-step invitation acceptance (invitation-mailbox-proof.ts): an ObjectStack endpoint on the catch-all, answering a caller with NO session that presents the mailbox proof only the invitation mail carries. With a valid proof it creates the account (or sets the password of an unverified one with no linked provider account, revoking its sessions), marks the address verified, accepts through the vendor accept route and signs the person in; an address with an account the one-step path does not touch answers outcome sign_in, unspent. Every proof that does not admit answers one 400 INVALID_TOKEN. Single-use, bound to the invitation, its address and its expiry; rate-limited per address and per invitation. Without a proof it serves a signed-in session whose address is the invited one and verified. The vendor accept route is unchanged' }, // #9941 — better-auth declares `addMember` with NO HTTP path (server-only // `auth.api.addMember`; measured on the installed 1.7.1), so the catch-all // never publishes it and it is correctly ABSENT from @@ -480,6 +481,7 @@ export const BETTER_AUTH_MOUNTED_SURFACE: readonly string[] = [ 'POST /api/v1/auth/oauth2/update-consent', 'POST /api/v1/auth/oauth2/userinfo', 'POST /api/v1/auth/organization/accept-invitation', + 'POST /api/v1/auth/organization/accept-invitation-with-proof', 'POST /api/v1/auth/organization/add-team-member', 'POST /api/v1/auth/organization/cancel-invitation', 'POST /api/v1/auth/organization/check-slug', diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts new file mode 100644 index 00000000000..e5d79003aa4 --- /dev/null +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -0,0 +1,351 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The invitation mail's mailbox proof, and the one-step door that redeems it. + * + * ## The rule + * + * Holding an invitation's accept link proves nothing about the invited + * mailbox. The link is the invitation's id and nothing more: + * `copy_invitation_link` answers it, and the invitation row carries it. What + * proves the mailbox is a secret that only the invitation mail carries, the + * proof. A person who holds the proof may, in one request, create the account + * (or set the password of an unverified one), have the address marked + * verified, accept the invitation and be signed in. A person who holds only + * the link keeps today's path: sign in, or register and verify by mail. + * + * ## The proof + * + * - Minted by `sendInvitationEmail` for each send, a resend included, and put + * in the mail's link only, after `#`, as `proof=VALUE` + * ({@link withInvitationProof}). The mail goes out through + * `SendTemplateInput.deliverOnly`, so the stored mail row never holds it. + * - Never at rest in clear. One `sys_verification` row per invitation, + * identifier {@link invitationProofIdentifier}, holds the proof's SHA-256, + * the invited address and the invitation's expiry, with the invitation's + * expiry as the row's own. Written and read through better-auth's internal + * adapter, so a host `secondaryStorage` is honoured as for every other + * verification value. + * - Bound to the invitation, its address and its expiry: the door requires + * all three to match the invitation as it stands. + * - Single-use: spent by the internal adapter's atomic consume, before any + * side effect. A proof that does not match is not spent. + * - A resend retires the old proof: the mint deletes the invitation's row + * before writing the new one. + * + * ## The door — `POST /organization/accept-invitation-with-proof` + * + * Body `{ invitationId, proof, name, password }`, or `{ invitationId }` alone + * from a signed-in session (the social return). Answers: + * + * - `{ outcome: 'accepted', organizationId }` — the invitation is accepted and + * the caller is signed in. + * - `{ outcome: 'sign_in' }` — the proof is good, and the address has an + * account the one-step path does not set a password on (verified, linked to + * a provider, second factor enrolled, or managed by an identity provider). + * The proof is not spent; the person signs in as today. + * - `{ outcome: 'verify_email' }` — session mode, and the session's address is + * not verified. Nothing is accepted. + * - `400 INVALID_TOKEN` — any proof that does not admit: unknown, used, + * expired, for another invitation or address, or an invitation that is no + * longer pending. One answer, which does not say which check failed. + * + * An unverified account with no linked provider account gets the typed + * password in place of its own, and every one of its sessions is revoked, as a + * password reset does. A new account is created through the internal adapter, + * so the sign-up gates that run on every creation (audience admission and the + * database hooks) run here too; the door itself refuses where email sign-up is + * off. The invitation is accepted through better-auth's own accept route, so + * every organization hook runs. + * + * Rate-limited per client address and per invitation, always armed. + */ + +import { incrementFixedWindow, InProcessCounterStore, type CounterStore } from './rate-limit-storage.js'; +import { readRequestClientAddress } from './request-client-address.js'; +import { isPendingSsoSource } from './pending-sso-marker.js'; +import { isIdpProvisionedSource, readUserSource } from './sso-only-local-password.js'; + +/** The door's path, under the auth mount. */ +export const ACCEPT_INVITATION_WITH_PROOF_PATH = '/organization/accept-invitation-with-proof'; + +/** The fragment key the mail's link carries the proof under. */ +export const INVITATION_PROOF_FRAGMENT_KEY = 'proof'; + +/** Per client address and per invitation, each its own window. */ +export const INVITATION_PROOF_RATE_LIMIT = { window: 60, max: 10 } as const; + +const IDENTIFIER_PREFIX = 'invitation-proof:'; + +/** The `sys_verification` identifier of an invitation's proof row. */ +export function invitationProofIdentifier(invitationId: string): string { + return `${IDENTIFIER_PREFIX}${invitationId}`; +} + +/** The mail's accept link: the copied link, with the proof after `#`. */ +export function withInvitationProof(acceptUrl: string, proof: string): string { + return `${acceptUrl}#${INVITATION_PROOF_FRAGMENT_KEY}=${encodeURIComponent(proof)}`; +} + +/** The internal-adapter members the proof reads and writes. */ +export interface InvitationProofStore { + createVerificationValue(data: { identifier: string; value: string; expiresAt: Date }): Promise; + findVerificationValue(identifier: string): Promise<{ value: string; expiresAt: Date | string } | null>; + consumeVerificationValue(identifier: string): Promise<{ value: string; expiresAt: Date | string } | null>; + deleteVerificationByIdentifier(identifier: string): Promise; +} + +interface StoredProof { + /** SHA-256 of the proof, base64url. */ + h: string; + /** The invited address, lowercased. */ + email: string; + /** The invitation's expiry, ISO-8601. */ + exp: string; +} + +async function sha256(value: string): Promise { + const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); + return Buffer.from(new Uint8Array(digest)).toString('base64url'); +} + +function isoOf(value: unknown): string | undefined { + if (!(value instanceof Date) && typeof value !== 'string' && typeof value !== 'number') return undefined; + const ms = new Date(value).getTime(); + return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined; +} + +function parseStored(value: unknown): StoredProof | undefined { + if (typeof value !== 'string') return undefined; + try { + const parsed = JSON.parse(value) as Partial; + if (typeof parsed?.h !== 'string' || typeof parsed.email !== 'string' || typeof parsed.exp !== 'string') return undefined; + return { h: parsed.h, email: parsed.email, exp: parsed.exp }; + } catch { + return undefined; + } +} + +/** + * Mint the proof for one invitation send, retiring any earlier one. Answers + * the proof, or `undefined` when the invitation's expiry is unreadable (no + * proof is minted for an invitation with no expiry to bind it to). + */ +export async function mintInvitationProof( + store: InvitationProofStore, + invitation: { id: string; email: string; expiresAt: unknown }, +): Promise { + const exp = isoOf(invitation.expiresAt); + if (!exp || !invitation.id || !invitation.email) return undefined; + const { generateRandomString } = await import('better-auth/crypto'); + const proof = generateRandomString(32, 'a-z', 'A-Z', '0-9'); + const identifier = invitationProofIdentifier(invitation.id); + await store.deleteVerificationByIdentifier(identifier); + const stored: StoredProof = { h: await sha256(proof), email: invitation.email.toLowerCase(), exp }; + await store.createVerificationValue({ identifier, value: JSON.stringify(stored), expiresAt: new Date(exp) }); + return proof; +} + +/** Does `stored` admit `proof` for this invitation as it stands? */ +async function admits( + stored: StoredProof | undefined, + proof: string, + invitation: { email: string; expiresAt: unknown }, +): Promise { + if (!stored) return false; + const { constantTimeEqual } = await import('better-auth/crypto'); + const hashMatches = constantTimeEqual(await sha256(proof), stored.h); + return hashMatches && stored.email === invitation.email.toLowerCase() && stored.exp === isoOf(invitation.expiresAt); +} + +/** What the door needs from the manager. */ +export interface InvitationProofDoorHost { + /** better-auth's API, for its own accept route. */ + getApi(): Promise; + /** The audience gate every account creation passes (`AuthManager#validateAudienceAdmission`). */ + validateAudienceAdmission( + data: { user?: Record; source?: { action?: string; method?: string } }, + ctx?: unknown, + ): Promise<{ error: string; errorDescription?: string } | undefined>; + /** SSO-only mode: no local password is set. */ + isSsoOnlyMode(): boolean; + /** The data engine, for the account's directory source. */ + getDataEngine(): unknown; + /** The shared counter store, when one is wired. */ + counterStore?: () => Promise; +} + +const FALLBACK_COUNTERS = new InProcessCounterStore(); + +const INVALID_PROOF_MESSAGE = + 'This invitation link cannot be used to join. Open the latest invitation email, or sign in to accept the invitation.'; + +function nonEmpty(value: unknown): string | undefined { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined; +} + +/** + * Build the better-auth plugin that mounts the door. The vendor modules are + * imported lazily, as the other endpoint builders here import them. + */ +export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHost): Promise { + const [{ createAuthEndpoint, APIError, getSessionFromCtx }, { setSessionCookie }] = await Promise.all([ + import('better-auth/api'), + import('better-auth/cookies'), + ]); + + const refuseProof = (): never => { + throw new APIError('BAD_REQUEST', { code: 'INVALID_TOKEN', message: INVALID_PROOF_MESSAGE }); + }; + + const rateLimit = async (keys: string[]) => { + let store: CounterStore = FALLBACK_COUNTERS; + try { + store = (await host.counterStore?.()) ?? FALLBACK_COUNTERS; + } catch { + store = FALLBACK_COUNTERS; + } + for (const key of keys) { + const { count, resetAt } = await incrementFixedWindow(store, key, INVITATION_PROOF_RATE_LIMIT.window); + if (count > INVITATION_PROOF_RATE_LIMIT.max) { + throw new APIError('TOO_MANY_REQUESTS', { + code: 'RATE_LIMITED', + message: `Too many attempts. Try again in ${Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))} seconds.`, + }); + } + } + }; + + const acceptAs = async (sessionToken: string, invitationId: string) => { + const api = await host.getApi(); + await api.acceptInvitation({ + body: { invitationId }, + headers: new Headers({ authorization: `Bearer ${sessionToken}` }), + }); + }; + + const endpoint = createAuthEndpoint( + ACCEPT_INVITATION_WITH_PROOF_PATH, + { method: 'POST' }, + async (ctx: any) => { + const body = (ctx.body ?? {}) as Record; + const invitationId = nonEmpty(body.invitationId); + const proof = nonEmpty(body.proof); + + const address = (await readRequestClientAddress()) ?? 'unknown'; + await rateLimit([ + `invitation-proof:addr:${address}`, + ...(invitationId ? [`invitation-proof:inv:${invitationId}`] : []), + ]); + + if (!invitationId) return refuseProof(); + const invitation: any = await ctx.context.adapter.findOne({ + model: 'invitation', + where: [{ field: 'id', value: invitationId }], + }); + const pending = + invitation && + invitation.status === 'pending' && + typeof invitation.email === 'string' && + new Date(invitation.expiresAt).getTime() > Date.now(); + + // ── Session mode: the social return ──────────────────────────────── + if (!proof) { + const session = await getSessionFromCtx(ctx); + if (!session) throw new APIError('UNAUTHORIZED', { code: 'UNAUTHENTICATED', message: 'Sign in to accept the invitation.' }); + if (!pending) return refuseProof(); + const sameAddress = String(session.user.email).toLowerCase() === invitation.email.toLowerCase(); + if (!sameAddress || session.user.emailVerified !== true) return ctx.json({ outcome: 'verify_email' }); + await acceptAs(session.session.token, invitationId); + return ctx.json({ outcome: 'accepted', organizationId: invitation.organizationId }); + } + + // ── Proof mode ───────────────────────────────────────────────────── + if (!pending) return refuseProof(); + const identifier = invitationProofIdentifier(invitationId); + const internal = ctx.context.internalAdapter; + const stored = await internal.findVerificationValue(identifier); + if (!(await admits(parseStored(stored?.value), proof, invitation))) return refuseProof(); + + const email = invitation.email.toLowerCase(); + const found = await internal.findUserByEmail(email, { includeAccounts: true }); + const existing = found?.user; + if (existing) { + const linkedProvider = (found.accounts ?? []).some((a: any) => a?.providerId !== 'credential'); + const source = await readUserSource(host.getDataEngine() as never, String(existing.id)); + const directoryManaged = !source.ok || isPendingSsoSource(source.value) || isIdpProvisionedSource(source.value); + if ( + existing.emailVerified === true || + linkedProvider || + existing.twoFactorEnabled === true || + directoryManaged || + host.isSsoOnlyMode() || + !ctx.context.options.emailAndPassword?.enabled + ) { + return ctx.json({ outcome: 'sign_in' }); + } + } + + const password = typeof body.password === 'string' ? body.password : ''; + const passwordConfig = ctx.context.password.config; + if (password.length < passwordConfig.minPasswordLength) { + throw new APIError('BAD_REQUEST', { code: 'PASSWORD_TOO_SHORT', message: 'Password too short' }); + } + if (password.length > passwordConfig.maxPasswordLength) { + throw new APIError('BAD_REQUEST', { code: 'PASSWORD_TOO_LONG', message: 'Password too long' }); + } + const name = nonEmpty(body.name); + + if (!existing) { + const ep = ctx.context.options.emailAndPassword; + if (!ep?.enabled || ep.disableSignUp) { + throw new APIError('BAD_REQUEST', { + code: 'EMAIL_PASSWORD_SIGN_UP_DISABLED', + message: 'Email and password sign up is not enabled', + }); + } + if (!name) throw new APIError('BAD_REQUEST', { code: 'VALIDATION_ERROR', message: 'Enter your name.' }); + const refusal = await host.validateAudienceAdmission( + { user: { email }, source: { action: 'create-user', method: 'email-password' } }, + ctx, + ); + if (refusal) { + throw new APIError('FORBIDDEN', { code: refusal.error, message: refusal.errorDescription ?? refusal.error }); + } + } + + // Hashed before the proof is spent: a password the hash step refuses + // (a breached one) leaves the proof usable. + const passwordHash = await ctx.context.password.hash(password); + + const consumed = await internal.consumeVerificationValue(identifier); + if (!consumed || parseStored(consumed.value)?.h !== parseStored(stored?.value)?.h) return refuseProof(); + + let user: any; + if (!existing) { + user = await internal.createUser({ email, name, emailVerified: true }, { method: 'email-password' }); + await internal.linkAccount({ userId: user.id, providerId: 'credential', accountId: user.id, password: passwordHash }); + } else { + const userId = String(existing.id); + await internal.deleteUserSessions(userId); + if (await internal.findCredentialAccount(userId)) { + await internal.updatePassword(userId, passwordHash); + } else { + await internal.createAccount({ userId, providerId: 'credential', accountId: userId, password: passwordHash }); + } + user = await internal.updateUser(userId, { emailVerified: true, ...(name ? { name } : {}) }); + } + + const session = await internal.createSession(user.id, false); + if (!session) throw new APIError('INTERNAL_SERVER_ERROR', { code: 'INTERNAL_ERROR', message: 'Failed to create a session.' }); + await setSessionCookie(ctx, { session, user }); + await acceptAs(session.token, invitationId); + return ctx.json({ outcome: 'accepted', organizationId: invitation.organizationId }); + }, + ); + + return { + id: 'invitation-mailbox-proof', + endpoints: { acceptInvitationWithProof: endpoint }, + }; +} From ee8037c9019a05fc759b982087cd664d2a788275 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:03:23 +0000 Subject: [PATCH 03/26] test(auth): pin one-step invitation acceptance rules Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/invitation-mailbox-proof.ts | 11 +- ...vitation-one-step-acceptance-34257.test.ts | 431 ++++++++++++++++++ 2 files changed, 437 insertions(+), 5 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index e5d79003aa4..3e11a48241a 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -175,8 +175,6 @@ export interface InvitationProofDoorHost { counterStore?: () => Promise; } -const FALLBACK_COUNTERS = new InProcessCounterStore(); - const INVALID_PROOF_MESSAGE = 'This invitation link cannot be used to join. Open the latest invitation email, or sign in to accept the invitation.'; @@ -194,16 +192,19 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo import('better-auth/cookies'), ]); + // Per door instance: the window counts somewhere even with no shared store. + const fallbackCounters = new InProcessCounterStore(); + const refuseProof = (): never => { throw new APIError('BAD_REQUEST', { code: 'INVALID_TOKEN', message: INVALID_PROOF_MESSAGE }); }; const rateLimit = async (keys: string[]) => { - let store: CounterStore = FALLBACK_COUNTERS; + let store: CounterStore = fallbackCounters; try { - store = (await host.counterStore?.()) ?? FALLBACK_COUNTERS; + store = (await host.counterStore?.()) ?? fallbackCounters; } catch { - store = FALLBACK_COUNTERS; + store = fallbackCounters; } for (const key of keys) { const { count, resetAt } = await incrementFixedWindow(store, key, INVITATION_PROOF_RATE_LIMIT.window); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts new file mode 100644 index 00000000000..36af1e2c2b4 --- /dev/null +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -0,0 +1,431 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// #34257 — one-step invitation acceptance with a mailbox-only proof. +// +// The real better-auth pipeline through a real `AuthManager` (organization +// plugin, audience gate, membership reconciler, ObjectQL adapter), over the +// same minimal engine double the other end-to-end auth-manager suites use. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql'; +import { AuthManager } from './auth-manager'; +import { inviteForAudienceGate } from './audience-gate-test-support'; +import { createCopyInvitationLinkHandler } from './invitation-link-action'; +import { ACCEPT_INVITATION_WITH_PROOF_PATH } from './invitation-mailbox-proof'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; +const BASE = 'http://localhost:3000'; +const DEFAULT_ORG = 'org_default'; +const PARTNER_ORG = 'org_partner'; +const PASSWORD = 'S3cure!Passw0rd-34257'; +const NEW_PASSWORD = 'N3w!Passw0rd-34257x'; + +const createMemoryEngine = () => { + const tables = new Map(); + const rows = (name: string) => { + if (!tables.has(name)) tables.set(name, []); + return tables.get(name)!; + }; + const eq = (a: any, b: any) => + a instanceof Date || b instanceof Date + ? new Date(a as any).getTime() === new Date(b as any).getTime() + : a === b; + const matches = (row: any, where: Record = {}) => + Object.entries(where).every(([k, v]) => { + if (k === '$and' && Array.isArray(v)) return v.every((w) => matches(row, w)); + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + const actual = row[k]; + if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) { + if ('$ne' in v) return !eq(actual, v.$ne); + if ('$in' in v) return (v.$in as any[]).some((x) => eq(actual, x)); + if ('$gt' in v) return actual > v.$gt; + if ('$gte' in v) return actual >= v.$gte; + if ('$lt' in v) return actual < v.$lt; + if ('$lte' in v) return actual <= v.$lte; + } + return eq(actual, v); + }); + let seq = 0; + return { + tables, + async insert(name: string, data: any) { + const row = { id: data.id ?? `row_${++seq}`, ...data }; + rows(name).push(row); + return { ...row }; + }, + async findOne(name: string, q: any = {}) { + assertEngineFindOnePredicate(name, q); + const found = rows(name).find((r) => matches(r, q.where)); + return found ? { ...found } : null; + }, + async find(name: string, q: any = {}) { + let out = rows(name).filter((r) => matches(r, q.where)); + const order = q.orderBy?.[0]; + if (order) { + out = [...out].sort( + (a, b) => (a[order.field] > b[order.field] ? 1 : -1) * (order.order === 'desc' ? -1 : 1), + ); + } + if (q.offset) out = out.slice(q.offset); + if (q.limit) out = out.slice(0, q.limit); + return out.map((r) => ({ ...r })); + }, + async count(name: string, q: any = {}) { + return rows(name).filter((r) => matches(r, q.where)).length; + }, + async update(name: string, patch: any, options?: any) { + assertEngineUpdateDispatch(patch, options); + if (options?.multi) { + const hit = rows(name).filter((r) => matches(r, options.where)); + const { id: _ignored, ...fields } = patch; + for (const r of hit) Object.assign(r, fields); + return hit.length; + } + const row = rows(name).find((r) => r.id === patch.id); + if (!row) return null; + Object.assign(row, patch); + return { ...row }; + }, + async delete(name: string, q: any = {}) { + assertEngineDeleteDispatch(q); + const table = rows(name); + const keep = table.filter((r) => !matches(r, q.where)); + tables.set(name, keep); + return table.length - keep.length; + }, + }; +}; +type MemoryEngine = ReturnType; + +interface SentMail { + template: string; + to: string; + data: Record; + deliverOnly?: Record; +} + +const singleOrgTenancy = () => + ({ + posture: 'single', + requestedPosture: 'single', + isolationActive: false, + requested: false, + degraded: false, + defaultOrgId: async () => DEFAULT_ORG, + }) as any; + +const cookieFrom = (response: Response): string => + (response.headers.getSetCookie?.() ?? [response.headers.get('set-cookie') ?? '']) + .map((c) => c.split(';')[0]) + .filter(Boolean) + .join('; '); + +const post = (manager: AuthManager, path: string, body: unknown, cookie?: string) => + manager.handleRequest( + new Request(`${BASE}/api/v1/auth${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...(cookie ? { cookie } : {}) }, + body: JSON.stringify(body), + }), + ); + +const sessionUser = async (manager: AuthManager, cookie: string) => { + const res = await manager.handleRequest( + new Request(`${BASE}/api/v1/auth/get-session`, { headers: { cookie } }), + ); + const body: any = await res.json().catch(() => null); + return body?.user ?? null; +}; + +const signUp = async (manager: AuthManager, engine: MemoryEngine, email: string) => { + const invitationId = await inviteForAudienceGate(engine, email); + const res = await post(manager, '/sign-up/email', { email, password: PASSWORD, name: email, invitationId }); + expect(res.status, await res.clone().text()).toBe(200); + const user = (engine.tables.get('sys_user') ?? []).find((u) => u.email === email); + return { cookie: cookieFrom(res), userId: String(user!.id) }; +}; + +const userRow = (engine: MemoryEngine, email: string) => + (engine.tables.get('sys_user') ?? []).find((u) => u.email === email); + +const membersOf = (engine: MemoryEngine, organizationId: string, userId: string) => + (engine.tables.get('sys_member') ?? []).filter( + (m) => m.organization_id === organizationId && m.user_id === userId, + ); + +const invitationOf = (engine: MemoryEngine, email: string) => + (engine.tables.get('sys_invitation') ?? []).find( + (i) => i.email === email && i.organization_id === PARTNER_ORG, + ); + +const proofOf = (mail: SentMail): string => { + const link = String(mail.deliverOnly?.acceptUrl ?? ''); + const match = /#proof=([^&]+)$/.exec(link); + expect(match, `the mail's link carries no proof: ${link}`).not.toBeNull(); + return decodeURIComponent(match![1]!); +}; + +const boot = async () => { + const engine = createMemoryEngine(); + engine.tables.set('sys_organization', [ + { id: DEFAULT_ORG, name: 'Default', slug: 'default' }, + { id: PARTNER_ORG, name: 'Partner', slug: 'partner' }, + ]); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine as any, + membershipPolicy: 'auto', + getTenancy: () => singleOrgTenancy(), + }); + const sent: SentMail[] = []; + manager.setEmailService({ + sendTemplate: async (input: SentMail) => { + sent.push(input); + return { id: `mail_${sent.length}`, status: 'sent' }; + }, + } as never); + const owner = await signUp(manager, engine, 'owner@example.com'); + await engine.insert('sys_member', { id: 'mem_owner_partner', organization_id: PARTNER_ORG, user_id: owner.userId, role: 'owner' }); + const invite = async (email: string, resend = false) => { + const res = await post( + manager, + '/organization/invite-member', + { email, role: 'member', organizationId: PARTNER_ORG, ...(resend ? { resend: true } : {}) }, + owner.cookie, + ); + expect(res.status, await res.clone().text()).toBe(200); + const mail = [...sent].reverse().find((m) => m.template === 'auth.invitation' && m.to === email); + expect(mail, `no invitation mail to ${email}`).toBeDefined(); + return { invitation: invitationOf(engine, email)!, mail: mail!, proof: proofOf(mail!) }; + }; + return { engine, manager, owner, sent, invite }; +}; + +const door = (manager: AuthManager, body: Record, cookie?: string) => + post(manager, ACCEPT_INVITATION_WITH_PROOF_PATH, body, cookie); + +const expectRefused = async (res: Response) => { + const text = await res.clone().text(); + expect(res.status, text).toBe(400); + const body: any = JSON.parse(text); + expect(body.code).toBe('INVALID_TOKEN'); +}; + +describe('#34257 — the invitation mail carries a mailbox-only proof', () => { + beforeEach(() => { + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => vi.restoreAllMocks()); + + it('the mail delivers the proof only as a deliver-only value, never in the logged template data', async () => { + const { invite } = await boot(); + const { mail, proof } = await invite('invitee@example.com'); + expect(JSON.stringify(mail.data)).not.toContain(proof); + expect(String(mail.deliverOnly?.acceptUrl).startsWith(`${mail.data.acceptUrl}#`)).toBe(true); + }); + + it('the proof is never at rest in clear', async () => { + const { engine, invite } = await boot(); + const { proof } = await invite('invitee@example.com'); + const everyRow = JSON.stringify([...engine.tables.entries()]); + expect(everyRow).not.toContain(proof); + }); + + it('the copy action answers the link without the proof', async () => { + const { engine, manager, owner, invite } = await boot(); + const { invitation, mail, proof } = await invite('invitee@example.com'); + const handler = createCopyInvitationLinkHandler({ + engine: engine as never, + consoleUrl: (path) => manager.getConsoleUrl(path), + }); + const answer = await handler({ params: { recordId: String(invitation.id) }, session: { userId: owner.userId } }); + expect(answer.acceptUrl).not.toContain(proof); + expect(answer.acceptUrl).toBe(mail.data.acceptUrl); + }); +}); + +describe('#34257 — accepting with the proof', () => { + beforeEach(() => { + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => vi.restoreAllMocks()); + + it('the proof creates the account, verifies the address, accepts and signs in, in one request', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('newcomer@example.com'); + + const res = await door(manager, { invitationId: invitation.id, proof, name: 'Newcomer', password: PASSWORD }); + const text = await res.clone().text(); + expect(res.status, text).toBe(200); + expect(JSON.parse(text)).toMatchObject({ outcome: 'accepted', organizationId: PARTNER_ORG }); + + const user = userRow(engine, 'newcomer@example.com'); + expect(user?.email_verified).toBeTruthy(); + expect(invitationOf(engine, 'newcomer@example.com')?.status).toBe('accepted'); + expect(membersOf(engine, PARTNER_ORG, String(user!.id))).toHaveLength(1); + expect((await sessionUser(manager, cookieFrom(res)))?.email).toBe('newcomer@example.com'); + + const signIn = await post(manager, '/sign-in/email', { email: 'newcomer@example.com', password: PASSWORD }); + expect(signIn.status, await signIn.clone().text()).toBe(200); + }); + + it('a link without the proof neither verifies an address nor accepts for an unverified account', async () => { + const { engine, manager, invite } = await boot(); + const { invitation } = await invite('unverified@example.com'); + const holder = await signUp(manager, engine, 'unverified@example.com'); + + const res = await door(manager, { invitationId: invitation.id }, holder.cookie); + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toEqual({ outcome: 'verify_email' }); + + const anonymous = await door(manager, { invitationId: invitation.id, name: 'X', password: PASSWORD }); + expect(anonymous.status).toBe(401); + + expect(userRow(engine, 'unverified@example.com')?.email_verified).toBeFalsy(); + expect(invitationOf(engine, 'unverified@example.com')?.status).toBe('pending'); + }); + + it('a proof is single-use', async () => { + const { manager, invite } = await boot(); + const { invitation, proof } = await invite('once@example.com'); + const first = await door(manager, { invitationId: invitation.id, proof, name: 'Once', password: PASSWORD }); + expect(first.status, await first.clone().text()).toBe(200); + await expectRefused(await door(manager, { invitationId: invitation.id, proof, name: 'Once', password: PASSWORD })); + }); + + it('a proof that does not match is refused, creates nothing and leaves the real proof usable', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('guarded@example.com'); + await expectRefused( + await door(manager, { invitationId: invitation.id, proof: `${proof.slice(0, -1)}x`, name: 'G', password: PASSWORD }), + ); + expect(userRow(engine, 'guarded@example.com')).toBeUndefined(); + const good = await door(manager, { invitationId: invitation.id, proof, name: 'G', password: PASSWORD }); + expect(good.status, await good.clone().text()).toBe(200); + }); + + it("another invitation's proof is refused", async () => { + const { manager, invite } = await boot(); + const a = await invite('first@example.com'); + const b = await invite('second@example.com'); + await expectRefused(await door(manager, { invitationId: a.invitation.id, proof: b.proof, name: 'A', password: PASSWORD })); + }); + + it('a proof for an expired invitation is refused', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('late@example.com'); + invitationOf(engine, 'late@example.com')!.expires_at = new Date(Date.now() - 1000); + await expectRefused(await door(manager, { invitationId: invitation.id, proof, name: 'L', password: PASSWORD })); + expect(userRow(engine, 'late@example.com')).toBeUndefined(); + }); + + it('a resend retires the earlier proof', async () => { + const { manager, invite } = await boot(); + const first = await invite('again@example.com'); + const second = await invite('again@example.com', true); + expect(second.proof).not.toBe(first.proof); + await expectRefused(await door(manager, { invitationId: first.invitation.id, proof: first.proof, name: 'A', password: PASSWORD })); + const res = await door(manager, { invitationId: second.invitation.id, proof: second.proof, name: 'A', password: PASSWORD }); + expect(res.status, await res.clone().text()).toBe(200); + }); + + it('an unverified account gets the typed password in place of its own and loses every session', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('squatted@example.com'); + const earlier = await signUp(manager, engine, 'squatted@example.com'); + expect(await sessionUser(manager, earlier.cookie)).not.toBeNull(); + + const res = await door(manager, { invitationId: invitation.id, proof, name: 'Owner', password: NEW_PASSWORD }); + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toMatchObject({ outcome: 'accepted' }); + + expect(await sessionUser(manager, earlier.cookie)).toBeNull(); + expect(userRow(engine, 'squatted@example.com')?.email_verified).toBeTruthy(); + const oldPassword = await post(manager, '/sign-in/email', { email: 'squatted@example.com', password: PASSWORD }); + expect(oldPassword.status).not.toBe(200); + const newPassword = await post(manager, '/sign-in/email', { email: 'squatted@example.com', password: NEW_PASSWORD }); + expect(newPassword.status, await newPassword.clone().text()).toBe(200); + }); + + it('an unverified account with a linked provider account signs in as today, its password and the proof untouched', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('linked@example.com'); + const holder = await signUp(manager, engine, 'linked@example.com'); + await engine.insert('sys_account', { + id: 'acc_linked_google', + user_id: holder.userId, + provider_id: 'google', + account_id: 'google-sub-1', + }); + + const res = await door(manager, { invitationId: invitation.id, proof, name: 'L', password: NEW_PASSWORD }); + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toEqual({ outcome: 'sign_in' }); + + expect(await sessionUser(manager, holder.cookie)).not.toBeNull(); + expect(invitationOf(engine, 'linked@example.com')?.status).toBe('pending'); + const samePassword = await post(manager, '/sign-in/email', { email: 'linked@example.com', password: PASSWORD }); + expect(samePassword.status, await samePassword.clone().text()).toBe(200); + // Unspent: the same proof answers again. + const again = await door(manager, { invitationId: invitation.id, proof, name: 'L', password: NEW_PASSWORD }); + expect(await again.json()).toEqual({ outcome: 'sign_in' }); + }); + + it('the door is rate-limited per invitation', async () => { + const { manager, invite } = await boot(); + const { invitation } = await invite('limited@example.com'); + for (let i = 0; i < 10; i++) { + await expectRefused(await door(manager, { invitationId: invitation.id, proof: `wrong-${i}`, name: 'L', password: PASSWORD })); + } + const over = await door(manager, { invitationId: invitation.id, proof: 'wrong-x', name: 'L', password: PASSWORD }); + expect(over.status).toBe(429); + expect((await over.json()).code).toBe('RATE_LIMITED'); + }); + + it('a verified account signs in as today and the proof stays unspent', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('verified@example.com'); + await signUp(manager, engine, 'verified@example.com'); + userRow(engine, 'verified@example.com')!.email_verified = true; + + const res = await door(manager, { invitationId: invitation.id, proof, name: 'V', password: NEW_PASSWORD }); + expect(await res.json()).toEqual({ outcome: 'sign_in' }); + const again = await door(manager, { invitationId: invitation.id, proof, name: 'V', password: NEW_PASSWORD }); + expect(await again.json()).toEqual({ outcome: 'sign_in' }); + expect(invitationOf(engine, 'verified@example.com')?.status).toBe('pending'); + }); +}); + +describe('#34257 — a signed-in return accepts only a verified address', () => { + beforeEach(() => { + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => vi.restoreAllMocks()); + + it('a session whose invited address is verified accepts', async () => { + const { engine, manager, invite } = await boot(); + const { invitation } = await invite('social@example.com'); + const person = await signUp(manager, engine, 'social@example.com'); + userRow(engine, 'social@example.com')!.email_verified = true; + + const res = await door(manager, { invitationId: invitation.id }, person.cookie); + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toMatchObject({ outcome: 'accepted', organizationId: PARTNER_ORG }); + expect(membersOf(engine, PARTNER_ORG, person.userId)).toHaveLength(1); + }); + + it('a session whose address is not verified is asked to verify, and nothing is accepted', async () => { + const { engine, manager, invite } = await boot(); + const { invitation } = await invite('unsure@example.com'); + const person = await signUp(manager, engine, 'unsure@example.com'); + + const res = await door(manager, { invitationId: invitation.id }, person.cookie); + expect(await res.json()).toEqual({ outcome: 'verify_email' }); + expect(membersOf(engine, PARTNER_ORG, person.userId)).toHaveLength(0); + expect(invitationOf(engine, 'unsure@example.com')?.status).toBe('pending'); + }); +}); From 5e664ba494ef1ed263af9859218f8dd1a042fc7e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:07:51 +0000 Subject: [PATCH 04/26] fix(auth): the one-step door answers the standard rate-limit code Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts | 2 +- .../src/invitation-one-step-acceptance-34257.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 3e11a48241a..0bcad73fdd2 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -210,7 +210,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo const { count, resetAt } = await incrementFixedWindow(store, key, INVITATION_PROOF_RATE_LIMIT.window); if (count > INVITATION_PROOF_RATE_LIMIT.max) { throw new APIError('TOO_MANY_REQUESTS', { - code: 'RATE_LIMITED', + code: 'RATE_LIMIT_EXCEEDED', message: `Too many attempts. Try again in ${Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))} seconds.`, }); } diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 36af1e2c2b4..66b6f658d14 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -382,7 +382,7 @@ describe('#34257 — accepting with the proof', () => { } const over = await door(manager, { invitationId: invitation.id, proof: 'wrong-x', name: 'L', password: PASSWORD }); expect(over.status).toBe(429); - expect((await over.json()).code).toBe('RATE_LIMITED'); + expect((await over.json()).code).toBe('RATE_LIMIT_EXCEEDED'); }); it('a verified account signs in as today and the proof stays unspent', async () => { From e6df37951418d08c69a02a8ad25e61a36993b804 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:07:51 +0000 Subject: [PATCH 05/26] docs(adr): ADR-0138 notes the one-step invitation acceptance door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- ...principal-doors-grants-and-organization.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index 604633c07a0..a751e2383e1 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -300,6 +300,32 @@ under class 2, ahead of the allowlist, so it is judged as this door and not as c infrastructure. The same ruling's Q2 B leaves the verification posture as it was: an invitation-link sign-up still owes the verification mail. +**Amended 2026-11-16 — the one-step invitation acceptance, a class-2-shaped door.** Card +[#34257](https://github.com/objectstack-ai/objectstack/issues/34257), on the owning seat's rulings in +claim amendment +[`6906424686`](https://github.com/objectstack-ai/objectstack/issues/34257#issuecomment-6906424686), +admits one more door of class 2's shape, not a seventh class: +`POST /api/v1/auth/organization/accept-invitation-with-proof`. What admits the request: the mailbox +proof the invitation mail carries, a capability token minted per send. The invitation id alone, which +the copied link and the invitation row carry, admits nothing. What it runs as: after validation, the +creation of the invited address's account (or the replacement of the password of an unverified +account with no linked provider account, revoking its sessions), the address marked verified, the +invitation accepted through the vendor's own accept route, and a session for that account. The proof +is never at rest in clear, the stored mail row never holds it, and it is single-use and bound to the +invitation, its address and its expiry; a resend retires the old one. Every proof that does not admit +gets one refusal that does not say which check failed. An address whose account is verified, is +linked to a provider, or otherwise takes no password from this door is answered "sign in", with the +proof unspent. It carries a per-address and per-invitation rate limit, as ADR-0121 D6 requires. +Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, +ledgered in `packages/plugins/plugin-auth/src/auth-route-ledger.ts`; it sits in the `/auth` +namespace and is classified under class 2 the way the preview above is. + +This refines ruling [`6413975861`](https://github.com/objectstack-ai/objectstack/issues/26020#issuecomment-6413975861) +Q2 B, recorded above as "an invitation-link sign-up still owes the verification mail". A +proof-carrying invitation link proves the mailbox, so a sign-up through it owes no verification mail. +A copied link, which carries no proof, still owes the verification mail, as Q2 B states. The vendor +accept route is unchanged by this note. + **Outside the guest model by construction**, and not on the list: - the control-plane allowlist (`packages/core/src/security/auth-gate.ts#isAuthGateAllowlisted`: From be7d4b05d57c830a9e1a1aa907e4225cca1fb3f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:07:51 +0000 Subject: [PATCH 06/26] feat(ui-auth): the auth client redeems an invitation in one step Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- ui/packages/auth/src/AuthContext.ts | 4 +- ui/packages/auth/src/AuthProvider.tsx | 11 +++- .../acceptInvitationWithProof-34257.test.ts | 59 +++++++++++++++++++ ui/packages/auth/src/createAuthClient.ts | 29 ++++++++- ui/packages/auth/src/index.ts | 2 + ui/packages/auth/src/types.ts | 27 +++++++++ ui/packages/auth/src/useAuth.ts | 1 + 7 files changed, 129 insertions(+), 4 deletions(-) create mode 100644 ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts diff --git a/ui/packages/auth/src/AuthContext.ts b/ui/packages/auth/src/AuthContext.ts index f2c3737facb..2a11da7c9db 100644 --- a/ui/packages/auth/src/AuthContext.ts +++ b/ui/packages/auth/src/AuthContext.ts @@ -7,7 +7,7 @@ */ import { createContext } from 'react'; -import type { AuthUser, AuthClientSession, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, SignInWithProviderOptions, DelegableScope, TwoFactorChallenge, SignInTwoFactorCodeKind } from './types.js'; +import type { AuthUser, AuthClientSession, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationProofInput, AuthInvitationProofOutcome, AuthPublicConfig, SignInWithProviderOptions, DelegableScope, TwoFactorChallenge, SignInTwoFactorCodeKind } from './types.js'; export interface AuthContextValue { /** Current authenticated user */ @@ -257,6 +257,8 @@ export interface AuthContextValue { getInvitationPreview: (invitationId: string) => Promise; /** Accept an invitation as the current user */ acceptInvitation: (invitationId: string) => Promise; + /** The one-step invitation acceptance (see `AuthClient.acceptInvitationWithProof`). */ + acceptInvitationWithProof: (input: AuthInvitationProofInput) => Promise; /** Reject an invitation as the current user */ rejectInvitation: (invitationId: string) => Promise; /** List invitations addressed to the current user */ diff --git a/ui/packages/auth/src/AuthProvider.tsx b/ui/packages/auth/src/AuthProvider.tsx index bd5457f9889..4201fd6510a 100644 --- a/ui/packages/auth/src/AuthProvider.tsx +++ b/ui/packages/auth/src/AuthProvider.tsx @@ -10,7 +10,7 @@ import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react' import { authGateEvents } from './auth-gate-events.js'; import { sessionEndEvents } from './session-end-events.js'; import { runBeforeSignOut } from './beforeSignOut.js'; -import type { AuthUser, AuthClient, AuthProviderOptions, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge } from './types.js'; +import type { AuthUser, AuthClient, AuthProviderOptions, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationProofInput, AuthInvitationProofOutcome, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge } from './types.js'; import { TWO_FACTOR_CHALLENGE_ENDED_CODES } from './two-factor-codes.js'; import { AuthCtx, type AuthContextValue } from './AuthContext.js'; import { createAuthClient, sessionReadWasInconclusive, takePreflightSession, TokenStorage } from './createAuthClient.js'; @@ -1144,6 +1144,12 @@ export function AuthProvider({ [client, refreshOrganizations], ); + const acceptInvitationWithProof = useCallback( + (input: AuthInvitationProofInput): Promise => + client.acceptInvitationWithProof(input), + [client], + ); + const rejectInvitation = useCallback( (invitationId: string): Promise => client.rejectInvitation(invitationId), [client], @@ -1233,6 +1239,7 @@ export function AuthProvider({ getInvitation, getInvitationPreview, acceptInvitation, + acceptInvitationWithProof, rejectInvitation, listUserInvitations, }), @@ -1244,7 +1251,7 @@ export function AuthProvider({ organizations, activeOrganization, activeMember, isOrganizationsLoading, isMembershipResolved, switchOrganization, createOrganization, refreshOrganizations, updateOrganization, deleteOrganization, leaveOrganization, getMembers, inviteMember, describeDelegableScope, removeMember, updateMemberRole, - listInvitations, cancelInvitation, getInvitation, getInvitationPreview, acceptInvitation, rejectInvitation, listUserInvitations, + listInvitations, cancelInvitation, getInvitation, getInvitationPreview, acceptInvitation, acceptInvitationWithProof, rejectInvitation, listUserInvitations, ], ); diff --git a/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts b/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts new file mode 100644 index 00000000000..0137dfc32d8 --- /dev/null +++ b/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts @@ -0,0 +1,59 @@ +/** + * #34257 — `createAuthClient().acceptInvitationWithProof(input)`, the client + * half of objectstack's one-step invitation acceptance + * (`POST {authUrl}/organization/accept-invitation-with-proof`). + */ + +import { describe, it, expect, vi } from 'vitest'; +import { createAuthClient } from '../createAuthClient'; + +const AUTH_URL = 'http://localhost/api/v1/auth'; + +function clientAnswering(status: number, body: unknown) { + const calls: Array<{ url: string; method: string; body: unknown }> = []; + const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + calls.push({ url, method: init?.method ?? 'GET', body: init?.body ? JSON.parse(String(init.body)) : undefined }); + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + }); + return { client: createAuthClient({ baseURL: AUTH_URL, fetchFn }), calls }; +} + +describe('acceptInvitationWithProof (#34257)', () => { + it('posts the input to the one-step door and answers the accepted outcome', async () => { + const { client, calls } = clientAnswering(200, { outcome: 'accepted', organizationId: 'org_1' }); + const input = { invitationId: 'inv_1', proof: 'p1', name: 'Ada', password: 'S3cure!pass' }; + + await expect(client.acceptInvitationWithProof(input)).resolves.toEqual({ + outcome: 'accepted', + organizationId: 'org_1', + }); + expect(calls).toEqual([ + { url: `${AUTH_URL}/organization/accept-invitation-with-proof`, method: 'POST', body: input }, + ]); + }); + + it('answers the sign-in and verify-email outcomes as they are', async () => { + await expect( + clientAnswering(200, { outcome: 'sign_in' }).client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' }), + ).resolves.toEqual({ outcome: 'sign_in' }); + await expect( + clientAnswering(200, { outcome: 'verify_email' }).client.acceptInvitationWithProof({ invitationId: 'inv_1' }), + ).resolves.toEqual({ outcome: 'verify_email' }); + }); + + it('a refusal rejects with the server code and status', async () => { + const { client } = clientAnswering(400, { code: 'INVALID_TOKEN', message: 'no' }); + await expect(client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'bad' })).rejects.toMatchObject({ + code: 'INVALID_TOKEN', + status: 400, + }); + }); + + it('an answer outside the outcome vocabulary rejects', async () => { + const { client } = clientAnswering(200, { outcome: 'something_else' }); + await expect(client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' })).rejects.toThrow( + /unexpected response body/, + ); + }); +}); diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts index ab510ed0c01..1893bc5eb39 100644 --- a/ui/packages/auth/src/createAuthClient.ts +++ b/ui/packages/auth/src/createAuthClient.ts @@ -10,7 +10,7 @@ import { createAuthClient as createBetterAuthClient, parseJSON } from 'better-au import { organizationClient, twoFactorClient } from 'better-auth/client/plugins'; import type { AuthClient, AuthClientConfig, AuthUser, AuthClientSession, SignInCredentials, SignUpData, - AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, + AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationProofInput, AuthInvitationProofOutcome, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge, TwoFactorMethod, } from './types.js'; import { AUTH_INVITATION_STATUSES, isAuthInvitationStatus } from './invitation-status.js'; @@ -1384,6 +1384,33 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { if (error) throw toAuthError(error, 'Failed to accept invitation'); }, + async acceptInvitationWithProof(input: AuthInvitationProofInput): Promise { + const url = `${origin}${basePath}/organization/accept-invitation-with-proof`; + const response = await bearerFetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(input), + }); + const body = (await response.json().catch(() => null)) as + | { outcome?: unknown; organizationId?: unknown; code?: string; message?: string; error?: { code?: string; message?: string } } + | null; + if (!response.ok) { + const code = body?.code ?? body?.error?.code; + const err = new Error( + body?.message ?? body?.error?.message ?? `Invitation acceptance failed with status ${response.status}`, + ) as Error & { code?: string; status?: number }; + if (code) err.code = code; + err.status = response.status; + throw err; + } + if (body?.outcome === 'accepted' && typeof body.organizationId === 'string') { + return { outcome: 'accepted', organizationId: body.organizationId }; + } + if (body?.outcome === 'sign_in' || body?.outcome === 'verify_email') return { outcome: body.outcome }; + throw new Error('acceptInvitationWithProof: unexpected response body'); + }, + async rejectInvitation(invitationId: string): Promise { const { error } = await (betterAuth as any).organization.rejectInvitation({ invitationId }); if (error) throw toAuthError(error, 'Failed to reject invitation'); diff --git a/ui/packages/auth/src/index.ts b/ui/packages/auth/src/index.ts index 5cf4b2d52c0..27ba5802b6b 100644 --- a/ui/packages/auth/src/index.ts +++ b/ui/packages/auth/src/index.ts @@ -112,6 +112,8 @@ export type { AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, + AuthInvitationProofInput, + AuthInvitationProofOutcome, AuthSocialProvider, AuthPublicConfig, SignInWithProviderOptions, diff --git a/ui/packages/auth/src/types.ts b/ui/packages/auth/src/types.ts index 578e81370a9..b51e95522ea 100644 --- a/ui/packages/auth/src/types.ts +++ b/ui/packages/auth/src/types.ts @@ -610,6 +610,18 @@ export interface AuthClient { getInvitationPreview: (invitationId: string) => Promise; /** Accept an invitation as the current user */ acceptInvitation: (invitationId: string) => Promise; + /** + * The one-step invitation acceptance (objectstack + * `POST /organization/accept-invitation-with-proof`). With the mailbox + * proof the invitation mail's link carries, it needs no session: it creates + * the account (or sets the password of an unverified one), verifies the + * address, accepts and signs in, answering `accepted`, or `sign_in` when the + * address has an account the person signs in to as today. Without a proof it + * accepts for the signed-in session when its address is the invited one and + * verified, else answers `verify_email`. Rejects with the server's `code` and + * `status` otherwise (`INVALID_TOKEN` for any proof that does not admit). + */ + acceptInvitationWithProof: (input: AuthInvitationProofInput) => Promise; /** Reject an invitation as the current user */ rejectInvitation: (invitationId: string) => Promise; /** List invitations addressed to the current user */ @@ -709,6 +721,21 @@ export interface AuthInvitationPreview { email: string; } +/** The body of the one-step invitation acceptance. */ +export interface AuthInvitationProofInput { + invitationId: string; + /** The mailbox proof from the invitation mail's link; absent for a signed-in session. */ + proof?: string; + name?: string; + password?: string; +} + +/** What the one-step invitation acceptance answers. */ +export type AuthInvitationProofOutcome = + | { outcome: 'accepted'; organizationId: string } + | { outcome: 'sign_in' } + | { outcome: 'verify_email' }; + /** Organization member */ export interface AuthOrganizationMember { /** Member record ID */ diff --git a/ui/packages/auth/src/useAuth.ts b/ui/packages/auth/src/useAuth.ts index f41722e4a86..434899834ba 100644 --- a/ui/packages/auth/src/useAuth.ts +++ b/ui/packages/auth/src/useAuth.ts @@ -86,6 +86,7 @@ export function useAuth(): AuthContextValue { getInvitation: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, getInvitationPreview: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, acceptInvitation: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, + acceptInvitationWithProof: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, rejectInvitation: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, listUserInvitations: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, }; From fa8bbd6cdc796002934f0277cadaa1a5252b4b29 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:23:10 +0000 Subject: [PATCH 07/26] feat(app-shell): the accept page offers one form to a visitor holding the mailbox proof Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../acceptInvitationOneStep-34257.test.tsx | 207 ++++++++++ .../manage/AcceptInvitationPage.tsx | 361 +++++++++++++++++- ui/packages/i18n/src/locales/ar.ts | 11 + ui/packages/i18n/src/locales/de.ts | 11 + ui/packages/i18n/src/locales/en.ts | 11 + ui/packages/i18n/src/locales/es.ts | 11 + ui/packages/i18n/src/locales/fr.ts | 11 + ui/packages/i18n/src/locales/ja.ts | 11 + ui/packages/i18n/src/locales/ko.ts | 11 + ui/packages/i18n/src/locales/pt-BR.ts | 11 + ui/packages/i18n/src/locales/ru.ts | 11 + ui/packages/i18n/src/locales/zh-Hans.ts | 11 + ui/packages/i18n/src/locales/zh-Hant.ts | 11 + 13 files changed, 676 insertions(+), 13 deletions(-) create mode 100644 ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx new file mode 100644 index 00000000000..d1ea04d69c5 --- /dev/null +++ b/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx @@ -0,0 +1,207 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34257 — the accept page's one-step path. A signed-out visitor + * whose invitation link carries the mailbox proof sees one form (a name and a + * password, or a provider sign-in) instead of the sign-in redirect; a link + * without the proof keeps today's path. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react'; +import { I18nProvider } from '@object-ui/i18n'; +import { builtInLocales } from '@object-ui/i18n/locales'; + +const en = builtInLocales.en.organization.accept; + +const INVITATION = { + id: 'inv-1', + organizationId: 'org-42', + organizationName: 'Acme', + email: 'ada@example.com', + role: 'member', + status: 'pending', + expiresAt: '2099-03-04T12:00:00.000Z', + inviterId: 'u0', +}; + +const PREVIEW = { organizationName: 'Acme', inviterName: 'Grace', email: 'a***@example.com' }; + +const socialProps: { current: Record | null } = { current: null }; + +// STABLE identities: the page keys its effects on these functions. +const auth = { + isAuthenticated: false, + isLoading: false, + getInvitation: vi.fn(async () => INVITATION), + getInvitationPreview: vi.fn(async () => PREVIEW as typeof PREVIEW | null), + acceptInvitation: vi.fn(async () => undefined), + acceptInvitationWithProof: vi.fn(async (): Promise => ({ outcome: 'accepted', organizationId: 'org-42' })), + rejectInvitation: vi.fn(async () => undefined), + switchOrganization: vi.fn(async () => undefined), +}; + +vi.mock('@object-ui/auth', async (importActual) => ({ + ...(await importActual()), + useAuth: () => auth, + SocialSignInButtons: (props: Record) => { + socialProps.current = props; + return
; + }, +})); + +const navigate = vi.fn(); +const location = { pathname: '/accept-invitation/inv-1', search: '' }; +vi.mock('react-router-dom', async (importActual) => { + const params = { invitationId: 'inv-1' }; + return { + ...(await importActual()), + useNavigate: () => navigate, + useLocation: () => location, + useParams: () => params, + }; +}); + +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +import { AcceptInvitationPage } from '../manage/AcceptInvitationPage'; + +const LOGIN_REDIRECT = '/login?redirect=' + encodeURIComponent('/accept-invitation/inv-1'); + +function arriveAt(url: string, signedIn: boolean): void { + window.history.replaceState(null, '', url); + location.search = new URL(url, 'http://localhost').search; + auth.isAuthenticated = signedIn; + render( + + + , + ); +} + +beforeEach(() => { + vi.clearAllMocks(); + socialProps.current = null; + auth.getInvitationPreview.mockImplementation(async () => PREVIEW); + auth.acceptInvitationWithProof.mockImplementation(async () => ({ outcome: 'accepted', organizationId: 'org-42' })); +}); + +afterEach(() => { + cleanup(); + window.history.replaceState(null, '', '/'); + location.search = ''; +}); + +function fillAndSubmit(): void { + fireEvent.change(screen.getByLabelText(en.proofNameLabel), { target: { value: 'Ada' } }); + fireEvent.change(screen.getByLabelText(en.proofPasswordLabel), { target: { value: 'S3cure!pass' } }); + fireEvent.click(screen.getByRole('button', { name: en.proofSubmit })); +} + +describe('AcceptInvitationPage — one-step acceptance (objectstack#34257)', () => { + it('a signed-out visitor holding the proof sees the one form, not the sign-in redirect', async () => { + arriveAt('/accept-invitation/inv-1#proof=p-1', false); + + expect(await screen.findByTestId('accept-invitation-one-step')).toBeInTheDocument(); + expect(await screen.findByText('Join Acme')).toBeInTheDocument(); + expect(screen.getByTestId('social-sign-in')).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it('the proof leaves the address bar once read', async () => { + arriveAt('/accept-invitation/inv-1#proof=p-1', false); + + await screen.findByTestId('accept-invitation-one-step'); + expect(window.location.hash).toBe(''); + expect(window.location.href).not.toContain('p-1'); + }); + + it('the provider sign-in returns to this page without the proof', async () => { + arriveAt('/accept-invitation/inv-1#proof=p-1', false); + + await screen.findByTestId('social-sign-in'); + const callbackURL = String(socialProps.current?.callbackURL); + expect(new URL(callbackURL).pathname).toBe('/accept-invitation/inv-1'); + expect(callbackURL).not.toContain('p-1'); + }); + + it('one submit sends the name, the password and the proof, and an acceptance shows the joined state', async () => { + arriveAt('/accept-invitation/inv-1#proof=p-1', false); + await screen.findByText('Join Acme'); + + fillAndSubmit(); + + expect(await screen.findByTestId('accept-invitation-joined')).toHaveTextContent('Welcome to Acme.'); + expect(auth.acceptInvitationWithProof).toHaveBeenCalledWith({ + invitationId: 'inv-1', + proof: 'p-1', + name: 'Ada', + password: 'S3cure!pass', + }); + expect(screen.getByRole('button', { name: en.continue })).toBeInTheDocument(); + }); + + it('an address with an account hands over to the sign-in, as today', async () => { + auth.acceptInvitationWithProof.mockImplementation(async () => ({ outcome: 'sign_in' })); + arriveAt('/accept-invitation/inv-1#proof=p-1', false); + await screen.findByText('Join Acme'); + + fillAndSubmit(); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(LOGIN_REDIRECT)); + }); + + it('a refused proof says the link can no longer be used', async () => { + auth.acceptInvitationWithProof.mockImplementation(async () => { + throw Object.assign(new Error('no'), { code: 'INVALID_TOKEN', status: 400 }); + }); + arriveAt('/accept-invitation/inv-1#proof=p-1', false); + await screen.findByText('Join Acme'); + + fillAndSubmit(); + + expect(await screen.findByRole('alert')).toHaveTextContent(en.proofInvalid); + expect(screen.queryByTestId('accept-invitation-joined')).toBeNull(); + }); + + it('a link without the proof keeps the sign-in redirect', async () => { + arriveAt('/accept-invitation/inv-1', false); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(LOGIN_REDIRECT)); + expect(screen.queryByTestId('accept-invitation-one-step')).toBeNull(); + expect(auth.acceptInvitationWithProof).not.toHaveBeenCalled(); + }); + + it('back from a provider sign-in, the page redeems the invitation for the session', async () => { + arriveAt('/accept-invitation/inv-1?via=provider', true); + + expect(await screen.findByTestId('accept-invitation-joined')).toHaveTextContent('Welcome to Acme.'); + expect(auth.acceptInvitationWithProof).toHaveBeenCalledTimes(1); + expect(auth.acceptInvitationWithProof).toHaveBeenCalledWith({ invitationId: 'inv-1' }); + expect(auth.switchOrganization).toHaveBeenCalledWith('org-42'); + expect(window.location.search).toBe(''); + }); + + it('back from a provider sign-in with an address that is not the verified invited one, the page asks for verification', async () => { + auth.acceptInvitationWithProof.mockImplementation(async () => ({ outcome: 'verify_email' })); + arriveAt('/accept-invitation/inv-1?via=provider', true); + + expect(await screen.findByTestId('accept-invitation-verify-email')).toHaveTextContent(en.verifyEmailTitle); + expect(screen.queryByTestId('accept-invitation-joined')).toBeNull(); + }); + + it('a signed-in visitor without the provider return keeps the Accept button path', async () => { + arriveAt('/accept-invitation/inv-1', true); + + expect(await screen.findByRole('button', { name: en.accept })).toBeInTheDocument(); + expect(auth.acceptInvitationWithProof).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx index 0468383b792..a3bf4f5abbb 100644 --- a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx +++ b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx @@ -9,11 +9,11 @@ * full-viewport shell, so hosts mount it bare — no auth layout around it. */ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState, type FormEvent } from 'react'; import { useLocation, useNavigate, useParams } from 'react-router-dom'; -import { Button } from '@object-ui/components'; -import { useAuth } from '@object-ui/auth'; -import type { AuthInvitation } from '@object-ui/auth'; +import { Button, Input, Label } from '@object-ui/components'; +import { SocialSignInButtons, useAuth } from '@object-ui/auth'; +import type { AuthInvitation, AuthInvitationPreview } from '@object-ui/auth'; import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; import { Loader2, Building2, CheckCircle, XCircle } from 'lucide-react'; import { toast } from 'sonner'; @@ -32,6 +32,55 @@ type InvitationWithOrg = AuthInvitation & { inviterEmail?: string; }; +/** The URL fragment key the invitation mail's link carries its mailbox proof under. */ +const PROOF_FRAGMENT_KEY = 'proof'; + +/** + * The query marker a provider sign-in started on this page returns with, so + * the page redeems the invitation for the session the provider just opened. + */ +const PROVIDER_RETURN_KEY = 'via'; +const PROVIDER_RETURN_VALUE = 'provider'; + +/** + * Reads the mailbox proof from the URL fragment once, and clears the fragment + * from the address bar, so the proof is not left in the visible URL, the + * history entry or a link copied from the page. A fragment never reaches the + * server, so the proof is only ever sent in the one-step request's body. + */ +function takeProofFromFragment(): string | null { + if (typeof window === 'undefined') return null; + const hash = window.location.hash; + if (!hash || hash.length < 2) return null; + const proof = new URLSearchParams(hash.slice(1)).get(PROOF_FRAGMENT_KEY); + if (!proof) return null; + window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search); + return proof; +} + +/** This page's address with the provider-return marker set, for a provider sign-in to come back to. */ +function providerReturnUrl(): string | undefined { + if (typeof window === 'undefined') return undefined; + const url = new URL(window.location.href); + url.hash = ''; + url.searchParams.set(PROVIDER_RETURN_KEY, PROVIDER_RETURN_VALUE); + return url.toString(); +} + +/** Removes the provider-return marker from the address bar once it has been read. */ +function clearProviderReturn(): void { + if (typeof window === 'undefined') return; + const url = new URL(window.location.href); + if (!url.searchParams.has(PROVIDER_RETURN_KEY)) return; + url.searchParams.delete(PROVIDER_RETURN_KEY); + window.history.replaceState(window.history.state, '', url.pathname + url.search + url.hash); +} + +const readCode = (err: unknown): string | undefined => { + const code = (err as { code?: unknown } | null)?.code; + return typeof code === 'string' ? code : undefined; +}; + export function AcceptInvitationPage() { const { t } = useObjectTranslation(); // Dates and numbers on this surface read the display locale; a bare @@ -40,8 +89,15 @@ export function AcceptInvitationPage() { const navigate = useNavigate(); const location = useLocation(); const { invitationId } = useParams<{ invitationId: string }>(); - const { isAuthenticated, isLoading: isAuthLoading, getInvitation, acceptInvitation, rejectInvitation, switchOrganization } = - useAuth(); + const { + isAuthenticated, + isLoading: isAuthLoading, + getInvitation, + acceptInvitation, + acceptInvitationWithProof, + rejectInvitation, + switchOrganization, + } = useAuth(); const [invitation, setInvitation] = useState(null); const [isLoading, setIsLoading] = useState(true); @@ -51,6 +107,31 @@ export function AcceptInvitationPage() { // Set once the membership exists and the session is switched to it: the page // then says the user joined, and Continue enters the organization. const [joined, setJoined] = useState(false); + // The mailbox proof the invitation mail's link carries in its fragment. A + // signed-out visitor holding it is offered the one-step form in place of + // the sign-in redirect; without it (a copied link) the page keeps its path. + const [proof] = useState(() => + typeof window === 'undefined' + ? null + : new URLSearchParams(window.location.hash.slice(1)).get(PROOF_FRAGMENT_KEY) || null, + ); + // True while the page redeems the invitation for a session a provider + // sign-in started here just opened. + const [providerReturn, setProviderReturn] = useState( + () => + typeof window !== 'undefined' && + new URLSearchParams(window.location.search).get(PROVIDER_RETURN_KEY) === PROVIDER_RETURN_VALUE, + ); + // Joined through the one-step door: the organization's name to welcome the + // visitor to (the door answers no role). + const [oneStepJoined, setOneStepJoined] = useState<{ orgName: string } | null>(null); + // The provider session's address is not the invited one, or not verified. + const [needsVerifiedEmail, setNeedsVerifiedEmail] = useState(false); + + // The proof leaves the address bar as soon as it has been read. + useEffect(() => { + if (proof) takeProofFromFragment(); + }, [proof]); // Redirect to login if not authenticated. // @@ -62,15 +143,54 @@ export function AcceptInvitationPage() { // `/console/console/accept-invitation/…`. Under the default `/` mount the two // spellings agree, which is why only the basename case can catch it // (objectui#3811). + // + // A visitor holding the mailbox proof is not redirected: the page offers the + // one-step form instead. + const loginRedirect = '/login?redirect=' + encodeURIComponent(location.pathname + location.search); useEffect(() => { - if (!isAuthLoading && !isAuthenticated) { - navigate('/login?redirect=' + encodeURIComponent(location.pathname + location.search)); + if (!isAuthLoading && !isAuthenticated && !proof) { + navigate(loginRedirect); } - }, [isAuthenticated, isAuthLoading, navigate, location.pathname, location.search]); + }, [isAuthenticated, isAuthLoading, navigate, loginRedirect, proof]); + + // Back from a provider sign-in started on this page: read the invitation + // while it is still pending, then redeem it for the new session. Anything + // but an acceptance falls back to the page's own path. + // Runs once: the redemption is not repeated when the effect re-runs. + const redeemStarted = useRef(false); + useEffect(() => { + if (!providerReturn || !invitationId || isAuthLoading || !isAuthenticated) return; + if (redeemStarted.current) return; + redeemStarted.current = true; + clearProviderReturn(); + setIsLoading(true); + void (async () => { + const inv = await getInvitation(invitationId).catch(() => null); + try { + const outcome = await acceptInvitationWithProof({ invitationId }); + if (outcome.outcome === 'accepted') { + await switchOrganization(outcome.organizationId).catch(() => null); + setOneStepJoined({ + orgName: (inv as InvitationWithOrg | null)?.organizationName ?? outcome.organizationId, + }); + setIsLoading(false); + return; + } + if (outcome.outcome === 'verify_email') { + setNeedsVerifiedEmail(true); + setIsLoading(false); + return; + } + } catch { + // Falls through to the page's own path below. + } + setProviderReturn(false); + })(); + }, [providerReturn, invitationId, isAuthLoading, isAuthenticated, getInvitation, acceptInvitationWithProof, switchOrganization]); // Fetch invitation details useEffect(() => { - if (!invitationId || !isAuthenticated) return; + if (!invitationId || !isAuthenticated || providerReturn) return; let cancelled = false; setIsLoading(true); setError(null); @@ -176,13 +296,68 @@ export function AcceptInvitationPage() { ); } - // Will redirect if not authenticated — show nothing in the meantime - if (!isAuthenticated) return null; + // Joined in one step: welcomed by name, and Continue enters the organization. + const oneStepJoinedState = oneStepJoined ? ( +
+
+ +
+
+

+ {t('organization.accept.accepted', { defaultValue: 'Invitation accepted' })} +

+

+ {t('organization.accept.joinedWelcome', { + defaultValue: 'Welcome to {{orgName}}.', + orgName: oneStepJoined.orgName, + })} +

+
+ +
+ ) : null; + + if (!isAuthenticated) { + // Will redirect when the link carries no proof — show nothing meanwhile. + if (!proof || !invitationId) return null; + return ( +
+
+ {oneStepJoinedState ?? ( + setOneStepJoined({ orgName })} + onSignIn={() => navigate(loginRedirect)} + /> + )} +
+
+ ); + } return (
- {isLoading ? ( + {oneStepJoinedState ? ( + oneStepJoinedState + ) : needsVerifiedEmail ? ( +
+ +

+ {t('organization.accept.verifyEmailTitle', { defaultValue: 'Verify your email address' })} +

+

+ {t('organization.accept.verifyEmailDescription', { + defaultValue: + 'The email address of this account must be the invited one, and verified. Verify it, then open the invitation link from your mailbox again.', + })} +

+
+ ) : isLoading ? (

@@ -307,3 +482,163 @@ export function AcceptInvitationPage() {

); } + +interface OneStepJoinFormProps { + invitationId: string; + proof: string; + acceptInvitationWithProof: ReturnType['acceptInvitationWithProof']; + /** The door accepted: the visitor has an account, a session and the membership. */ + onJoined: (orgName: string) => void; + /** The address has an account the visitor signs in to, as today. */ + onSignIn: () => void; +} + +/** + * The one form a signed-out visitor holding the mailbox proof sees: a name and + * a password, or a provider sign-in. One request creates the account (or sets + * the password of an unverified one), verifies the address, accepts and signs + * in. A provider sign-in returns to this page, which redeems the invitation for + * the provider's session. + */ +function OneStepJoinForm({ invitationId, proof, acceptInvitationWithProof, onJoined, onSignIn }: OneStepJoinFormProps) { + const { t } = useObjectTranslation(); + const { getInvitationPreview } = useAuth(); + const [preview, setPreview] = useState(null); + const [gone, setGone] = useState(false); + const [name, setName] = useState(''); + const [password, setPassword] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [failure, setFailure] = useState(null); + + useEffect(() => { + let cancelled = false; + getInvitationPreview(invitationId) + .then((answer) => { + if (cancelled) return; + if (answer === null) setGone(true); + else setPreview(answer); + }) + .catch(() => null); + return () => { + cancelled = true; + }; + }, [getInvitationPreview, invitationId]); + + const invalidMessage = t('organization.accept.proofInvalid', { + defaultValue: 'This invitation link can no longer be used. Ask for a new invitation, or sign in to an existing account.', + }); + + const handleSubmit = async (event: FormEvent) => { + event.preventDefault(); + if (submitting) return; + setSubmitting(true); + setFailure(null); + try { + const outcome = await acceptInvitationWithProof({ invitationId, proof, name: name.trim(), password }); + if (outcome.outcome === 'accepted') { + onJoined(preview?.organizationName ?? outcome.organizationId); + return; + } + onSignIn(); + } catch (err) { + setFailure( + readCode(err) === 'INVALID_TOKEN' + ? invalidMessage + : resolveOrgErrorMessage(err, t, { + key: 'organization.accept.acceptFailed', + defaultValue: 'Failed to accept invitation', + }), + ); + setSubmitting(false); + } + }; + + if (gone) { + return ( +
+ +

+ {t('organization.accept.errorTitle', { defaultValue: 'Invitation unavailable' })} +

+

{invalidMessage}

+ +
+ ); + } + + return ( +
+
+
+ +
+
+

+ {preview + ? t('organization.accept.proofTitle', { + defaultValue: 'Join {{orgName}}', + orgName: preview.organizationName, + }) + : t('organization.accept.title', { defaultValue: 'You have been invited' })} +

+ {preview && ( +

+ {t('organization.accept.proofDescription', { + defaultValue: 'Set up your account for {{email}} to accept the invitation.', + email: preview.email, + })} +

+ )} +
+
+ + + +
+ {failure && ( +
+ {failure} +
+ )} +
+ + setName(e.target.value)} + required + /> +
+
+ + setPassword(e.target.value)} + required + /> +
+ + +
+
+ ); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index f8a4d3cea7c..e20d0fe0d8f 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4017,6 +4017,17 @@ const ar = { accept: "قبول الدعوة", accepted: "تم قبول الدعوة", joinedDescription: "مرحبًا بك في {{orgName}}. انضممت بصفة {{role}}.", + joinedWelcome: "مرحبًا بك في {{orgName}}.", + verifyEmailTitle: "تحقّق من عنوان بريدك الإلكتروني", + verifyEmailDescription: "يجب أن يكون عنوان البريد الإلكتروني لهذا الحساب هو العنوان المدعو وأن يكون موثّقًا. وثّقه، ثم افتح رابط الدعوة من بريدك مرة أخرى.", + proofInvalid: "لم يعد بالإمكان استخدام رابط الدعوة هذا. اطلب دعوة جديدة، أو سجّل الدخول إلى حساب موجود.", + signInInstead: "تسجيل الدخول إلى حساب موجود", + proofTitle: "انضم إلى {{orgName}}", + proofDescription: "أعدّ حسابك للعنوان {{email}} لقبول الدعوة.", + proofDivider: "أو عيّن كلمة مرور", + proofNameLabel: "الاسم", + proofPasswordLabel: "كلمة المرور", + proofSubmit: "إنشاء حساب والانضمام", continue: "متابعة", acceptFailed: "فشل قبول الدعوة", decline: "رفض", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 5f2a3369d71..7487090b9a1 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3708,6 +3708,17 @@ const de = { accept: "Einladung annehmen", accepted: "Einladung angenommen", joinedDescription: "Willkommen bei {{orgName}}. Sie sind als {{role}} beigetreten.", + joinedWelcome: "Willkommen bei {{orgName}}.", + verifyEmailTitle: "Bestätigen Sie Ihre E-Mail-Adresse", + verifyEmailDescription: "Die E-Mail-Adresse dieses Kontos muss die eingeladene und bestätigt sein. Bestätigen Sie sie und öffnen Sie dann den Einladungslink aus Ihrem Postfach erneut.", + proofInvalid: "Dieser Einladungslink kann nicht mehr verwendet werden. Fordern Sie eine neue Einladung an oder melden Sie sich bei einem bestehenden Konto an.", + signInInstead: "Bei einem bestehenden Konto anmelden", + proofTitle: "{{orgName}} beitreten", + proofDescription: "Richten Sie Ihr Konto für {{email}} ein, um die Einladung anzunehmen.", + proofDivider: "oder ein Passwort festlegen", + proofNameLabel: "Name", + proofPasswordLabel: "Passwort", + proofSubmit: "Konto erstellen und beitreten", continue: "Weiter", acceptFailed: "Einladung konnte nicht angenommen werden", decline: "Ablehnen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 38d44ccad62..04188888c3e 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4596,6 +4596,17 @@ const en = { accept: 'Accept invitation', accepted: 'Invitation accepted', joinedDescription: 'Welcome to {{orgName}}. You joined as {{role}}.', + joinedWelcome: 'Welcome to {{orgName}}.', + verifyEmailTitle: 'Verify your email address', + verifyEmailDescription: 'The email address of this account must be the invited one, and verified. Verify it, then open the invitation link from your mailbox again.', + proofInvalid: 'This invitation link can no longer be used. Ask for a new invitation, or sign in to an existing account.', + signInInstead: 'Sign in to an existing account', + proofTitle: 'Join {{orgName}}', + proofDescription: 'Set up your account for {{email}} to accept the invitation.', + proofDivider: 'or set a password', + proofNameLabel: 'Name', + proofPasswordLabel: 'Password', + proofSubmit: 'Create account and join', continue: 'Continue', acceptFailed: 'Failed to accept invitation', decline: 'Decline', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index e7f43fda5f5..a017423d164 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3786,6 +3786,17 @@ const es = { accept: "Aceptar invitación", accepted: "Invitación aceptada", joinedDescription: "Te damos la bienvenida a {{orgName}}. Te uniste como {{role}}.", + joinedWelcome: "Te damos la bienvenida a {{orgName}}.", + verifyEmailTitle: "Verifica tu dirección de correo", + verifyEmailDescription: "La dirección de correo de esta cuenta debe ser la invitada y estar verificada. Verifícala y vuelve a abrir el enlace de invitación desde tu buzón.", + proofInvalid: "Este enlace de invitación ya no se puede usar. Pide una nueva invitación o inicia sesión en una cuenta existente.", + signInInstead: "Iniciar sesión en una cuenta existente", + proofTitle: "Únete a {{orgName}}", + proofDescription: "Configura tu cuenta para {{email}} y acepta la invitación.", + proofDivider: "o establece una contraseña", + proofNameLabel: "Nombre", + proofPasswordLabel: "Contraseña", + proofSubmit: "Crear cuenta y unirme", continue: "Continuar", acceptFailed: "No se pudo aceptar la invitación", decline: "Rechazar", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 78783ed4870..b99b5bd29a1 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3782,6 +3782,17 @@ const fr = { accept: "Accepter l'invitation", accepted: "Invitation acceptée", joinedDescription: "Bienvenue dans {{orgName}}. Vous l'avez rejoint en tant que {{role}}.", + joinedWelcome: "Bienvenue dans {{orgName}}.", + verifyEmailTitle: "Vérifiez votre adresse e-mail", + verifyEmailDescription: "L'adresse e-mail de ce compte doit être celle invitée et être vérifiée. Vérifiez-la, puis rouvrez le lien d'invitation depuis votre boîte de réception.", + proofInvalid: "Ce lien d'invitation ne peut plus être utilisé. Demandez une nouvelle invitation ou connectez-vous à un compte existant.", + signInInstead: "Se connecter à un compte existant", + proofTitle: "Rejoindre {{orgName}}", + proofDescription: "Configurez votre compte pour {{email}} afin d'accepter l'invitation.", + proofDivider: "ou définir un mot de passe", + proofNameLabel: "Nom", + proofPasswordLabel: "Mot de passe", + proofSubmit: "Créer le compte et rejoindre", continue: "Continuer", acceptFailed: "Impossible d'accepter l'invitation", decline: "Refuser", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 2bbdcf1d902..df0ae39473b 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3710,6 +3710,17 @@ const ja = { accept: "招待を承諾", accepted: "招待を承諾しました", joinedDescription: "{{orgName}} へようこそ。{{role}} として参加しました。", + joinedWelcome: "{{orgName}} へようこそ。", + verifyEmailTitle: "メールアドレスを確認してください", + verifyEmailDescription: "このアカウントのメールアドレスは招待されたアドレスで、確認済みである必要があります。確認してから、メールボックスの招待リンクをもう一度開いてください。", + proofInvalid: "この招待リンクはもう使用できません。新しい招待を依頼するか、既存のアカウントにサインインしてください。", + signInInstead: "既存のアカウントにサインイン", + proofTitle: "{{orgName}} に参加", + proofDescription: "招待を承諾するには、{{email}} のアカウントを設定してください。", + proofDivider: "またはパスワードを設定", + proofNameLabel: "名前", + proofPasswordLabel: "パスワード", + proofSubmit: "アカウントを作成して参加", continue: "続行", acceptFailed: "招待の承諾に失敗しました", decline: "辞退", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 85e340a1cee..f6befbfa545 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3707,6 +3707,17 @@ const ko = { accept: "초대 수락", accepted: "초대를 수락함", joinedDescription: "{{orgName}}에 오신 것을 환영합니다. {{role}}(으)로 참여했습니다.", + joinedWelcome: "{{orgName}}에 오신 것을 환영합니다.", + verifyEmailTitle: "이메일 주소를 인증하세요", + verifyEmailDescription: "이 계정의 이메일 주소는 초대받은 주소여야 하며 인증되어 있어야 합니다. 인증한 다음 메일함에서 초대 링크를 다시 여세요.", + proofInvalid: "이 초대 링크는 더 이상 사용할 수 없습니다. 새 초대를 요청하거나 기존 계정으로 로그인하세요.", + signInInstead: "기존 계정으로 로그인", + proofTitle: "{{orgName}}에 참여", + proofDescription: "초대를 수락하려면 {{email}} 계정을 설정하세요.", + proofDivider: "또는 비밀번호 설정", + proofNameLabel: "이름", + proofPasswordLabel: "비밀번호", + proofSubmit: "계정 만들고 참여", continue: "계속", acceptFailed: "초대 수락 실패", decline: "거절", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index fb06f2e6b8b..5d915cef396 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3781,6 +3781,17 @@ const pt = { accept: "Aceitar convite", accepted: "Convite aceito", joinedDescription: "Boas-vindas a {{orgName}}. Você entrou como {{role}}.", + joinedWelcome: "Boas-vindas a {{orgName}}.", + verifyEmailTitle: "Verifique seu endereço de e-mail", + verifyEmailDescription: "O endereço de e-mail desta conta precisa ser o convidado e estar verificado. Verifique-o e abra novamente o link do convite a partir da sua caixa de entrada.", + proofInvalid: "Este link de convite não pode mais ser usado. Peça um novo convite ou entre em uma conta existente.", + signInInstead: "Entrar em uma conta existente", + proofTitle: "Entrar em {{orgName}}", + proofDescription: "Configure sua conta para {{email}} para aceitar o convite.", + proofDivider: "ou defina uma senha", + proofNameLabel: "Nome", + proofPasswordLabel: "Senha", + proofSubmit: "Criar conta e entrar", continue: "Continuar", acceptFailed: "Falha ao aceitar o convite", decline: "Recusar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 709edafa4a5..cadc9960ee5 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3873,6 +3873,17 @@ const ru = { accept: "Принять приглашение", accepted: "Приглашение принято", joinedDescription: "Добро пожаловать в {{orgName}}. Вы присоединились в роли {{role}}.", + joinedWelcome: "Добро пожаловать в {{orgName}}.", + verifyEmailTitle: "Подтвердите адрес электронной почты", + verifyEmailDescription: "Адрес электронной почты этой учётной записи должен совпадать с приглашённым и быть подтверждён. Подтвердите его, затем снова откройте ссылку приглашения из почтового ящика.", + proofInvalid: "Эту ссылку приглашения больше нельзя использовать. Запросите новое приглашение или войдите в существующую учётную запись.", + signInInstead: "Войти в существующую учётную запись", + proofTitle: "Присоединиться к {{orgName}}", + proofDescription: "Настройте учётную запись для {{email}}, чтобы принять приглашение.", + proofDivider: "или задайте пароль", + proofNameLabel: "Имя", + proofPasswordLabel: "Пароль", + proofSubmit: "Создать учётную запись и присоединиться", continue: "Продолжить", acceptFailed: "Не удалось принять приглашение", decline: "Отклонить", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index dfa8db59aa2..63fc8d45ade 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3956,6 +3956,17 @@ const zh = { accept: '接受邀请', accepted: '邀请已接受', joinedDescription: '欢迎加入 {{orgName}},您的身份是 {{role}}。', + joinedWelcome: '欢迎加入 {{orgName}}。', + verifyEmailTitle: '请验证您的邮箱地址', + verifyEmailDescription: '此账号的邮箱地址须是受邀地址且已验证。请先完成验证,再从邮箱中重新打开邀请链接。', + proofInvalid: '此邀请链接已无法使用。请索取新的邀请,或登录已有账号。', + signInInstead: '登录已有账号', + proofTitle: '加入 {{orgName}}', + proofDescription: '为 {{email}} 设置账号以接受邀请。', + proofDivider: '或设置密码', + proofNameLabel: '姓名', + proofPasswordLabel: '密码', + proofSubmit: '创建账号并加入', continue: '继续', acceptFailed: '接受邀请失败', decline: '拒绝', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index f6245ff3d7e..307d0e6ef7a 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3956,6 +3956,17 @@ const zhHant = { accept: '接受邀請', accepted: '邀請已接受', joinedDescription: '歡迎加入 {{orgName}},您的身份是 {{role}}。', + joinedWelcome: '歡迎加入 {{orgName}}。', + verifyEmailTitle: '請驗證您的郵箱地址', + verifyEmailDescription: '此賬號的郵箱地址須是受邀地址且已驗證。請先完成驗證,再從郵箱中重新開啟邀請連結。', + proofInvalid: '此邀請連結已無法使用。請索取新的邀請,或登入已有賬號。', + signInInstead: '登入已有賬號', + proofTitle: '加入 {{orgName}}', + proofDescription: '為 {{email}} 設定賬號以接受邀請。', + proofDivider: '或設定密碼', + proofNameLabel: '姓名', + proofPasswordLabel: '密碼', + proofSubmit: '建立賬號並加入', continue: '繼續', acceptFailed: '接受邀請失敗', decline: '拒絕', From 2a2409921df290fd0e3382752aac5fb8839ff6c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:40:14 +0000 Subject: [PATCH 08/26] chore(changeset): one-step invitation acceptance Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../34257-one-step-invitation-acceptance.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/34257-one-step-invitation-acceptance.md diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md new file mode 100644 index 00000000000..21746e473c9 --- /dev/null +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-email': patch +'@objectstack/plugin-auth': patch +'@object-ui/auth': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(auth): an invitation is accepted in one step with the proof its mail carries + +Clause-②: yes (widening) +Metadata-protocol: none + +- **The invitation mail carries a mailbox proof.** The accept link in the mail ends with `#proof=…`. The server keeps only a hash of the proof, bound to the invitation's address and expiry. A resend retires the earlier proof. The stored mail row never holds the proof, and the console's copy-link action answers the link without it. +- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-with-proof` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had), verifies the address, accepts the invitation and signs in. A proof is single-use. A proof that does not admit is refused with one `INVALID_TOKEN` answer and leaves the real proof usable. The door is rate-limited per client address and per invitation, and runs the sign-up gates: who may sign up, password length, complexity and breach checks, SSO-only mode. +- **An address with an account signs in as today.** When the address belongs to a verified account, an account with a linked provider, a second factor or a directory-managed account, the door answers `sign_in` and the proof stays unspent. +- **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. +- **`SendTemplateInput.deliverOnly`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row. A send carrying them is delivered inline, never through the durable queue. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. +- **The accept page offers one form.** A signed-out visitor whose link carries the proof sees a name and password form, or a provider sign-in, in place of the sign-in redirect. The proof is cleared from the address bar once read. A provider sign-in returns to the page, which redeems the invitation for the new session. A link without the proof keeps today's path. The `@object-ui/auth` client gains `acceptInvitationWithProof`. From 85b6f0ab875783bf29608b69b3e9cffbe8031912 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:20:43 +0000 Subject: [PATCH 09/26] test(auth): the plugin list carries the one-step door; a redeemed proof leaves nothing that admits it Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugins/plugin-auth/src/auth-manager.test.ts | 12 +++++++++--- .../src/invitation-one-step-acceptance-34257.test.ts | 10 ++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-manager.test.ts b/packages/plugins/plugin-auth/src/auth-manager.test.ts index bc49d363369..9d48f729438 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.test.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.test.ts @@ -438,7 +438,13 @@ describe('AuthManager', () => { warnSpy.mockRestore(); // [#28367] The agent forward view rides right after bearer(), on every instance. - expect(capturedConfig.plugins.map((p: any) => p.id)).toEqual(['bearer', 'objectstack-agent-forward-identity-view', 'organization']); + // [#34257] The one-step invitation door rides right after organization(). + expect(capturedConfig.plugins.map((p: any) => p.id)).toEqual([ + 'bearer', + 'objectstack-agent-forward-identity-view', + 'organization', + 'invitation-mailbox-proof', + ]); }); it('should register organization plugin with schema mapping when enabled', async () => { @@ -1635,9 +1641,9 @@ describe('AuthManager', () => { await manager.getAuthInstance(); warnSpy.mockRestore(); - expect(capturedConfig.plugins).toHaveLength(5); + expect(capturedConfig.plugins).toHaveLength(6); expect(capturedConfig.plugins.map((p: any) => p.id).sort()).toEqual( - ['bearer', 'magic-link', 'objectstack-agent-forward-identity-view', 'organization', 'two-factor'], + ['bearer', 'invitation-mailbox-proof', 'magic-link', 'objectstack-agent-forward-identity-view', 'organization', 'two-factor'], ); }); }); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 66b6f658d14..6ee1e62e1bb 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -11,7 +11,7 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { AuthManager } from './auth-manager'; import { inviteForAudienceGate } from './audience-gate-test-support'; import { createCopyInvitationLinkHandler } from './invitation-link-action'; -import { ACCEPT_INVITATION_WITH_PROOF_PATH } from './invitation-mailbox-proof'; +import { ACCEPT_INVITATION_WITH_PROOF_PATH, invitationProofIdentifier } from './invitation-mailbox-proof'; const SECRET = 'test-secret-at-least-32-chars-long!!'; const BASE = 'http://localhost:3000'; @@ -289,10 +289,16 @@ describe('#34257 — accepting with the proof', () => { }); it('a proof is single-use', async () => { - const { manager, invite } = await boot(); + const { engine, manager, invite } = await boot(); const { invitation, proof } = await invite('once@example.com'); + const proofRows = () => + (engine.tables.get('sys_verification') ?? []).filter( + (row) => row.identifier === invitationProofIdentifier(String(invitation.id)), + ); + expect(proofRows()).toHaveLength(1); const first = await door(manager, { invitationId: invitation.id, proof, name: 'Once', password: PASSWORD }); expect(first.status, await first.clone().text()).toBe(200); + expect(proofRows()).toHaveLength(0); await expectRefused(await door(manager, { invitationId: invitation.id, proof, name: 'Once', password: PASSWORD })); }); From 5a3f2c1cf50e2813c7edbea169865f22d529c70e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:55:07 +0000 Subject: [PATCH 10/26] test(auth): annotate the one-step harness matcher's return type Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/invitation-one-step-acceptance-34257.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 6ee1e62e1bb..f1ccea8a944 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -30,8 +30,8 @@ const createMemoryEngine = () => { a instanceof Date || b instanceof Date ? new Date(a as any).getTime() === new Date(b as any).getTime() : a === b; - const matches = (row: any, where: Record = {}) => - Object.entries(where).every(([k, v]) => { + const matches = (row: any, where: Record = {}): boolean => + Object.entries(where).every(([k, v]): boolean => { if (k === '$and' && Array.isArray(v)) return v.every((w) => matches(row, w)); if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); const actual = row[k]; From bb6f32248ac4a0a1f60fb0887d84a7163e710071 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:01:35 +0000 Subject: [PATCH 11/26] docs(adr): ADR-0138 names the OAuth client-name read beside the one-step door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- ...-anonymous-principal-doors-grants-and-organization.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index a751e2383e1..7cb6d70b304 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -300,7 +300,7 @@ under class 2, ahead of the allowlist, so it is judged as this door and not as c infrastructure. The same ruling's Q2 B leaves the verification posture as it was: an invitation-link sign-up still owes the verification mail. -**Amended 2026-11-16 — the one-step invitation acceptance, a class-2-shaped door.** Card +**Amended 2026-11-16 — the one-step invitation acceptance and the OAuth client-name read, class-2-shaped doors.** Card [#34257](https://github.com/objectstack-ai/objectstack/issues/34257), on the owning seat's rulings in claim amendment [`6906424686`](https://github.com/objectstack-ai/objectstack/issues/34257#issuecomment-6906424686), @@ -320,6 +320,13 @@ Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildI ledgered in `packages/plugins/plugin-auth/src/auth-route-ledger.ts`; it sits in the `/auth` namespace and is classified under class 2 the way the preview above is. +The same amendment admits a second door of class 2's shape, added by +[#34168](https://github.com/objectstack-ai/objectstack/issues/34168): +`GET /api/v1/auth/oauth2/client-name`, a public read. What admits the request: a request the server +itself signed, which names one OAuth client. What it answers: that client's display name and nothing +else, and only for the client the signed request names. Every other request gets one uniform 404. +It is rate-limited per client address on the counter the invitation preview above uses, as ADR-0121 D6 requires. + This refines ruling [`6413975861`](https://github.com/objectstack-ai/objectstack/issues/26020#issuecomment-6413975861) Q2 B, recorded above as "an invitation-link sign-up still owes the verification mail". A proof-carrying invitation link proves the mailbox, so a sign-up through it owes no verification mail. From 16d71d96dbdc06729d538b2fae669cdf11df1725 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:16:42 +0000 Subject: [PATCH 12/26] fix(auth): the one-step door answers registered codes; its test double applies the caller's bound by presence Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugin-auth/src/invitation-mailbox-proof.ts | 8 ++++---- .../invitation-one-step-acceptance-34257.test.ts | 4 ++-- scripts/engine-double-contract.pinned.json | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 0bcad73fdd2..e7c8119dd3c 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -290,18 +290,18 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo const password = typeof body.password === 'string' ? body.password : ''; const passwordConfig = ctx.context.password.config; if (password.length < passwordConfig.minPasswordLength) { - throw new APIError('BAD_REQUEST', { code: 'PASSWORD_TOO_SHORT', message: 'Password too short' }); + throw new APIError('BAD_REQUEST', { code: 'PASSWORD_POLICY_VIOLATION', message: 'Password too short' }); } if (password.length > passwordConfig.maxPasswordLength) { - throw new APIError('BAD_REQUEST', { code: 'PASSWORD_TOO_LONG', message: 'Password too long' }); + throw new APIError('BAD_REQUEST', { code: 'PASSWORD_POLICY_VIOLATION', message: 'Password too long' }); } const name = nonEmpty(body.name); if (!existing) { const ep = ctx.context.options.emailAndPassword; if (!ep?.enabled || ep.disableSignUp) { - throw new APIError('BAD_REQUEST', { - code: 'EMAIL_PASSWORD_SIGN_UP_DISABLED', + throw new APIError('FORBIDDEN', { + code: 'PERMISSION_DENIED', message: 'Email and password sign up is not enabled', }); } diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index f1ccea8a944..06d25f34b39 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -66,8 +66,8 @@ const createMemoryEngine = () => { (a, b) => (a[order.field] > b[order.field] ? 1 : -1) * (order.order === 'desc' ? -1 : 1), ); } - if (q.offset) out = out.slice(q.offset); - if (q.limit) out = out.slice(0, q.limit); + if (typeof q.offset === 'number') out = out.slice(q.offset); + if (typeof q.limit === 'number') out = out.slice(0, q.limit); return out.map((r) => ({ ...r })); }, async count(name: string, q: any = {}) { diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 7013c2223f8..38b77910274 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3901,6 +3901,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts", "verb": "delete", From ec9f03b5ecb86b0c581106edc44cd601b2dacc87 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:00:10 +0000 Subject: [PATCH 13/26] fix(auth): the one-step door answers in the envelope Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/invitation-mailbox-proof.ts | 11 ++++++----- ...nvitation-one-step-acceptance-34257.test.ts | 18 +++++++++--------- scripts/check-route-envelope.mjs | 6 ++++++ .../acceptInvitationWithProof-34257.test.ts | 8 ++++---- ui/packages/auth/src/createAuthClient.ts | 15 +++++++++++---- 5 files changed, 36 insertions(+), 22 deletions(-) diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index e7c8119dd3c..7135018c770 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -36,7 +36,8 @@ * ## The door — `POST /organization/accept-invitation-with-proof` * * Body `{ invitationId, proof, name, password }`, or `{ invitationId }` alone - * from a signed-in session (the social return). Answers: + * from a signed-in session (the social return). Answers in the envelope, + * `{ success: true, data }`, with `data` one of: * * - `{ outcome: 'accepted', organizationId }` — the invitation is accepted and * the caller is signed in. @@ -256,9 +257,9 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo if (!session) throw new APIError('UNAUTHORIZED', { code: 'UNAUTHENTICATED', message: 'Sign in to accept the invitation.' }); if (!pending) return refuseProof(); const sameAddress = String(session.user.email).toLowerCase() === invitation.email.toLowerCase(); - if (!sameAddress || session.user.emailVerified !== true) return ctx.json({ outcome: 'verify_email' }); + if (!sameAddress || session.user.emailVerified !== true) return ctx.json({ success: true, data: { outcome: 'verify_email' } }); await acceptAs(session.session.token, invitationId); - return ctx.json({ outcome: 'accepted', organizationId: invitation.organizationId }); + return ctx.json({ success: true, data: { outcome: 'accepted', organizationId: invitation.organizationId } }); } // ── Proof mode ───────────────────────────────────────────────────── @@ -283,7 +284,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo host.isSsoOnlyMode() || !ctx.context.options.emailAndPassword?.enabled ) { - return ctx.json({ outcome: 'sign_in' }); + return ctx.json({ success: true, data: { outcome: 'sign_in' } }); } } @@ -341,7 +342,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo if (!session) throw new APIError('INTERNAL_SERVER_ERROR', { code: 'INTERNAL_ERROR', message: 'Failed to create a session.' }); await setSessionCookie(ctx, { session, user }); await acceptAs(session.token, invitationId); - return ctx.json({ outcome: 'accepted', organizationId: invitation.organizationId }); + return ctx.json({ success: true, data: { outcome: 'accepted', organizationId: invitation.organizationId } }); }, ); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 06d25f34b39..11d4599fddb 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -260,7 +260,7 @@ describe('#34257 — accepting with the proof', () => { const res = await door(manager, { invitationId: invitation.id, proof, name: 'Newcomer', password: PASSWORD }); const text = await res.clone().text(); expect(res.status, text).toBe(200); - expect(JSON.parse(text)).toMatchObject({ outcome: 'accepted', organizationId: PARTNER_ORG }); + expect(JSON.parse(text)).toEqual({ success: true, data: { outcome: 'accepted', organizationId: PARTNER_ORG } }); const user = userRow(engine, 'newcomer@example.com'); expect(user?.email_verified).toBeTruthy(); @@ -279,7 +279,7 @@ describe('#34257 — accepting with the proof', () => { const res = await door(manager, { invitationId: invitation.id }, holder.cookie); expect(res.status, await res.clone().text()).toBe(200); - expect(await res.json()).toEqual({ outcome: 'verify_email' }); + expect((await res.json()).data).toEqual({ outcome: 'verify_email' }); const anonymous = await door(manager, { invitationId: invitation.id, name: 'X', password: PASSWORD }); expect(anonymous.status).toBe(401); @@ -346,7 +346,7 @@ describe('#34257 — accepting with the proof', () => { const res = await door(manager, { invitationId: invitation.id, proof, name: 'Owner', password: NEW_PASSWORD }); expect(res.status, await res.clone().text()).toBe(200); - expect(await res.json()).toMatchObject({ outcome: 'accepted' }); + expect((await res.json()).data).toMatchObject({ outcome: 'accepted' }); expect(await sessionUser(manager, earlier.cookie)).toBeNull(); expect(userRow(engine, 'squatted@example.com')?.email_verified).toBeTruthy(); @@ -369,7 +369,7 @@ describe('#34257 — accepting with the proof', () => { const res = await door(manager, { invitationId: invitation.id, proof, name: 'L', password: NEW_PASSWORD }); expect(res.status, await res.clone().text()).toBe(200); - expect(await res.json()).toEqual({ outcome: 'sign_in' }); + expect((await res.json()).data).toEqual({ outcome: 'sign_in' }); expect(await sessionUser(manager, holder.cookie)).not.toBeNull(); expect(invitationOf(engine, 'linked@example.com')?.status).toBe('pending'); @@ -377,7 +377,7 @@ describe('#34257 — accepting with the proof', () => { expect(samePassword.status, await samePassword.clone().text()).toBe(200); // Unspent: the same proof answers again. const again = await door(manager, { invitationId: invitation.id, proof, name: 'L', password: NEW_PASSWORD }); - expect(await again.json()).toEqual({ outcome: 'sign_in' }); + expect((await again.json()).data).toEqual({ outcome: 'sign_in' }); }); it('the door is rate-limited per invitation', async () => { @@ -398,9 +398,9 @@ describe('#34257 — accepting with the proof', () => { userRow(engine, 'verified@example.com')!.email_verified = true; const res = await door(manager, { invitationId: invitation.id, proof, name: 'V', password: NEW_PASSWORD }); - expect(await res.json()).toEqual({ outcome: 'sign_in' }); + expect((await res.json()).data).toEqual({ outcome: 'sign_in' }); const again = await door(manager, { invitationId: invitation.id, proof, name: 'V', password: NEW_PASSWORD }); - expect(await again.json()).toEqual({ outcome: 'sign_in' }); + expect((await again.json()).data).toEqual({ outcome: 'sign_in' }); expect(invitationOf(engine, 'verified@example.com')?.status).toBe('pending'); }); }); @@ -420,7 +420,7 @@ describe('#34257 — a signed-in return accepts only a verified address', () => const res = await door(manager, { invitationId: invitation.id }, person.cookie); expect(res.status, await res.clone().text()).toBe(200); - expect(await res.json()).toMatchObject({ outcome: 'accepted', organizationId: PARTNER_ORG }); + expect((await res.json()).data).toMatchObject({ outcome: 'accepted', organizationId: PARTNER_ORG }); expect(membersOf(engine, PARTNER_ORG, person.userId)).toHaveLength(1); }); @@ -430,7 +430,7 @@ describe('#34257 — a signed-in return accepts only a verified address', () => const person = await signUp(manager, engine, 'unsure@example.com'); const res = await door(manager, { invitationId: invitation.id }, person.cookie); - expect(await res.json()).toEqual({ outcome: 'verify_email' }); + expect((await res.json()).data).toEqual({ outcome: 'verify_email' }); expect(membersOf(engine, PARTNER_ORG, person.userId)).toHaveLength(0); expect(invitationOf(engine, 'unsure@example.com')?.status).toBe('pending'); }); diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 564e09e2738..05e40455218 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1471,6 +1471,12 @@ const PLUGIN_ROUTE_MODULES = { // nothing this file BUILDS departs from the envelope. 'packages/plugins/plugin-auth/src/list-user-invitations-verification.ts': {}, + // [#34257] FIRST AUDIT — the one-step invitation acceptance, a better-auth + // endpoint this repo defines (`POST /organization/accept-invitation-with-proof`). + // Every body it BUILDS is the envelope, `{ success: true, data: { outcome, … } }`; + // its refusals are `throw APIError.*`, raised rather than written. + 'packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts': {}, + // ── Ratchet: real, tracked, NOT blessed ───────────────────────────────── // // Measured by #9267 when this surface was added, not chosen. Each entry names diff --git a/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts b/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts index 0137dfc32d8..1f986ec9fd9 100644 --- a/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts +++ b/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts @@ -21,7 +21,7 @@ function clientAnswering(status: number, body: unknown) { describe('acceptInvitationWithProof (#34257)', () => { it('posts the input to the one-step door and answers the accepted outcome', async () => { - const { client, calls } = clientAnswering(200, { outcome: 'accepted', organizationId: 'org_1' }); + const { client, calls } = clientAnswering(200, { success: true, data: { outcome: 'accepted', organizationId: 'org_1' } }); const input = { invitationId: 'inv_1', proof: 'p1', name: 'Ada', password: 'S3cure!pass' }; await expect(client.acceptInvitationWithProof(input)).resolves.toEqual({ @@ -35,10 +35,10 @@ describe('acceptInvitationWithProof (#34257)', () => { it('answers the sign-in and verify-email outcomes as they are', async () => { await expect( - clientAnswering(200, { outcome: 'sign_in' }).client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' }), + clientAnswering(200, { success: true, data: { outcome: 'sign_in' } }).client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' }), ).resolves.toEqual({ outcome: 'sign_in' }); await expect( - clientAnswering(200, { outcome: 'verify_email' }).client.acceptInvitationWithProof({ invitationId: 'inv_1' }), + clientAnswering(200, { success: true, data: { outcome: 'verify_email' } }).client.acceptInvitationWithProof({ invitationId: 'inv_1' }), ).resolves.toEqual({ outcome: 'verify_email' }); }); @@ -51,7 +51,7 @@ describe('acceptInvitationWithProof (#34257)', () => { }); it('an answer outside the outcome vocabulary rejects', async () => { - const { client } = clientAnswering(200, { outcome: 'something_else' }); + const { client } = clientAnswering(200, { success: true, data: { outcome: 'something_else' } }); await expect(client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' })).rejects.toThrow( /unexpected response body/, ); diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts index 1893bc5eb39..a1482af3c9d 100644 --- a/ui/packages/auth/src/createAuthClient.ts +++ b/ui/packages/auth/src/createAuthClient.ts @@ -1393,7 +1393,12 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { body: JSON.stringify(input), }); const body = (await response.json().catch(() => null)) as - | { outcome?: unknown; organizationId?: unknown; code?: string; message?: string; error?: { code?: string; message?: string } } + | { + data?: { outcome?: unknown; organizationId?: unknown }; + code?: string; + message?: string; + error?: { code?: string; message?: string }; + } | null; if (!response.ok) { const code = body?.code ?? body?.error?.code; @@ -1404,10 +1409,12 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { err.status = response.status; throw err; } - if (body?.outcome === 'accepted' && typeof body.organizationId === 'string') { - return { outcome: 'accepted', organizationId: body.organizationId }; + // A success answers in the envelope, `{ success: true, data }`. + const data = body?.data; + if (data?.outcome === 'accepted' && typeof data.organizationId === 'string') { + return { outcome: 'accepted', organizationId: data.organizationId }; } - if (body?.outcome === 'sign_in' || body?.outcome === 'verify_email') return { outcome: body.outcome }; + if (data?.outcome === 'sign_in' || data?.outcome === 'verify_email') return { outcome: data.outcome }; throw new Error('acceptInvitationWithProof: unexpected response body'); }, From 9b95ba90952671756cb99a439b31a4a99aa0be20 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:24:00 +0000 Subject: [PATCH 14/26] chore(changeset): state the one-step acceptance at rule level Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/34257-one-step-invitation-acceptance.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index 21746e473c9..6e1a3fe8131 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -12,9 +12,9 @@ feat(auth): an invitation is accepted in one step with the proof its mail carrie Clause-②: yes (widening) Metadata-protocol: none -- **The invitation mail carries a mailbox proof.** The accept link in the mail ends with `#proof=…`. The server keeps only a hash of the proof, bound to the invitation's address and expiry. A resend retires the earlier proof. The stored mail row never holds the proof, and the console's copy-link action answers the link without it. -- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-with-proof` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had), verifies the address, accepts the invitation and signs in. A proof is single-use. A proof that does not admit is refused with one `INVALID_TOKEN` answer and leaves the real proof usable. The door is rate-limited per client address and per invitation, and runs the sign-up gates: who may sign up, password length, complexity and breach checks, SSO-only mode. +- **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. +- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-with-proof` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had), verifies the address, accepts the invitation and signs in. A proof is single-use. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client address and per invitation, and runs the sign-up gates: who may sign up, password length, complexity and breach checks, SSO-only mode. - **An address with an account signs in as today.** When the address belongs to a verified account, an account with a linked provider, a second factor or a directory-managed account, the door answers `sign_in` and the proof stays unspent. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. - **`SendTemplateInput.deliverOnly`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row. A send carrying them is delivered inline, never through the durable queue. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. -- **The accept page offers one form.** A signed-out visitor whose link carries the proof sees a name and password form, or a provider sign-in, in place of the sign-in redirect. The proof is cleared from the address bar once read. A provider sign-in returns to the page, which redeems the invitation for the new session. A link without the proof keeps today's path. The `@object-ui/auth` client gains `acceptInvitationWithProof`. +- **The accept page offers one form.** A signed-out visitor whose link carries the proof sees a name and password form, or a provider sign-in, in place of the sign-in redirect. The accept page does not keep the proof in its address. A provider sign-in returns to the page, which redeems the invitation for the new session. A link without the proof keeps today's path. The `@object-ui/auth` client gains `acceptInvitationWithProof`. From fbe5bfd1505192d7390f71b9f0d6ce3ac70d5792 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:35:05 +0000 Subject: [PATCH 15/26] test(auth): pin every gate of the invitation proof door Each gate refuses before anything is written and leaves the proof usable; the anonymous session-mode refusal asserts its code. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- ...vitation-one-step-acceptance-34257.test.ts | 181 +++++++++++++++++- 1 file changed, 180 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 11d4599fddb..af5d9df2126 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -6,6 +6,7 @@ // plugin, audience gate, membership reconciler, ObjectQL adapter), over the // same minimal engine double the other end-to-end auth-manager suites use. +import { createHash } from 'node:crypto'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql'; import { AuthManager } from './auth-manager'; @@ -165,7 +166,7 @@ const proofOf = (mail: SentMail): string => { return decodeURIComponent(match![1]!); }; -const boot = async () => { +const boot = async (options: Record = {}) => { const engine = createMemoryEngine(); engine.tables.set('sys_organization', [ { id: DEFAULT_ORG, name: 'Default', slug: 'default' }, @@ -177,6 +178,7 @@ const boot = async () => { dataEngine: engine as any, membershipPolicy: 'auto', getTenancy: () => singleOrgTenancy(), + ...options, }); const sent: SentMail[] = []; manager.setEmailService({ @@ -283,6 +285,7 @@ describe('#34257 — accepting with the proof', () => { const anonymous = await door(manager, { invitationId: invitation.id, name: 'X', password: PASSWORD }); expect(anonymous.status).toBe(401); + expect((await anonymous.json()).code).toBe('UNAUTHENTICATED'); expect(userRow(engine, 'unverified@example.com')?.email_verified).toBeFalsy(); expect(invitationOf(engine, 'unverified@example.com')?.status).toBe('pending'); @@ -435,3 +438,179 @@ describe('#34257 — a signed-in return accepts only a verified address', () => expect(invitationOf(engine, 'unsure@example.com')?.status).toBe('pending'); }); }); + +// The tables a redemption writes: the account, its credential, its sessions, +// the membership, the invitation and the proof row. +const WRITTEN_TABLES = ['sys_user', 'sys_account', 'sys_session', 'sys_member', 'sys_invitation', 'sys_verification']; +const writtenState = (engine: MemoryEngine) => + JSON.stringify(WRITTEN_TABLES.map((table) => [table, engine.tables.get(table) ?? []])); + +const expectAnswer = async (res: Response, status: number, code: string) => { + const text = await res.clone().text(); + expect(res.status, text).toBe(status); + expect(JSON.parse(text).code, text).toBe(code); +}; + +const expectSignIn = async (res: Response) => { + const text = await res.clone().text(); + expect(res.status, text).toBe(200); + expect(JSON.parse(text).data).toEqual({ outcome: 'sign_in' }); +}; + +const expectAccepted = async (res: Response) => { + const text = await res.clone().text(); + expect(res.status, text).toBe(200); + expect(JSON.parse(text).data).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); +}; + +describe('#34257 — every gate refuses before anything is written, and the proof stays usable', () => { + beforeEach(() => { + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + }); + afterEach(() => vi.restoreAllMocks()); + + it('a new address is refused where email sign-up is switched off', async () => { + const { engine, manager, invite } = await boot({ emailAndPassword: { disableSignUp: true } }); + const { invitation, proof } = await invite('closed@example.com'); + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'C', password: PASSWORD }), 403, 'PERMISSION_DENIED'); + expect(writtenState(engine)).toBe(before); + + manager.applyConfigPatch({ emailAndPassword: { disableSignUp: false } } as never); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'C', password: PASSWORD })); + }); + + it('a new address is refused in SSO-only mode', async () => { + const { engine, manager, invite } = await boot({ ssoOnlyMode: true }); + const { invitation, proof } = await invite('sso-new@example.com'); + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: PASSWORD }), 403, 'PERMISSION_DENIED'); + expect(writtenState(engine)).toBe(before); + + manager.applyConfigPatch({ ssoOnlyMode: false } as never); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: PASSWORD })); + }); + + it('an unverified account in SSO-only mode signs in as today, and the proof stays unspent', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('sso-held@example.com'); + await signUp(manager, engine, 'sso-held@example.com'); + manager.applyConfigPatch({ ssoOnlyMode: true } as never); + const before = writtenState(engine); + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); + expect(writtenState(engine)).toBe(before); + + manager.applyConfigPatch({ ssoOnlyMode: false } as never); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); + }); + + it('an unverified account with a second factor signs in as today, and the proof stays unspent', async () => { + const { engine, manager, invite } = await boot({ plugins: { twoFactor: true } }); + const { invitation, proof } = await invite('two-factor@example.com'); + await signUp(manager, engine, 'two-factor@example.com'); + userRow(engine, 'two-factor@example.com')!.two_factor_enabled = true; + const before = writtenState(engine); + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'T', password: NEW_PASSWORD })); + expect(writtenState(engine)).toBe(before); + + userRow(engine, 'two-factor@example.com')!.two_factor_enabled = false; + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'T', password: NEW_PASSWORD })); + }); + + it.each([ + ['provisioned by an identity provider', 'idp_provisioned'], + ['pending its first SSO sign-in', 'idp_pending'], + ])('an unverified account %s signs in as today, and the proof stays unspent', async (_label, source) => { + const { engine, manager, invite } = await boot(); + const email = `directory-${source}@example.com`; + const { invitation, proof } = await invite(email); + await signUp(manager, engine, email); + userRow(engine, email)!.source = source; + const before = writtenState(engine); + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'D', password: NEW_PASSWORD })); + expect(writtenState(engine)).toBe(before); + + userRow(engine, email)!.source = null; + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'D', password: NEW_PASSWORD })); + }); + + it('a password under the minimum length is refused', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('short@example.com'); + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: 'Ab1!' }), 400, 'PASSWORD_POLICY_VIOLATION'); + expect(writtenState(engine)).toBe(before); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: PASSWORD })); + }); + + it('a password the complexity policy refuses is refused', async () => { + const { engine, manager, invite } = await boot({ passwordRequireComplexity: true }); + const { invitation, proof } = await invite('simple@example.com'); + const before = writtenState(engine); + + await expectAnswer( + await door(manager, { invitationId: invitation.id, proof, name: 'S', password: 'onlylowercaseletters' }), + 400, + 'PASSWORD_POLICY_VIOLATION', + ); + expect(writtenState(engine)).toBe(before); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: PASSWORD })); + }); + + it('a breached password is refused, and the proof stays usable', async () => { + const BREACHED = 'Br3ached!Passw0rd-list'; + const digest = createHash('sha1').update(BREACHED).digest('hex').toUpperCase(); + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: any) => { + const url = String(input instanceof Request ? input.url : input); + if (!url.startsWith('https://api.pwnedpasswords.com/range/')) throw new Error(`unexpected fetch: ${url}`); + const listed = url.endsWith(`/${digest.slice(0, 5)}`) ? `${digest.slice(5)}:42` : '0000000000000000000000000000000000A:1'; + return new Response(listed, { status: 200, headers: { 'content-type': 'text/plain' } }); + }); + const { engine, manager, invite } = await boot({ plugins: { passwordRejectBreached: true } }); + const { invitation, proof } = await invite('breached@example.com'); + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'B', password: BREACHED }), 400, 'PASSWORD_COMPROMISED'); + expect(writtenState(engine)).toBe(before); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'B', password: PASSWORD })); + }); + + it('a new address the audience admission refuses is refused', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('refused@example.com'); + // A posture outside the vocabulary refuses every self-serve creation. The + // entry validation refuses one at the door, so it is set behind it. + const config = (manager as unknown as { config: Record }).config; + const standing = config.audience; + config.audience = { posture: 'not_a_posture' }; + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: PASSWORD }), 403, 'AUTH_CONFIG_ERROR'); + expect(writtenState(engine)).toBe(before); + + config.audience = standing; + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: PASSWORD })); + }); + + it('a new address with no name is refused', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('nameless@example.com'); + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: ' ', password: PASSWORD }), 400, 'VALIDATION_ERROR'); + expect(writtenState(engine)).toBe(before); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'Named', password: PASSWORD })); + }); +}); From d7bec5f031f39061e4a36b8a4fe96ac64c8fe826 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:35:56 +0000 Subject: [PATCH 16/26] docs(auth): name the door's rate limit per client address Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- ...t-model-anonymous-principal-doors-grants-and-organization.md | 2 +- packages/plugins/plugin-auth/src/auth-route-ledger.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index 7cb6d70b304..f7b8b1a5418 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -315,7 +315,7 @@ is never at rest in clear, the stored mail row never holds it, and it is single- invitation, its address and its expiry; a resend retires the old one. Every proof that does not admit gets one refusal that does not say which check failed. An address whose account is verified, is linked to a provider, or otherwise takes no password from this door is answered "sign in", with the -proof unspent. It carries a per-address and per-invitation rate limit, as ADR-0121 D6 requires. +proof unspent. It carries a rate limit per client address and per invitation, as ADR-0121 D6 requires. Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in `packages/plugins/plugin-auth/src/auth-route-ledger.ts`; it sits in the `/auth` namespace and is classified under class 2 the way the preview above is. diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 57e647010a0..79a0df37cbd 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -299,7 +299,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ { route: 'POST /api/v1/auth/sys-oauth-application/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application create action posts it directly; session-required self-service wrapper over better-auth /oauth2/create-client that splits the Console\'s newline-separated redirect-URL textarea into the redirect_uris array the vendor schema requires' }, { route: 'POST /api/v1/auth/sys-session/revoke', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_session revoke_session row action posts it directly with the row id; the server resolves the session from the id, so the session token never travels to or from the console. The session owner is re-dispatched to better-auth /revoke-session; another user\'s session is revocable by a platform admin only (ADR-0068 D2), tombstoned with reason admin (ADR-0069 D4)' }, { route: 'POST /api/v1/auth/organization/accept-invitation', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.invitations.accept', requires: 'organization' }, - { route: 'POST /api/v1/auth/organization/accept-invitation-with-proof', family: 'organization', source: 'better-auth', disposition: 'public', requires: 'organization', note: 'the one-step invitation acceptance (invitation-mailbox-proof.ts): an ObjectStack endpoint on the catch-all, answering a caller with NO session that presents the mailbox proof only the invitation mail carries. With a valid proof it creates the account (or sets the password of an unverified one with no linked provider account, revoking its sessions), marks the address verified, accepts through the vendor accept route and signs the person in; an address with an account the one-step path does not touch answers outcome sign_in, unspent. Every proof that does not admit answers one 400 INVALID_TOKEN. Single-use, bound to the invitation, its address and its expiry; rate-limited per address and per invitation. Without a proof it serves a signed-in session whose address is the invited one and verified. The vendor accept route is unchanged' }, + { route: 'POST /api/v1/auth/organization/accept-invitation-with-proof', family: 'organization', source: 'better-auth', disposition: 'public', requires: 'organization', note: 'the one-step invitation acceptance (invitation-mailbox-proof.ts): an ObjectStack endpoint on the catch-all, answering a caller with NO session that presents the mailbox proof only the invitation mail carries. With a valid proof it creates the account (or sets the password of an unverified one with no linked provider account, revoking its sessions), marks the address verified, accepts through the vendor accept route and signs the person in; an address with an account the one-step path does not touch answers outcome sign_in, unspent. Every proof that does not admit answers one 400 INVALID_TOKEN. Single-use, bound to the invitation, its address and its expiry; rate-limited per client address and per invitation. Without a proof it serves a signed-in session whose address is the invited one and verified. The vendor accept route is unchanged' }, // #9941 — better-auth declares `addMember` with NO HTTP path (server-only // `auth.api.addMember`; measured on the installed 1.7.1), so the catch-all // never publishes it and it is correctly ABSENT from From 2d7ac400c66e5ba02e4ef8b8ce819fb3b31bb2d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:56:56 +0000 Subject: [PATCH 17/26] feat(auth): close the one-step door on a managed environment, stamp its password, rename it The door answers the cloud-managed refusal before reading a proof, writes the password-age stamp and forced-change clear, ledgers the sessions it ends, states its closing rule for existing accounts, and is renamed accept-invitation-one-step; SendTemplateInput.deliverOnly becomes deliverOnlyData. Pins every gate and state. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../34257-one-step-invitation-acceptance.md | 11 +- ...principal-doors-grants-and-organization.md | 56 ++-- .../src/auth-manager-before-hook.ts | 4 +- .../src/auth-manager-organization-plugin.ts | 2 +- .../src/auth-manager-plugin-list.ts | 37 ++- .../plugins/plugin-auth/src/auth-manager.ts | 1 + .../plugins/plugin-auth/src/auth-plugin.ts | 3 +- .../plugin-auth/src/auth-route-ledger.ts | 4 +- .../plugins/plugin-auth/src/cloud-managed.ts | 11 +- .../src/invitation-mailbox-proof.ts | 136 +++++++-- ...vitation-one-step-acceptance-34257.test.ts | 278 ++++++++++++++---- .../plugin-auth/src/session-tombstone.ts | 9 +- .../src/sso-only-local-password.ts | 7 +- .../plugins/plugin-email/src/email-service.ts | 8 +- .../send-template-deliver-only-34257.test.ts | 6 +- .../anonymous-door-sweep.classification.ts | 24 +- .../test/anonymous-door-sweep.dogfood.test.ts | 12 + packages/spec/src/contracts/email-service.ts | 13 +- scripts/check-route-envelope.mjs | 2 +- .../acceptInvitationOneStep-34257.test.tsx | 20 +- .../manage/AcceptInvitationPage.tsx | 14 +- ui/packages/auth/src/AuthContext.ts | 6 +- ui/packages/auth/src/AuthProvider.tsx | 12 +- ... => acceptInvitationOneStep-34257.test.ts} | 18 +- ui/packages/auth/src/createAuthClient.ts | 8 +- ui/packages/auth/src/index.ts | 4 +- ui/packages/auth/src/types.ts | 8 +- ui/packages/auth/src/useAuth.ts | 2 +- 28 files changed, 517 insertions(+), 199 deletions(-) rename ui/packages/auth/src/__tests__/{acceptInvitationWithProof-34257.test.ts => acceptInvitationOneStep-34257.test.ts} (73%) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index 6e1a3fe8131..c0ac2600689 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -12,9 +12,10 @@ feat(auth): an invitation is accepted in one step with the proof its mail carrie Clause-②: yes (widening) Metadata-protocol: none -- **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. -- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-with-proof` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had), verifies the address, accepts the invitation and signs in. A proof is single-use. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client address and per invitation, and runs the sign-up gates: who may sign up, password length, complexity and breach checks, SSO-only mode. -- **An address with an account signs in as today.** When the address belongs to a verified account, an account with a linked provider, a second factor or a directory-managed account, the door answers `sign_in` and the proof stays unspent. +- **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row. +- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. +- **An address with an account signs in as today.** The door sets a password on an existing account only when the account's address is not verified and the mailbox is its one claim: an account that is verified, linked to a provider, enrolled in a second factor, provisioned by an identity provider, waiting for its first single sign-on or whose source cannot be read, or a server in SSO-only mode or with email and password off, answers `sign_in`, and the proof stays unspent. +- **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. -- **`SendTemplateInput.deliverOnly`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row. A send carrying them is delivered inline, never through the durable queue. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. -- **The accept page offers one form.** A signed-out visitor whose link carries the proof sees a name and password form, or a provider sign-in, in place of the sign-in redirect. The accept page does not keep the proof in its address. A provider sign-in returns to the page, which redeems the invitation for the new session. A link without the proof keeps today's path. The `@object-ui/auth` client gains `acceptInvitationWithProof`. +- **`SendTemplateInput.deliverOnlyData`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row, which gives no sign they were overlaid. Required template variables are checked against `data` alone. A send carrying them is delivered inline, never through the durable queue, so its sender gives up queued delivery where a queue is mounted. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. +- **The accept page offers one form.** A signed-out visitor whose link carries the proof sees a name and password form, or a provider sign-in, in place of the sign-in redirect. The accept page does not keep the proof in its address. A provider sign-in returns to the page, which redeems the invitation for the new session. A link without the proof keeps today's path. The `@object-ui/auth` client gains `acceptInvitationOneStep`, with the types `AuthInvitationOneStepInput` and `AuthInvitationOneStepOutcome`. diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index f7b8b1a5418..79f29791b3c 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -301,37 +301,41 @@ infrastructure. The same ruling's Q2 B leaves the verification posture as it was invitation-link sign-up still owes the verification mail. **Amended 2026-11-16 — the one-step invitation acceptance and the OAuth client-name read, class-2-shaped doors.** Card -[#34257](https://github.com/objectstack-ai/objectstack/issues/34257), on the owning seat's rulings in -claim amendment -[`6906424686`](https://github.com/objectstack-ai/objectstack/issues/34257#issuecomment-6906424686), -admits one more door of class 2's shape, not a seventh class: -`POST /api/v1/auth/organization/accept-invitation-with-proof`. What admits the request: the mailbox -proof the invitation mail carries, a capability token minted per send. The invitation id alone, which -the copied link and the invitation row carry, admits nothing. What it runs as: after validation, the -creation of the invited address's account (or the replacement of the password of an unverified -account with no linked provider account, revoking its sessions), the address marked verified, the -invitation accepted through the vendor's own accept route, and a session for that account. The proof -is never at rest in clear, the stored mail row never holds it, and it is single-use and bound to the -invitation, its address and its expiry; a resend retires the old one. Every proof that does not admit -gets one refusal that does not say which check failed. An address whose account is verified, is -linked to a provider, or otherwise takes no password from this door is answered "sign in", with the -proof unspent. It carries a rate limit per client address and per invitation, as ADR-0121 D6 requires. -Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, -ledgered in `packages/plugins/plugin-auth/src/auth-route-ledger.ts`; it sits in the `/auth` -namespace and is classified under class 2 the way the preview above is. +[#34257](https://github.com/objectstack-ai/objectstack/issues/34257) admits one more door of class 2's shape, not a +seventh class: `POST /api/v1/auth/organization/accept-invitation-one-step`. What admits the request: the mailbox +proof the invitation mail carries, a capability token minted per send. The invitation id alone, which the copied link +and the invitation row carry, admits nothing. What it runs as: after validation, the creation of the invited +address's account (or the replacement of the password of an unverified account whose mailbox is its one claim, +revoking its sessions), the address marked verified, the invitation accepted through the vendor's own accept route, +and a session for that account. The proof is never at rest in clear, the stored mail row never holds it, and it is +bound to the invitation, its address and its expiry; a resend retires the old one. It is spent only by a request that +passed every gate, and one server process serializes concurrent redemptions of it; across processes, single use is +as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check +failed. An address whose account is verified, is linked to a provider, or otherwise takes no password from this door +is answered "sign in", with the proof unspent. A cloud-managed environment sets no local password, so there the door +refuses every request that carries a proof. It carries a rate limit per client network address and per invitation, +as ADR-0121 D6 requires. Enforced by +`packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in +`packages/plugins/plugin-auth/src/auth-route-ledger.ts`. It is a better-auth endpoint, so it rides the `/auth` +catch-all, which no route table lists door by door: the anonymous sweep's classification names it under class 2 as a +door the catch-all serves, and probes it by its own path. The same amendment admits a second door of class 2's shape, added by [#34168](https://github.com/objectstack-ai/objectstack/issues/34168): `GET /api/v1/auth/oauth2/client-name`, a public read. What admits the request: a request the server itself signed, which names one OAuth client. What it answers: that client's display name and nothing -else, and only for the client the signed request names. Every other request gets one uniform 404. -It is rate-limited per client address on the counter the invitation preview above uses, as ADR-0121 D6 requires. - -This refines ruling [`6413975861`](https://github.com/objectstack-ai/objectstack/issues/26020#issuecomment-6413975861) -Q2 B, recorded above as "an invitation-link sign-up still owes the verification mail". A -proof-carrying invitation link proves the mailbox, so a sign-up through it owes no verification mail. -A copied link, which carries no proof, still owes the verification mail, as Q2 B states. The vendor -accept route is unchanged by this note. +else, and only for the client the signed request names. Every request with a well-formed query that is +not served a name gets one uniform 404; a malformed query answers 400, and a caller over the rate limit +429. It is rate-limited per client network address on the counter the invitation preview above uses, as +ADR-0121 D6 requires. Mounted ahead of the catch-all like the preview, it is classified under class 2 by +its route. + +This note states a refinement of ruling +[`6413975861`](https://github.com/objectstack-ai/objectstack/issues/26020#issuecomment-6413975861) Q2 B, recorded +above as "an invitation-link sign-up still owes the verification mail": a proof-carrying invitation link proves the +mailbox, so a sign-up through it owes no verification mail, and a copied link, which carries no proof, still owes the +verification mail, as Q2 B states. The refinement is the maintainer's to approve, on this note's Tier H hand-off; +until that approval it binds nothing. The vendor accept route is unchanged by this note. **Outside the guest model by construction**, and not on the list: diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index de6e1dbe145..7256f90266d 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -58,7 +58,7 @@ * Nothing re-exports this module, so the published surface does not move. */ -import { ACCEPT_INVITATION_WITH_PROOF_PATH } from './invitation-mailbox-proof.js'; +import { ACCEPT_INVITATION_ONE_STEP_PATH } from './invitation-mailbox-proof.js'; import { isCloudManaged } from '@objectstack/core'; import { VENDOR_ROLE_SCALAR_ADMIN_PATHS } from './admin-impersonate-endpoint.js'; import { setAuthActorResolver } from './auth-actor-attribution.js'; @@ -337,7 +337,7 @@ export async function globalBeforeHook( ctx?.path === '/sign-up/email' || ctx?.path === '/reset-password' || ctx?.path === '/change-password' || - ctx?.path === ACCEPT_INVITATION_WITH_PROOF_PATH + ctx?.path === ACCEPT_INVITATION_ONE_STEP_PATH ) { const candidate = (typeof ctx?.body?.password === 'string' && ctx.body.password) || diff --git a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts index 3ea7ea644dd..9a51cffffee 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts @@ -659,7 +659,7 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { template: 'auth.invitation', to: recipientEmail, ...mailLocale, - ...(proof ? { deliverOnly: { acceptUrl: withInvitationProof(acceptUrl, proof) } } : {}), + ...(proof ? { deliverOnlyData: { acceptUrl: withInvitationProof(acceptUrl, proof) } } : {}), data: { inviter: { name: inviter?.user?.name ?? inviter?.user?.email ?? 'A teammate', diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index ffb65b9dff9..e2a4564d7e6 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -64,7 +64,7 @@ import { resolveUserAuthzGrants } from '@objectstack/core'; import { applyPlatformAdminImpersonation } from './admin-impersonate-endpoint.js'; import { requireSecondFactorAtCodeAndLinkDoors } from './second-factor-code-and-link-doors.js'; import { buildOrganizationPlugin, type OrganizationPluginHost } from './auth-manager-organization-plugin.js'; -import { ACCEPT_INVITATION_WITH_PROOF_PATH, buildInvitationProofDoorPlugin } from './invitation-mailbox-proof.js'; +import { ACCEPT_INVITATION_ONE_STEP_PATH, buildInvitationProofDoorPlugin } from './invitation-mailbox-proof.js'; import { OAUTH_ORGANIZATION_CLAIM, assertScimAdminCoherence, @@ -132,10 +132,29 @@ export interface PluginListHost { resolveAuthSecret: AuthManager['resolveAuthSecret']; resolveMembershipRole: AuthManager['resolveMembershipRole']; resolveTwoFactorAccountLockout: AuthManager['resolveTwoFactorAccountLockout']; + stampPasswordChangedAt: AuthManager['stampPasswordChangedAt']; storedRecipientLocale: AuthManager['storedRecipientLocale']; validateAudienceAdmission: AuthManager['validateAudienceAdmission']; } +/** + * better-auth's `haveIBeenPwned` default door list, as the installed vendor + * declares it. Handing the plugin an explicit list replaces that default, so + * the list the platform hands it is this one plus the one-step invitation + * acceptance; the card's test reads the installed vendor default and pins the + * two equal, so a vendor that grows its list reds that test instead of + * silently losing the addition. + */ +export const BREACH_CHECK_VENDOR_DEFAULT_PATHS: readonly string[] = [ + '/sign-up/email', + '/change-password', + '/reset-password', + '/email-otp/reset-password', + '/phone-number/reset-password', + '/admin/create-user', + '/admin/set-user-password', +]; + /** * The body of `AuthManager.buildPluginList()`; the method's docblock and the * comments in it are its contract. @@ -288,6 +307,7 @@ export async function buildPluginList(this: PluginListHost): Promise { isSsoOnlyMode: () => this.isSsoOnlyMode(), getDataEngine: () => this.getDataEngine(), counterStore: () => this.config.sharedCounterStore?.() ?? Promise.reject(new Error('no shared counter store')), + stampPasswordChangedAt: (userId) => this.stampPasswordChangedAt(userId), })); } @@ -314,18 +334,9 @@ export async function buildPluginList(this: PluginListHost): Promise { if (enabled.passwordRejectBreached) { const { haveIBeenPwned } = await import('better-auth/plugins/haveibeenpwned'); plugins.push(haveIBeenPwned({ - // The plugin's own default doors, plus the invitation proof door, which - // sets a password too. - paths: [ - '/sign-up/email', - '/change-password', - '/reset-password', - '/email-otp/reset-password', - '/phone-number/reset-password', - '/admin/create-user', - '/admin/set-user-password', - ACCEPT_INVITATION_WITH_PROOF_PATH, - ], + // The plugin's own default doors, plus the one-step invitation + // acceptance, which sets a password too. + paths: [...BREACH_CHECK_VENDOR_DEFAULT_PATHS, ACCEPT_INVITATION_ONE_STEP_PATH], customPasswordCompromisedMessage: 'This password has appeared in a known data breach. Please choose a different one.', })); diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 4a73380eff6..853e5dae650 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -2449,6 +2449,7 @@ export class AuthManager { resolveAuthSecret: (...a) => this.resolveAuthSecret(...a), resolveMembershipRole: (...a) => this.resolveMembershipRole(...a), resolveTwoFactorAccountLockout: (...a) => this.resolveTwoFactorAccountLockout(...a), + stampPasswordChangedAt: (...a) => this.stampPasswordChangedAt(...a), storedRecipientLocale: (...a) => this.storedRecipientLocale(...a), validateAudienceAdmission: (...a) => this.validateAudienceAdmission(...a), }; diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index fd77a75ba04..dfcd797151a 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -169,6 +169,7 @@ import { cloudManagedRefusal } from './cloud-managed.js'; import { identitySourceUnreadable, judgeSsoOnlyLocalPassword, readUserSource, ssoOnlyPasswordRefusal } from './sso-only-local-password.js'; import { isPendingSsoSource, pendingSsoPasswordRefusal } from './pending-sso-marker.js'; import { registerCopyInvitationLinkAction } from './invitation-link-action.js'; +import { ACCEPT_INVITATION_ONE_STEP_PATH } from './invitation-mailbox-proof.js'; import { ALLOWED_IP_RANGES_ENV, allowedIpRangesWritePredicate, @@ -2760,7 +2761,7 @@ export class AuthPlugin implements Plugin { '/sign-up/email': { window, max }, '/request-password-reset': { window, max }, '/reset-password': { window, max }, - '/organization/accept-invitation-with-proof': { window, max }, + [ACCEPT_INVITATION_ONE_STEP_PATH]: { window, max }, // #2780 — OTP endpoints cost an SMS per hit (pumping abuse); // the per-number cooldown (otp-send-guard.ts) is always on, // this adds the operator-tuned per-IP dimension. The plugin diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 79a0df37cbd..2c447fb8426 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -299,7 +299,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ { route: 'POST /api/v1/auth/sys-oauth-application/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application create action posts it directly; session-required self-service wrapper over better-auth /oauth2/create-client that splits the Console\'s newline-separated redirect-URL textarea into the redirect_uris array the vendor schema requires' }, { route: 'POST /api/v1/auth/sys-session/revoke', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_session revoke_session row action posts it directly with the row id; the server resolves the session from the id, so the session token never travels to or from the console. The session owner is re-dispatched to better-auth /revoke-session; another user\'s session is revocable by a platform admin only (ADR-0068 D2), tombstoned with reason admin (ADR-0069 D4)' }, { route: 'POST /api/v1/auth/organization/accept-invitation', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.invitations.accept', requires: 'organization' }, - { route: 'POST /api/v1/auth/organization/accept-invitation-with-proof', family: 'organization', source: 'better-auth', disposition: 'public', requires: 'organization', note: 'the one-step invitation acceptance (invitation-mailbox-proof.ts): an ObjectStack endpoint on the catch-all, answering a caller with NO session that presents the mailbox proof only the invitation mail carries. With a valid proof it creates the account (or sets the password of an unverified one with no linked provider account, revoking its sessions), marks the address verified, accepts through the vendor accept route and signs the person in; an address with an account the one-step path does not touch answers outcome sign_in, unspent. Every proof that does not admit answers one 400 INVALID_TOKEN. Single-use, bound to the invitation, its address and its expiry; rate-limited per client address and per invitation. Without a proof it serves a signed-in session whose address is the invited one and verified. The vendor accept route is unchanged' }, + { route: 'POST /api/v1/auth/organization/accept-invitation-one-step', family: 'organization', source: 'better-auth', disposition: 'public', requires: 'organization', note: 'the one-step invitation acceptance (invitation-mailbox-proof.ts): an ObjectStack endpoint on the catch-all, answering a caller with NO session that presents the mailbox proof only the invitation mail carries. With a valid proof it creates the account (or sets the password of an unverified one with no linked provider account, revoking its sessions), marks the address verified, accepts through the vendor accept route and signs the person in; an address with an account the one-step path does not touch answers outcome sign_in, unspent. Every proof that does not admit answers one 400 INVALID_TOKEN. Single-use (spent only by a request that passed every gate), bound to the invitation, its address and its expiry; rate-limited per client network address and per invitation. On a cloud-managed environment a request carrying a proof answers 409 RESOURCE_CONFLICT, the proof unspent. Without a proof it serves a signed-in session whose address is the invited one and verified. The vendor accept route is unchanged' }, // #9941 — better-auth declares `addMember` with NO HTTP path (server-only // `auth.api.addMember`; measured on the installed 1.7.1), so the catch-all // never publishes it and it is correctly ABSENT from @@ -481,7 +481,7 @@ export const BETTER_AUTH_MOUNTED_SURFACE: readonly string[] = [ 'POST /api/v1/auth/oauth2/update-consent', 'POST /api/v1/auth/oauth2/userinfo', 'POST /api/v1/auth/organization/accept-invitation', - 'POST /api/v1/auth/organization/accept-invitation-with-proof', + 'POST /api/v1/auth/organization/accept-invitation-one-step', 'POST /api/v1/auth/organization/add-team-member', 'POST /api/v1/auth/organization/cancel-invitation', 'POST /api/v1/auth/organization/check-slug', diff --git a/packages/plugins/plugin-auth/src/cloud-managed.ts b/packages/plugins/plugin-auth/src/cloud-managed.ts index 857ae5f94e5..9f021f2df62 100644 --- a/packages/plugins/plugin-auth/src/cloud-managed.ts +++ b/packages/plugins/plugin-auth/src/cloud-managed.ts @@ -25,7 +25,11 @@ * creates the credential when the user holds none) refuse every request, with * the two doors that send their link or code (`/request-password-reset`, * `/phone-number/request-password-reset`), so nobody is sent a link the reset - * door would refuse. A password set before stays where it is (changing one is + * door would refuse; and the one-step invitation acceptance + * (`/organization/accept-invitation-one-step`, `invitation-mailbox-proof.ts`), + * which creates an account with a password or sets one on an unverified + * account, refuses every request that carries the invitation mail's proof, + * before the proof is read. A password set before stays where it is (changing one is * `/change-password`'s, objectstack-ai/cloud#4471). ADR-0135 D5.2's * break-glass clause, which kept a local credential reachable by population, * holds on self-hosted deployments only. @@ -83,6 +87,11 @@ export const CLOUD_MANAGED_REFUSAL_MESSAGES = { requestPasswordReset: "This environment is cloud-managed: you sign in through the hosting organisation's identity provider, and no " + 'local password is set or reset here for anyone, an administrator included. No reset link or code was sent.', + // `/organization/accept-invitation-one-step` with the invitation mail's proof. + acceptInvitationOneStep: + "This environment is cloud-managed: you sign in through the hosting organisation's identity provider, and no " + + 'local password is set here for anyone, so an invitation is not accepted with a new password. Sign in through ' + + 'that identity provider instead. No account or password was changed.', } as const; /** The doors a cloud-managed environment narrows. */ diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 7135018c770..79ff3d9172c 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -19,7 +19,7 @@ * - Minted by `sendInvitationEmail` for each send, a resend included, and put * in the mail's link only, after `#`, as `proof=VALUE` * ({@link withInvitationProof}). The mail goes out through - * `SendTemplateInput.deliverOnly`, so the stored mail row never holds it. + * `SendTemplateInput.deliverOnlyData`, so the stored mail row never holds it. * - Never at rest in clear. One `sys_verification` row per invitation, * identifier {@link invitationProofIdentifier}, holds the proof's SHA-256, * the invited address and the invitation's expiry, with the invitation's @@ -28,12 +28,17 @@ * verification value. * - Bound to the invitation, its address and its expiry: the door requires * all three to match the invitation as it stands. - * - Single-use: spent by the internal adapter's atomic consume, before any - * side effect. A proof that does not match is not spent. + * - Single-use: spent through the internal adapter's consume before any + * write, and only by a request that passed every gate; a proof that does + * not match, or a request a gate refuses, leaves it unspent. Within one + * server process concurrent redemptions of one proof are serialized, so + * exactly one succeeds. Across server processes the guarantee is the + * store's: on the platform's own adapter the consume reads the row and + * then deletes it, which is not one atomic step. * - A resend retires the old proof: the mint deletes the invitation's row * before writing the new one. * - * ## The door — `POST /organization/accept-invitation-with-proof` + * ## The door — `POST /organization/accept-invitation-one-step` * * Body `{ invitationId, proof, name, password }`, or `{ invitationId }` alone * from a signed-in session (the social return). Answers in the envelope, @@ -42,33 +47,50 @@ * - `{ outcome: 'accepted', organizationId }` — the invitation is accepted and * the caller is signed in. * - `{ outcome: 'sign_in' }` — the proof is good, and the address has an - * account the one-step path does not set a password on (verified, linked to - * a provider, second factor enrolled, or managed by an identity provider). - * The proof is not spent; the person signs in as today. + * account the one-step path does not set a password on (the closing rule + * below). The proof is not spent; the person signs in as today. * - `{ outcome: 'verify_email' }` — session mode, and the session's address is * not verified. Nothing is accepted. * - `400 INVALID_TOKEN` — any proof that does not admit: unknown, used, * expired, for another invitation or address, or an invitation that is no * longer pending. One answer, which does not say which check failed. * - * An unverified account with no linked provider account gets the typed - * password in place of its own, and every one of its sessions is revoked, as a - * password reset does. A new account is created through the internal adapter, - * so the sign-up gates that run on every creation (audience admission and the - * database hooks) run here too; the door itself refuses where email sign-up is - * off. The invitation is accepted through better-auth's own accept route, so - * every organization hook runs. + * ## Which existing account the door sets a password on + * + * The closing rule: the door sets a password on an existing account only when + * the mailbox the proof establishes is the account's one and only claim, and + * the server lets a local password be set here at all. Every other existing + * account answers `sign_in` with the proof unspent. The states, each one a + * reason the account holds a claim the proof does not outrank or the server + * sets no local password, are {@link ONE_STEP_SIGN_IN_STATES}, judged by + * {@link oneStepSignInState}; the card's test pins one case per state. + * + * An account that passes gets the typed password in place of its own, and + * every one of its sessions is revoked with the reason a password reset + * records (`session-tombstone.ts`). A new account is created through the + * internal adapter, so the sign-up gates that run on every creation (audience + * admission and the database hooks) run here too; the door itself refuses + * where email sign-up is off. Either way the password-age stamp and the + * forced-change clear a password change writes (ADR-0069 D1) are written. The + * invitation is accepted through better-auth's own accept route, so every + * organization hook runs. + * + * On a cloud-managed environment the door sets no local password for anyone + * (`cloud-managed.ts`): proof mode answers that posture's refusal before the + * proof is read, and the proof stays unspent. * * Rate-limited per client address and per invitation, always armed. */ +import { isCloudManaged } from '@objectstack/core'; +import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { incrementFixedWindow, InProcessCounterStore, type CounterStore } from './rate-limit-storage.js'; import { readRequestClientAddress } from './request-client-address.js'; import { isPendingSsoSource } from './pending-sso-marker.js'; import { isIdpProvisionedSource, readUserSource } from './sso-only-local-password.js'; /** The door's path, under the auth mount. */ -export const ACCEPT_INVITATION_WITH_PROOF_PATH = '/organization/accept-invitation-with-proof'; +export const ACCEPT_INVITATION_ONE_STEP_PATH = '/organization/accept-invitation-one-step'; /** The fragment key the mail's link carries the proof under. */ export const INVITATION_PROOF_FRAGMENT_KEY = 'proof'; @@ -174,6 +196,54 @@ export interface InvitationProofDoorHost { getDataEngine(): unknown; /** The shared counter store, when one is wired. */ counterStore?: () => Promise; + /** The ADR-0069 D1 after-effects of a password set (`AuthManager#stampPasswordChangedAt`). */ + stampPasswordChangedAt(userId: string): Promise; +} + +/** + * The states of an existing account that answer `sign_in`, in the order they + * are judged. Each is either a claim on the account the mailbox proof does not + * outrank, or a server that sets no local password here. + */ +export const ONE_STEP_SIGN_IN_STATES = [ + /** The address is already verified: its holder signs in. */ + 'verified', + /** The account is linked to a sign-in provider. */ + 'linked_provider', + /** The account has a second factor enrolled. */ + 'second_factor', + /** The account is provisioned by an identity provider. */ + 'idp_provisioned', + /** The account is waiting for its first single sign-on. */ + 'pending_sso', + /** The account's directory source cannot be read: judged as managed. */ + 'source_unreadable', + /** SSO-only mode: no local password is set. */ + 'sso_only', + /** Email and password sign-in is off. */ + 'email_password_off', +] as const; + +export type OneStepSignInState = (typeof ONE_STEP_SIGN_IN_STATES)[number]; + +/** The first state of {@link ONE_STEP_SIGN_IN_STATES} the account is in, or `undefined` when the door may set its password. */ +export function oneStepSignInState(account: { + emailVerified: boolean; + linkedProvider: boolean; + twoFactorEnabled: boolean; + source: { ok: true; value: string | null } | { ok: false }; + ssoOnly: boolean; + emailPasswordEnabled: boolean; +}): OneStepSignInState | undefined { + if (account.emailVerified) return 'verified'; + if (account.linkedProvider) return 'linked_provider'; + if (account.twoFactorEnabled) return 'second_factor'; + if (account.source.ok && isIdpProvisionedSource(account.source.value)) return 'idp_provisioned'; + if (account.source.ok && isPendingSsoSource(account.source.value)) return 'pending_sso'; + if (!account.source.ok) return 'source_unreadable'; + if (account.ssoOnly) return 'sso_only'; + if (!account.emailPasswordEnabled) return 'email_password_off'; + return undefined; } const INVALID_PROOF_MESSAGE = @@ -227,7 +297,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo }; const endpoint = createAuthEndpoint( - ACCEPT_INVITATION_WITH_PROOF_PATH, + ACCEPT_INVITATION_ONE_STEP_PATH, { method: 'POST' }, async (ctx: any) => { const body = (ctx.body ?? {}) as Record; @@ -263,6 +333,14 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo } // ── Proof mode ───────────────────────────────────────────────────── + // A cloud-managed environment sets no local password for anyone + // (`cloud-managed.ts`); asked before the proof is read, so it stays unspent. + if (isCloudManaged()) { + throw new APIError('CONFLICT', { + code: CLOUD_MANAGED_REFUSAL_CODE, + message: CLOUD_MANAGED_REFUSAL_MESSAGES.acceptInvitationOneStep, + }); + } if (!pending) return refuseProof(); const identifier = invitationProofIdentifier(invitationId); const internal = ctx.context.internalAdapter; @@ -273,19 +351,15 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo const found = await internal.findUserByEmail(email, { includeAccounts: true }); const existing = found?.user; if (existing) { - const linkedProvider = (found.accounts ?? []).some((a: any) => a?.providerId !== 'credential'); - const source = await readUserSource(host.getDataEngine() as never, String(existing.id)); - const directoryManaged = !source.ok || isPendingSsoSource(source.value) || isIdpProvisionedSource(source.value); - if ( - existing.emailVerified === true || - linkedProvider || - existing.twoFactorEnabled === true || - directoryManaged || - host.isSsoOnlyMode() || - !ctx.context.options.emailAndPassword?.enabled - ) { - return ctx.json({ success: true, data: { outcome: 'sign_in' } }); - } + const state = oneStepSignInState({ + emailVerified: existing.emailVerified === true, + linkedProvider: (found.accounts ?? []).some((a: any) => a?.providerId !== 'credential'), + twoFactorEnabled: existing.twoFactorEnabled === true, + source: await readUserSource(host.getDataEngine() as never, String(existing.id)), + ssoOnly: host.isSsoOnlyMode(), + emailPasswordEnabled: Boolean(ctx.context.options.emailAndPassword?.enabled), + }); + if (state) return ctx.json({ success: true, data: { outcome: 'sign_in' } }); } const password = typeof body.password === 'string' ? body.password : ''; @@ -337,6 +411,8 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo } user = await internal.updateUser(userId, { emailVerified: true, ...(name ? { name } : {}) }); } + // ADR-0069 D1: the password-age stamp and the forced-change clear. + await host.stampPasswordChangedAt(String(user.id)); const session = await internal.createSession(user.id, false); if (!session) throw new APIError('INTERNAL_SERVER_ERROR', { code: 'INTERNAL_ERROR', message: 'Failed to create a session.' }); @@ -348,6 +424,6 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo return { id: 'invitation-mailbox-proof', - endpoints: { acceptInvitationWithProof: endpoint }, + endpoints: { acceptInvitationOneStep: endpoint }, }; } diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index af5d9df2126..323796d55d4 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -7,12 +7,22 @@ // same minimal engine double the other end-to-end auth-manager suites use. import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { resetCloudManagedForTesting } from '@objectstack/core'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql'; import { AuthManager } from './auth-manager'; import { inviteForAudienceGate } from './audience-gate-test-support'; import { createCopyInvitationLinkHandler } from './invitation-link-action'; -import { ACCEPT_INVITATION_WITH_PROOF_PATH, invitationProofIdentifier } from './invitation-mailbox-proof'; +import { + ACCEPT_INVITATION_ONE_STEP_PATH, + ONE_STEP_SIGN_IN_STATES, + invitationProofIdentifier, + type OneStepSignInState, +} from './invitation-mailbox-proof'; +import { BREACH_CHECK_VENDOR_DEFAULT_PATHS } from './auth-manager-plugin-list'; +import { INTERACTIVE_REVOKE_REASON } from './session-tombstone'; const SECRET = 'test-secret-at-least-32-chars-long!!'; const BASE = 'http://localhost:3000'; @@ -102,7 +112,7 @@ interface SentMail { template: string; to: string; data: Record; - deliverOnly?: Record; + deliverOnlyData?: Record; } const singleOrgTenancy = () => @@ -121,13 +131,14 @@ const cookieFrom = (response: Response): string => .filter(Boolean) .join('; '); -const post = (manager: AuthManager, path: string, body: unknown, cookie?: string) => +const post = (manager: AuthManager, path: string, body: unknown, cookie?: string, remoteAddress?: string) => manager.handleRequest( new Request(`${BASE}/api/v1/auth${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(cookie ? { cookie } : {}) }, body: JSON.stringify(body), }), + remoteAddress ? { remoteAddress } : undefined, ); const sessionUser = async (manager: AuthManager, cookie: string) => { @@ -160,7 +171,7 @@ const invitationOf = (engine: MemoryEngine, email: string) => ); const proofOf = (mail: SentMail): string => { - const link = String(mail.deliverOnly?.acceptUrl ?? ''); + const link = String(mail.deliverOnlyData?.acceptUrl ?? ''); const match = /#proof=([^&]+)$/.exec(link); expect(match, `the mail's link carries no proof: ${link}`).not.toBeNull(); return decodeURIComponent(match![1]!); @@ -204,8 +215,8 @@ const boot = async (options: Record = {}) => { return { engine, manager, owner, sent, invite }; }; -const door = (manager: AuthManager, body: Record, cookie?: string) => - post(manager, ACCEPT_INVITATION_WITH_PROOF_PATH, body, cookie); +const door = (manager: AuthManager, body: Record, cookie?: string, remoteAddress?: string) => + post(manager, ACCEPT_INVITATION_ONE_STEP_PATH, body, cookie, remoteAddress); const expectRefused = async (res: Response) => { const text = await res.clone().text(); @@ -225,7 +236,7 @@ describe('#34257 — the invitation mail carries a mailbox-only proof', () => { const { invite } = await boot(); const { mail, proof } = await invite('invitee@example.com'); expect(JSON.stringify(mail.data)).not.toContain(proof); - expect(String(mail.deliverOnly?.acceptUrl).startsWith(`${mail.data.acceptUrl}#`)).toBe(true); + expect(String(mail.deliverOnlyData?.acceptUrl).startsWith(`${mail.data.acceptUrl}#`)).toBe(true); }); it('the proof is never at rest in clear', async () => { @@ -352,6 +363,10 @@ describe('#34257 — accepting with the proof', () => { expect((await res.json()).data).toMatchObject({ outcome: 'accepted' }); expect(await sessionUser(manager, earlier.cookie)).toBeNull(); + // Each session it ended records the reason a password reset records. + const ended = (engine.tables.get('sys_session') ?? []).filter((row) => row.user_id === earlier.userId && row.revoked_at); + expect(ended.length).toBeGreaterThan(0); + expect(ended.map((row) => row.revoke_reason)).toEqual(ended.map(() => 'password_reset')); expect(userRow(engine, 'squatted@example.com')?.email_verified).toBeTruthy(); const oldPassword = await post(manager, '/sign-in/email', { email: 'squatted@example.com', password: PASSWORD }); expect(oldPassword.status).not.toBe(200); @@ -439,6 +454,7 @@ describe('#34257 — a signed-in return accepts only a verified address', () => }); }); + // The tables a redemption writes: the account, its credential, its sessions, // the membership, the invitation and the proof row. const WRITTEN_TABLES = ['sys_user', 'sys_account', 'sys_session', 'sys_member', 'sys_invitation', 'sys_verification']; @@ -463,13 +479,21 @@ const expectAccepted = async (res: Response) => { expect(JSON.parse(text).data).toEqual({ outcome: 'accepted', organizationId: PARTNER_ORG }); }; -describe('#34257 — every gate refuses before anything is written, and the proof stays usable', () => { +const quietConsole = () => { beforeEach(() => { vi.spyOn(console, 'info').mockImplementation(() => {}); vi.spyOn(console, 'warn').mockImplementation(() => {}); vi.spyOn(console, 'error').mockImplementation(() => {}); }); - afterEach(() => vi.restoreAllMocks()); + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + resetCloudManagedForTesting(); + }); +}; + +describe('#34257 — every gate refuses before anything is written, and the proof stays usable', () => { + quietConsole(); it('a new address is refused where email sign-up is switched off', async () => { const { engine, manager, invite } = await boot({ emailAndPassword: { disableSignUp: true } }); @@ -495,52 +519,6 @@ describe('#34257 — every gate refuses before anything is written, and the proo await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: PASSWORD })); }); - it('an unverified account in SSO-only mode signs in as today, and the proof stays unspent', async () => { - const { engine, manager, invite } = await boot(); - const { invitation, proof } = await invite('sso-held@example.com'); - await signUp(manager, engine, 'sso-held@example.com'); - manager.applyConfigPatch({ ssoOnlyMode: true } as never); - const before = writtenState(engine); - - await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); - expect(writtenState(engine)).toBe(before); - - manager.applyConfigPatch({ ssoOnlyMode: false } as never); - await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); - }); - - it('an unverified account with a second factor signs in as today, and the proof stays unspent', async () => { - const { engine, manager, invite } = await boot({ plugins: { twoFactor: true } }); - const { invitation, proof } = await invite('two-factor@example.com'); - await signUp(manager, engine, 'two-factor@example.com'); - userRow(engine, 'two-factor@example.com')!.two_factor_enabled = true; - const before = writtenState(engine); - - await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'T', password: NEW_PASSWORD })); - expect(writtenState(engine)).toBe(before); - - userRow(engine, 'two-factor@example.com')!.two_factor_enabled = false; - await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'T', password: NEW_PASSWORD })); - }); - - it.each([ - ['provisioned by an identity provider', 'idp_provisioned'], - ['pending its first SSO sign-in', 'idp_pending'], - ])('an unverified account %s signs in as today, and the proof stays unspent', async (_label, source) => { - const { engine, manager, invite } = await boot(); - const email = `directory-${source}@example.com`; - const { invitation, proof } = await invite(email); - await signUp(manager, engine, email); - userRow(engine, email)!.source = source; - const before = writtenState(engine); - - await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'D', password: NEW_PASSWORD })); - expect(writtenState(engine)).toBe(before); - - userRow(engine, email)!.source = null; - await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'D', password: NEW_PASSWORD })); - }); - it('a password under the minimum length is refused', async () => { const { engine, manager, invite } = await boot(); const { invitation, proof } = await invite('short@example.com'); @@ -586,6 +564,17 @@ describe('#34257 — every gate refuses before anything is written, and the proo await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'B', password: PASSWORD })); }); + it('the breach check covers the vendor default doors and this door, and the vendor list is the installed one', () => { + const vendorFile = createRequire(import.meta.url).resolve('better-auth/plugins/haveibeenpwned'); + const source = readFileSync(vendorFile, 'utf8'); + const literal = /options\?\.paths\s*\|\|\s*\[([^\]]*)\]/.exec(source); + expect(literal, `no default path list found in ${vendorFile}`).not.toBeNull(); + const vendorDefault = [...literal![1]!.matchAll(/["']([^"']+)["']/g)].map((m) => m[1]); + expect(vendorDefault.length).toBeGreaterThan(0); + expect([...BREACH_CHECK_VENDOR_DEFAULT_PATHS]).toEqual(vendorDefault); + expect(vendorDefault).not.toContain(ACCEPT_INVITATION_ONE_STEP_PATH); + }); + it('a new address the audience admission refuses is refused', async () => { const { engine, manager, invite } = await boot(); const { invitation, proof } = await invite('refused@example.com'); @@ -613,4 +602,183 @@ describe('#34257 — every gate refuses before anything is written, and the proo await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'Named', password: PASSWORD })); }); + + it('the window per client network address refuses, and the proof stays usable from another address', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('windowed@example.com'); + for (let i = 0; i < 10; i++) { + await expectRefused(await door(manager, { invitationId: `inv_unknown_${i}`, proof: 'wrong', name: 'W', password: PASSWORD }, undefined, '203.0.113.7')); + } + const before = writtenState(engine); + + await expectAnswer( + await door(manager, { invitationId: invitation.id, proof, name: 'W', password: PASSWORD }, undefined, '203.0.113.7'), + 429, + 'RATE_LIMIT_EXCEEDED', + ); + expect(writtenState(engine)).toBe(before); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'W', password: PASSWORD }, undefined, '203.0.113.8')); + }); + + it('a cloud-managed environment refuses a proof, and the proof stays usable where it is not', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('managed@example.com'); + vi.stubEnv('OS_CLOUD_MANAGED', '1'); + resetCloudManagedForTesting(); + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'M', password: PASSWORD }), 409, 'RESOURCE_CONFLICT'); + expect(writtenState(engine)).toBe(before); + + vi.unstubAllEnvs(); + resetCloudManagedForTesting(); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'M', password: PASSWORD })); + }); + + it('two concurrent redemptions of one proof: exactly one is accepted', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('raced@example.com'); + const answers = await Promise.all([ + door(manager, { invitationId: invitation.id, proof, name: 'One', password: PASSWORD }), + door(manager, { invitationId: invitation.id, proof, name: 'Two', password: NEW_PASSWORD }), + ]); + const statuses = answers.map((res) => res.status).sort(); + expect(statuses).toEqual([200, 400]); + await expectRefused(answers.find((res) => res.status === 400)!); + expect((engine.tables.get('sys_user') ?? []).filter((u) => u.email === 'raced@example.com')).toHaveLength(1); + }); +}); + +describe('#34257 — the door sets a password only where the mailbox is the account\'s one claim', () => { + quietConsole(); + + type Booted = Awaited>; + interface StateCase { + options?: Record; + /** Put the account into the state, and answer how to take it out again. */ + enter(booted: Booted, email: string): Promise<() => Promise | void>; + } + const findThrowsForSource = (engine: MemoryEngine) => { + const find = engine.find.bind(engine); + engine.find = async (name: string, q: any = {}) => { + if (name === 'sys_user' && Array.isArray(q.fields) && q.fields.includes('source')) throw new Error('store unavailable'); + return find(name, q); + }; + return () => { + engine.find = find; + }; + }; + + // Typed as a Record over the states, so a state added to the rule without a + // case here fails to compile, and the test below fails at run time. + const CASES: Record = { + verified: { + enter: async ({ engine }, email) => { + userRow(engine, email)!.email_verified = true; + return () => { + userRow(engine, email)!.email_verified = false; + }; + }, + }, + linked_provider: { + enter: async ({ engine }, email) => { + await engine.insert('sys_account', { id: `acc_${email}`, user_id: userRow(engine, email)!.id, provider_id: 'google', account_id: `google-${email}` }); + return () => { + engine.tables.set('sys_account', (engine.tables.get('sys_account') ?? []).filter((a) => a.id !== `acc_${email}`)); + }; + }, + }, + second_factor: { + options: { plugins: { twoFactor: true } }, + enter: async ({ engine }, email) => { + userRow(engine, email)!.two_factor_enabled = true; + return () => { + userRow(engine, email)!.two_factor_enabled = false; + }; + }, + }, + idp_provisioned: { + enter: async ({ engine }, email) => { + userRow(engine, email)!.source = 'idp_provisioned'; + return () => { + userRow(engine, email)!.source = null; + }; + }, + }, + pending_sso: { + enter: async ({ engine }, email) => { + userRow(engine, email)!.source = 'idp_pending'; + return () => { + userRow(engine, email)!.source = null; + }; + }, + }, + source_unreadable: { + enter: async ({ engine }) => findThrowsForSource(engine), + }, + sso_only: { + enter: async ({ manager }) => { + manager.applyConfigPatch({ ssoOnlyMode: true } as never); + return () => manager.applyConfigPatch({ ssoOnlyMode: false } as never); + }, + }, + email_password_off: { + enter: async ({ manager }) => { + manager.applyConfigPatch({ emailAndPassword: { enabled: false } } as never); + return () => manager.applyConfigPatch({ emailAndPassword: { enabled: true } } as never); + }, + }, + }; + + it('every state the closing rule names has a case, and no case names another state', () => { + expect(Object.keys(CASES).sort()).toEqual([...ONE_STEP_SIGN_IN_STATES].sort()); + }); + + it.each([...ONE_STEP_SIGN_IN_STATES])('an unverified account in state %s signs in as today, and the proof stays unspent', async (state) => { + const testCase = CASES[state]; + const booted = await boot(testCase.options); + const { engine, manager, invite } = booted; + const email = `state-${state.replace(/_/g, '-')}@example.com`; + const { invitation, proof } = await invite(email); + await signUp(manager, engine, email); + const leave = await testCase.enter(booted, email); + const before = writtenState(engine); + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); + expect(writtenState(engine)).toBe(before); + + await leave(); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); + }); +}); + +describe('#34257 — a password the door sets starts the password-age clock and clears a forced change', () => { + quietConsole(); + + it('a new account is stamped', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('aged-new@example.com'); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'N', password: PASSWORD })); + const user = userRow(engine, 'aged-new@example.com')!; + expect(user.password_changed_at).toBeInstanceOf(Date); + expect(user.must_change_password).toBe(false); + }); + + it('an unverified account under a forced change is stamped and the forced change cleared', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('aged-held@example.com'); + await signUp(manager, engine, 'aged-held@example.com'); + const user = userRow(engine, 'aged-held@example.com')!; + user.must_change_password = true; + user.password_changed_at = new Date('2020-01-01T00:00:00Z'); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'H', password: NEW_PASSWORD })); + expect(user.must_change_password).toBe(false); + expect(new Date(user.password_changed_at).getTime()).toBeGreaterThan(Date.now() - 60_000); + }); + + it('the sessions the door ends are ledgered with the reason a password reset records', () => { + expect(INTERACTIVE_REVOKE_REASON[ACCEPT_INVITATION_ONE_STEP_PATH]).toBe('password_reset'); + }); }); diff --git a/packages/plugins/plugin-auth/src/session-tombstone.ts b/packages/plugins/plugin-auth/src/session-tombstone.ts index ceacc6c6bc2..7cc3c2b9cbb 100644 --- a/packages/plugins/plugin-auth/src/session-tombstone.ts +++ b/packages/plugins/plugin-auth/src/session-tombstone.ts @@ -156,7 +156,8 @@ * holds (`password-reset-ends-sessions.ts`), and a session it ends leaves the * same kind of trail an interactive revoke leaves, so the reset doors are in * {@link INTERACTIVE_REVOKE_REASON} with their own value, `password_reset`. - * The seam is the same one: measured against the installed better-auth + * The one-step invitation acceptance, which replaces the password of an + * unverified account the same way, records the same value. The seam is the same one: measured against the installed better-auth * `1.7.12`, every reset door runs `resetCredentialPassword` * (`dist/utils/password.mjs`), which ends the sessions with * `internalAdapter.deleteUserSessions`; with no `secondaryStorage` that is @@ -239,6 +240,12 @@ export const INTERACTIVE_REVOKE_REASON: Readonly> = { // that plugin today; the entry is keyed on the plugin's declared path, so // the door records the same trail the day the platform mounts it. '/email-otp/reset-password': 'password_reset', + // The one-step invitation acceptance (`invitation-mailbox-proof.ts`, + // `ACCEPT_INVITATION_ONE_STEP_PATH`), which replaces the password of an + // unverified account and ends its sessions, as a reset does. Spelled as the + // literal so this ledger imports no door module; the card's test pins the + // two equal. + '/organization/accept-invitation-one-step': 'password_reset', }; /** diff --git a/packages/plugins/plugin-auth/src/sso-only-local-password.ts b/packages/plugins/plugin-auth/src/sso-only-local-password.ts index cb9f26c1b94..9d4f99deaa5 100644 --- a/packages/plugins/plugin-auth/src/sso-only-local-password.ts +++ b/packages/plugins/plugin-auth/src/sso-only-local-password.ts @@ -18,7 +18,12 @@ * administrator setting one for the user; * - `POST /reset-password` (the emailed link) and * `POST /phone-number/reset-password` (the texted code), each of which - * creates the local password when the user holds none. + * creates the local password when the user holds none; + * - `POST /organization/accept-invitation-one-step` with the invitation + * mail's proof (`invitation-mailbox-proof.ts`). Under SSO-only mode it sets + * no local password for anyone, an environment-native user included: an + * existing account answers `sign_in` and a new address is refused, because + * SSO-only mode forces email sign-up off. * * One exception, the break-glass one ADR-0135 D5.2 keeps and the * cloud-managed narrowing already makes (`cloud-managed.ts`): a platform diff --git a/packages/plugins/plugin-email/src/email-service.ts b/packages/plugins/plugin-email/src/email-service.ts index a5ad24035df..25843a77e12 100644 --- a/packages/plugins/plugin-email/src/email-service.ts +++ b/packages/plugins/plugin-email/src/email-service.ts @@ -965,7 +965,7 @@ export class EmailService implements IEmailService { /** * `delivered`, when given, holds the faces the recipient receives in place - * of the stored row's (`SendTemplateInput.deliverOnly`): the row is written + * of the stored row's (`SendTemplateInput.deliverOnlyData`): the row is written * from `input`, the transport is handed `delivered`, and the send is inline, * because the queue delivers from the row. */ @@ -1854,9 +1854,9 @@ export class EmailService implements IEmailService { // Deliver-only values reach the recipient and never the stored row: the // row is written from the faces rendered above, from `data` alone, and the // transport gets the faces rendered from `data` overlaid with them. - const deliverOnly = input.deliverOnly; - const delivered = deliverOnly && Object.keys(deliverOnly).length > 0 - ? (await this.resolveAndRenderTemplate({ ...input, data: { ...(input.data || {}), ...deliverOnly } })).rendered + const deliverOnlyData = input.deliverOnlyData; + const delivered = deliverOnlyData && Object.keys(deliverOnlyData).length > 0 + ? (await this.resolveAndRenderTemplate({ ...input, data: { ...(input.data || {}), ...deliverOnlyData } })).rendered : undefined; const from: EmailAddress | undefined = input.from diff --git a/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts b/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts index 8abaa4c5b85..e43ce57d366 100644 --- a/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts +++ b/packages/plugins/plugin-email/src/send-template-deliver-only-34257.test.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// `SendTemplateInput.deliverOnly`: values delivered with the message and never +// `SendTemplateInput.deliverOnlyData`: values delivered with the message and never // written to the stored mail row. import { describe, it, expect } from 'vitest'; @@ -63,7 +63,7 @@ describe('deliver-only template values (#34257)', () => { template: 'auth.invitation', to: 'invitee@example.com', data: { orgName: 'Acme', acceptUrl: PLAIN_URL }, - deliverOnly: { acceptUrl: DELIVERED_URL }, + deliverOnlyData: { acceptUrl: DELIVERED_URL }, }); expect(res.status).toBe('sent'); @@ -83,7 +83,7 @@ describe('deliver-only template values (#34257)', () => { template: 'auth.invitation', to: 'invitee@example.com', data: { orgName: 'Acme', acceptUrl: PLAIN_URL }, - deliverOnly: { acceptUrl: DELIVERED_URL }, + deliverOnlyData: { acceptUrl: DELIVERED_URL }, }); expect(res.status).toBe('sent'); diff --git a/packages/qa/dogfood/test/anonymous-door-sweep.classification.ts b/packages/qa/dogfood/test/anonymous-door-sweep.classification.ts index 5d21b554f7f..56a480740ef 100644 --- a/packages/qa/dogfood/test/anonymous-door-sweep.classification.ts +++ b/packages/qa/dogfood/test/anonymous-door-sweep.classification.ts @@ -122,6 +122,13 @@ export interface DoorClass { readonly match?: (r: SweptRoute) => boolean; /** For a class with no route of its own: the routes it rides, all in the population. */ readonly ridesOn?: readonly string[]; + /** + * Doors of this class a catch-all route serves (`ALL /api/v1/auth/*`, the + * better-auth endpoints): no route table lists them on their own, so the + * sweep's one request per route never reaches them, and the control-plane + * allowlist claims the catch-all itself. Each is probed by its own path. + */ + readonly servedByCatchAll?: readonly { readonly method: string; readonly path: string; readonly catchAll: string }[]; /** The class-level answer to the sweep's request on one of its routes. */ readonly expect?: ClassExpectation; } @@ -149,8 +156,10 @@ export const DOOR_CLASSES: readonly DoorClass[] = [ id: 2, name: 'share links', enforcedBy: - 'registerShareLinkRoutes (plugin-sharing), the capability token; and the signed-out invitation preview ' + - '(plugin-auth runInvitationPreview), the invitation id as the capability token', + 'registerShareLinkRoutes (plugin-sharing), the capability token; the signed-out invitation preview ' + + '(plugin-auth runInvitationPreview), the invitation id as the capability token; the OAuth client-name read ' + + '(plugin-auth answerOAuthClientName), the server-signed authorization request; and the one-step invitation ' + + 'acceptance (plugin-auth buildInvitationProofDoorPlugin), the mailbox proof the invitation mail carries', // The two token-addressed reads. The create / list / revoke routes beside // them manage links and need a signed-in caller: they are everything-else. // @@ -160,11 +169,22 @@ export const DOOR_CLASSES: readonly DoorClass[] = [ // row the control-plane allowlist below would claim it and the sweep would // judge nothing. Matched here first, the sweep's probe (which carries no // invitation id) is held to the class's answer: a 4xx, nothing served. + // + // The OAuth client-name read, by the same note's amendment: a public read + // admitted by a request the server signed, mounted ahead of the catch-all + // like the preview, so the same reasoning holds. match: routeIs( 'GET /api/v1/share-links/:token/resolve', 'GET /api/v1/share-links/:token/messages', 'GET /api/v1/auth/organization/invitation-preview', + 'GET /api/v1/auth/oauth2/client-name', ), + // The one-step invitation acceptance, by the same amendment: a better-auth + // endpoint, so it rides the auth catch-all and is probed by its own path. + // An anonymous request that carries no proof is held to the class's answer. + servedByCatchAll: [ + { method: 'POST', path: '/api/v1/auth/organization/accept-invitation-one-step', catchAll: 'ALL /api/v1/auth/*' }, + ], expect: REFUSED_WITHOUT_A_SUBJECT, }, { diff --git a/packages/qa/dogfood/test/anonymous-door-sweep.dogfood.test.ts b/packages/qa/dogfood/test/anonymous-door-sweep.dogfood.test.ts index 0297ba80655..7a7c236578c 100644 --- a/packages/qa/dogfood/test/anonymous-door-sweep.dogfood.test.ts +++ b/packages/qa/dogfood/test/anonymous-door-sweep.dogfood.test.ts @@ -472,6 +472,18 @@ describe('ADR-0138 D2 class 2: share links', () => { const after = await send(stack, 'GET', `/api/v1/share-links/${link.token}/resolve`); expect(DOOR_CLASSES[1]!.expect!(after), 'a revoked token is no door').toBeUndefined(); }); + + it('hold the class-2 doors a catch-all serves to the class answer, each reached by its own path', async () => { + const keys = new Set(population.map((p) => keyOf(p.route))); + const doors = DOOR_CLASSES[1]!.servedByCatchAll ?? []; + expect(doors.length, 'class 2 names no door behind a catch-all: this leg would be vacuous').toBeGreaterThan(0); + for (const door of doors) { + expect(keys.has(door.catchAll), `${door.method} ${door.path} rides ${door.catchAll}, which is not in the population`).toBe(true); + const res = await send(stack, door.method, door.path, { body: JSON.stringify({}) }); + expect(res.status, `${door.method} ${door.path} answered 404: the catch-all does not serve it`).not.toBe(404); + expect(DOOR_CLASSES[1]!.expect!(res), `${door.method} ${door.path}`).toBeUndefined(); + } + }); }); describe('ADR-0138 D2 class 3: the public book and doc metadata reads', () => { diff --git a/packages/spec/src/contracts/email-service.ts b/packages/spec/src/contracts/email-service.ts index 3418b40c750..424cae619ca 100644 --- a/packages/spec/src/contracts/email-service.ts +++ b/packages/spec/src/contracts/email-service.ts @@ -198,16 +198,19 @@ export interface SendTemplateInput { * The message the recipient receives renders `data` overlaid with these * values. The stored row (`sys_email` / `sys_identity_email`) records the * message rendered from `data` alone, so a hole present in both reads the - * `data` value in the row. A send carrying any deliver-only value is - * delivered inline, never through the durable queue: the queue delivers - * from the stored row, which does not hold them. A message re-delivered from - * its stored row carries the row's faces. + * `data` value in the row, and the row gives no sign that deliver-only + * values were overlaid. Required template variables are checked against + * `data` alone, so a deliver-only value never satisfies one. A send carrying + * any deliver-only value is delivered inline, never through the durable + * queue, so its sender gives up queued delivery where a queue is mounted: + * the queue delivers from the stored row, which does not hold them. A + * message re-delivered from its stored row carries the row's faces. * * Only this server-side template send declares it; the caller-facing mail * doors (`POST /email/send`, a script body's `ctx.email.send`) take a * {@link SendEmailInput}, which has no such member. */ - deliverOnly?: Record; + deliverOnlyData?: Record; /** * Preferred BCP-47 locale (e.g. user's locale). * diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 05e40455218..5d589c98966 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1472,7 +1472,7 @@ const PLUGIN_ROUTE_MODULES = { 'packages/plugins/plugin-auth/src/list-user-invitations-verification.ts': {}, // [#34257] FIRST AUDIT — the one-step invitation acceptance, a better-auth - // endpoint this repo defines (`POST /organization/accept-invitation-with-proof`). + // endpoint this repo defines (`POST /organization/accept-invitation-one-step`). // Every body it BUILDS is the envelope, `{ success: true, data: { outcome, … } }`; // its refusals are `throw APIError.*`, raised rather than written. 'packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts': {}, diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx index d1ea04d69c5..6053ef606ba 100644 --- a/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx +++ b/ui/packages/app-shell/src/console/organizations/__tests__/acceptInvitationOneStep-34257.test.tsx @@ -44,7 +44,7 @@ const auth = { getInvitation: vi.fn(async () => INVITATION), getInvitationPreview: vi.fn(async () => PREVIEW as typeof PREVIEW | null), acceptInvitation: vi.fn(async () => undefined), - acceptInvitationWithProof: vi.fn(async (): Promise => ({ outcome: 'accepted', organizationId: 'org-42' })), + acceptInvitationOneStep: vi.fn(async (): Promise => ({ outcome: 'accepted', organizationId: 'org-42' })), rejectInvitation: vi.fn(async () => undefined), switchOrganization: vi.fn(async () => undefined), }; @@ -91,7 +91,7 @@ beforeEach(() => { vi.clearAllMocks(); socialProps.current = null; auth.getInvitationPreview.mockImplementation(async () => PREVIEW); - auth.acceptInvitationWithProof.mockImplementation(async () => ({ outcome: 'accepted', organizationId: 'org-42' })); + auth.acceptInvitationOneStep.mockImplementation(async () => ({ outcome: 'accepted', organizationId: 'org-42' })); }); afterEach(() => { @@ -140,7 +140,7 @@ describe('AcceptInvitationPage — one-step acceptance (objectstack#34257)', () fillAndSubmit(); expect(await screen.findByTestId('accept-invitation-joined')).toHaveTextContent('Welcome to Acme.'); - expect(auth.acceptInvitationWithProof).toHaveBeenCalledWith({ + expect(auth.acceptInvitationOneStep).toHaveBeenCalledWith({ invitationId: 'inv-1', proof: 'p-1', name: 'Ada', @@ -150,7 +150,7 @@ describe('AcceptInvitationPage — one-step acceptance (objectstack#34257)', () }); it('an address with an account hands over to the sign-in, as today', async () => { - auth.acceptInvitationWithProof.mockImplementation(async () => ({ outcome: 'sign_in' })); + auth.acceptInvitationOneStep.mockImplementation(async () => ({ outcome: 'sign_in' })); arriveAt('/accept-invitation/inv-1#proof=p-1', false); await screen.findByText('Join Acme'); @@ -160,7 +160,7 @@ describe('AcceptInvitationPage — one-step acceptance (objectstack#34257)', () }); it('a refused proof says the link can no longer be used', async () => { - auth.acceptInvitationWithProof.mockImplementation(async () => { + auth.acceptInvitationOneStep.mockImplementation(async () => { throw Object.assign(new Error('no'), { code: 'INVALID_TOKEN', status: 400 }); }); arriveAt('/accept-invitation/inv-1#proof=p-1', false); @@ -177,21 +177,21 @@ describe('AcceptInvitationPage — one-step acceptance (objectstack#34257)', () await waitFor(() => expect(navigate).toHaveBeenCalledWith(LOGIN_REDIRECT)); expect(screen.queryByTestId('accept-invitation-one-step')).toBeNull(); - expect(auth.acceptInvitationWithProof).not.toHaveBeenCalled(); + expect(auth.acceptInvitationOneStep).not.toHaveBeenCalled(); }); it('back from a provider sign-in, the page redeems the invitation for the session', async () => { arriveAt('/accept-invitation/inv-1?via=provider', true); expect(await screen.findByTestId('accept-invitation-joined')).toHaveTextContent('Welcome to Acme.'); - expect(auth.acceptInvitationWithProof).toHaveBeenCalledTimes(1); - expect(auth.acceptInvitationWithProof).toHaveBeenCalledWith({ invitationId: 'inv-1' }); + expect(auth.acceptInvitationOneStep).toHaveBeenCalledTimes(1); + expect(auth.acceptInvitationOneStep).toHaveBeenCalledWith({ invitationId: 'inv-1' }); expect(auth.switchOrganization).toHaveBeenCalledWith('org-42'); expect(window.location.search).toBe(''); }); it('back from a provider sign-in with an address that is not the verified invited one, the page asks for verification', async () => { - auth.acceptInvitationWithProof.mockImplementation(async () => ({ outcome: 'verify_email' })); + auth.acceptInvitationOneStep.mockImplementation(async () => ({ outcome: 'verify_email' })); arriveAt('/accept-invitation/inv-1?via=provider', true); expect(await screen.findByTestId('accept-invitation-verify-email')).toHaveTextContent(en.verifyEmailTitle); @@ -202,6 +202,6 @@ describe('AcceptInvitationPage — one-step acceptance (objectstack#34257)', () arriveAt('/accept-invitation/inv-1', true); expect(await screen.findByRole('button', { name: en.accept })).toBeInTheDocument(); - expect(auth.acceptInvitationWithProof).not.toHaveBeenCalled(); + expect(auth.acceptInvitationOneStep).not.toHaveBeenCalled(); }); }); diff --git a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx index a3bf4f5abbb..29a467ab98c 100644 --- a/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx +++ b/ui/packages/app-shell/src/console/organizations/manage/AcceptInvitationPage.tsx @@ -94,7 +94,7 @@ export function AcceptInvitationPage() { isLoading: isAuthLoading, getInvitation, acceptInvitation, - acceptInvitationWithProof, + acceptInvitationOneStep, rejectInvitation, switchOrganization, } = useAuth(); @@ -167,7 +167,7 @@ export function AcceptInvitationPage() { void (async () => { const inv = await getInvitation(invitationId).catch(() => null); try { - const outcome = await acceptInvitationWithProof({ invitationId }); + const outcome = await acceptInvitationOneStep({ invitationId }); if (outcome.outcome === 'accepted') { await switchOrganization(outcome.organizationId).catch(() => null); setOneStepJoined({ @@ -186,7 +186,7 @@ export function AcceptInvitationPage() { } setProviderReturn(false); })(); - }, [providerReturn, invitationId, isAuthLoading, isAuthenticated, getInvitation, acceptInvitationWithProof, switchOrganization]); + }, [providerReturn, invitationId, isAuthLoading, isAuthenticated, getInvitation, acceptInvitationOneStep, switchOrganization]); // Fetch invitation details useEffect(() => { @@ -329,7 +329,7 @@ export function AcceptInvitationPage() { setOneStepJoined({ orgName })} onSignIn={() => navigate(loginRedirect)} /> @@ -486,7 +486,7 @@ export function AcceptInvitationPage() { interface OneStepJoinFormProps { invitationId: string; proof: string; - acceptInvitationWithProof: ReturnType['acceptInvitationWithProof']; + acceptInvitationOneStep: ReturnType['acceptInvitationOneStep']; /** The door accepted: the visitor has an account, a session and the membership. */ onJoined: (orgName: string) => void; /** The address has an account the visitor signs in to, as today. */ @@ -500,7 +500,7 @@ interface OneStepJoinFormProps { * in. A provider sign-in returns to this page, which redeems the invitation for * the provider's session. */ -function OneStepJoinForm({ invitationId, proof, acceptInvitationWithProof, onJoined, onSignIn }: OneStepJoinFormProps) { +function OneStepJoinForm({ invitationId, proof, acceptInvitationOneStep, onJoined, onSignIn }: OneStepJoinFormProps) { const { t } = useObjectTranslation(); const { getInvitationPreview } = useAuth(); const [preview, setPreview] = useState(null); @@ -534,7 +534,7 @@ function OneStepJoinForm({ invitationId, proof, acceptInvitationWithProof, onJoi setSubmitting(true); setFailure(null); try { - const outcome = await acceptInvitationWithProof({ invitationId, proof, name: name.trim(), password }); + const outcome = await acceptInvitationOneStep({ invitationId, proof, name: name.trim(), password }); if (outcome.outcome === 'accepted') { onJoined(preview?.organizationName ?? outcome.organizationId); return; diff --git a/ui/packages/auth/src/AuthContext.ts b/ui/packages/auth/src/AuthContext.ts index 2a11da7c9db..9e99270eff7 100644 --- a/ui/packages/auth/src/AuthContext.ts +++ b/ui/packages/auth/src/AuthContext.ts @@ -7,7 +7,7 @@ */ import { createContext } from 'react'; -import type { AuthUser, AuthClientSession, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationProofInput, AuthInvitationProofOutcome, AuthPublicConfig, SignInWithProviderOptions, DelegableScope, TwoFactorChallenge, SignInTwoFactorCodeKind } from './types.js'; +import type { AuthUser, AuthClientSession, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationOneStepInput, AuthInvitationOneStepOutcome, AuthPublicConfig, SignInWithProviderOptions, DelegableScope, TwoFactorChallenge, SignInTwoFactorCodeKind } from './types.js'; export interface AuthContextValue { /** Current authenticated user */ @@ -257,8 +257,8 @@ export interface AuthContextValue { getInvitationPreview: (invitationId: string) => Promise; /** Accept an invitation as the current user */ acceptInvitation: (invitationId: string) => Promise; - /** The one-step invitation acceptance (see `AuthClient.acceptInvitationWithProof`). */ - acceptInvitationWithProof: (input: AuthInvitationProofInput) => Promise; + /** The one-step invitation acceptance (see `AuthClient.acceptInvitationOneStep`). */ + acceptInvitationOneStep: (input: AuthInvitationOneStepInput) => Promise; /** Reject an invitation as the current user */ rejectInvitation: (invitationId: string) => Promise; /** List invitations addressed to the current user */ diff --git a/ui/packages/auth/src/AuthProvider.tsx b/ui/packages/auth/src/AuthProvider.tsx index 4201fd6510a..131896f4f8c 100644 --- a/ui/packages/auth/src/AuthProvider.tsx +++ b/ui/packages/auth/src/AuthProvider.tsx @@ -10,7 +10,7 @@ import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react' import { authGateEvents } from './auth-gate-events.js'; import { sessionEndEvents } from './session-end-events.js'; import { runBeforeSignOut } from './beforeSignOut.js'; -import type { AuthUser, AuthClient, AuthProviderOptions, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationProofInput, AuthInvitationProofOutcome, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge } from './types.js'; +import type { AuthUser, AuthClient, AuthProviderOptions, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationOneStepInput, AuthInvitationOneStepOutcome, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge } from './types.js'; import { TWO_FACTOR_CHALLENGE_ENDED_CODES } from './two-factor-codes.js'; import { AuthCtx, type AuthContextValue } from './AuthContext.js'; import { createAuthClient, sessionReadWasInconclusive, takePreflightSession, TokenStorage } from './createAuthClient.js'; @@ -1144,9 +1144,9 @@ export function AuthProvider({ [client, refreshOrganizations], ); - const acceptInvitationWithProof = useCallback( - (input: AuthInvitationProofInput): Promise => - client.acceptInvitationWithProof(input), + const acceptInvitationOneStep = useCallback( + (input: AuthInvitationOneStepInput): Promise => + client.acceptInvitationOneStep(input), [client], ); @@ -1239,7 +1239,7 @@ export function AuthProvider({ getInvitation, getInvitationPreview, acceptInvitation, - acceptInvitationWithProof, + acceptInvitationOneStep, rejectInvitation, listUserInvitations, }), @@ -1251,7 +1251,7 @@ export function AuthProvider({ organizations, activeOrganization, activeMember, isOrganizationsLoading, isMembershipResolved, switchOrganization, createOrganization, refreshOrganizations, updateOrganization, deleteOrganization, leaveOrganization, getMembers, inviteMember, describeDelegableScope, removeMember, updateMemberRole, - listInvitations, cancelInvitation, getInvitation, getInvitationPreview, acceptInvitation, acceptInvitationWithProof, rejectInvitation, listUserInvitations, + listInvitations, cancelInvitation, getInvitation, getInvitationPreview, acceptInvitation, acceptInvitationOneStep, rejectInvitation, listUserInvitations, ], ); diff --git a/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts b/ui/packages/auth/src/__tests__/acceptInvitationOneStep-34257.test.ts similarity index 73% rename from ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts rename to ui/packages/auth/src/__tests__/acceptInvitationOneStep-34257.test.ts index 1f986ec9fd9..1b69984c653 100644 --- a/ui/packages/auth/src/__tests__/acceptInvitationWithProof-34257.test.ts +++ b/ui/packages/auth/src/__tests__/acceptInvitationOneStep-34257.test.ts @@ -1,7 +1,7 @@ /** - * #34257 — `createAuthClient().acceptInvitationWithProof(input)`, the client + * #34257 — `createAuthClient().acceptInvitationOneStep(input)`, the client * half of objectstack's one-step invitation acceptance - * (`POST {authUrl}/organization/accept-invitation-with-proof`). + * (`POST {authUrl}/organization/accept-invitation-one-step`). */ import { describe, it, expect, vi } from 'vitest'; @@ -19,32 +19,32 @@ function clientAnswering(status: number, body: unknown) { return { client: createAuthClient({ baseURL: AUTH_URL, fetchFn }), calls }; } -describe('acceptInvitationWithProof (#34257)', () => { +describe('acceptInvitationOneStep (#34257)', () => { it('posts the input to the one-step door and answers the accepted outcome', async () => { const { client, calls } = clientAnswering(200, { success: true, data: { outcome: 'accepted', organizationId: 'org_1' } }); const input = { invitationId: 'inv_1', proof: 'p1', name: 'Ada', password: 'S3cure!pass' }; - await expect(client.acceptInvitationWithProof(input)).resolves.toEqual({ + await expect(client.acceptInvitationOneStep(input)).resolves.toEqual({ outcome: 'accepted', organizationId: 'org_1', }); expect(calls).toEqual([ - { url: `${AUTH_URL}/organization/accept-invitation-with-proof`, method: 'POST', body: input }, + { url: `${AUTH_URL}/organization/accept-invitation-one-step`, method: 'POST', body: input }, ]); }); it('answers the sign-in and verify-email outcomes as they are', async () => { await expect( - clientAnswering(200, { success: true, data: { outcome: 'sign_in' } }).client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' }), + clientAnswering(200, { success: true, data: { outcome: 'sign_in' } }).client.acceptInvitationOneStep({ invitationId: 'inv_1', proof: 'p' }), ).resolves.toEqual({ outcome: 'sign_in' }); await expect( - clientAnswering(200, { success: true, data: { outcome: 'verify_email' } }).client.acceptInvitationWithProof({ invitationId: 'inv_1' }), + clientAnswering(200, { success: true, data: { outcome: 'verify_email' } }).client.acceptInvitationOneStep({ invitationId: 'inv_1' }), ).resolves.toEqual({ outcome: 'verify_email' }); }); it('a refusal rejects with the server code and status', async () => { const { client } = clientAnswering(400, { code: 'INVALID_TOKEN', message: 'no' }); - await expect(client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'bad' })).rejects.toMatchObject({ + await expect(client.acceptInvitationOneStep({ invitationId: 'inv_1', proof: 'bad' })).rejects.toMatchObject({ code: 'INVALID_TOKEN', status: 400, }); @@ -52,7 +52,7 @@ describe('acceptInvitationWithProof (#34257)', () => { it('an answer outside the outcome vocabulary rejects', async () => { const { client } = clientAnswering(200, { success: true, data: { outcome: 'something_else' } }); - await expect(client.acceptInvitationWithProof({ invitationId: 'inv_1', proof: 'p' })).rejects.toThrow( + await expect(client.acceptInvitationOneStep({ invitationId: 'inv_1', proof: 'p' })).rejects.toThrow( /unexpected response body/, ); }); diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts index a1482af3c9d..b526b7eb048 100644 --- a/ui/packages/auth/src/createAuthClient.ts +++ b/ui/packages/auth/src/createAuthClient.ts @@ -10,7 +10,7 @@ import { createAuthClient as createBetterAuthClient, parseJSON } from 'better-au import { organizationClient, twoFactorClient } from 'better-auth/client/plugins'; import type { AuthClient, AuthClientConfig, AuthUser, AuthClientSession, SignInCredentials, SignUpData, - AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationProofInput, AuthInvitationProofOutcome, AuthPublicConfig, + AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthInvitationOneStepInput, AuthInvitationOneStepOutcome, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge, TwoFactorMethod, } from './types.js'; import { AUTH_INVITATION_STATUSES, isAuthInvitationStatus } from './invitation-status.js'; @@ -1384,8 +1384,8 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { if (error) throw toAuthError(error, 'Failed to accept invitation'); }, - async acceptInvitationWithProof(input: AuthInvitationProofInput): Promise { - const url = `${origin}${basePath}/organization/accept-invitation-with-proof`; + async acceptInvitationOneStep(input: AuthInvitationOneStepInput): Promise { + const url = `${origin}${basePath}/organization/accept-invitation-one-step`; const response = await bearerFetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -1415,7 +1415,7 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { return { outcome: 'accepted', organizationId: data.organizationId }; } if (data?.outcome === 'sign_in' || data?.outcome === 'verify_email') return { outcome: data.outcome }; - throw new Error('acceptInvitationWithProof: unexpected response body'); + throw new Error('acceptInvitationOneStep: unexpected response body'); }, async rejectInvitation(invitationId: string): Promise { diff --git a/ui/packages/auth/src/index.ts b/ui/packages/auth/src/index.ts index 27ba5802b6b..cb4a6681049 100644 --- a/ui/packages/auth/src/index.ts +++ b/ui/packages/auth/src/index.ts @@ -112,8 +112,8 @@ export type { AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, - AuthInvitationProofInput, - AuthInvitationProofOutcome, + AuthInvitationOneStepInput, + AuthInvitationOneStepOutcome, AuthSocialProvider, AuthPublicConfig, SignInWithProviderOptions, diff --git a/ui/packages/auth/src/types.ts b/ui/packages/auth/src/types.ts index d4824a57f8a..d1547beca63 100644 --- a/ui/packages/auth/src/types.ts +++ b/ui/packages/auth/src/types.ts @@ -622,7 +622,7 @@ export interface AuthClient { acceptInvitation: (invitationId: string) => Promise; /** * The one-step invitation acceptance (objectstack - * `POST /organization/accept-invitation-with-proof`). With the mailbox + * `POST /organization/accept-invitation-one-step`). With the mailbox * proof the invitation mail's link carries, it needs no session: it creates * the account (or sets the password of an unverified one), verifies the * address, accepts and signs in, answering `accepted`, or `sign_in` when the @@ -631,7 +631,7 @@ export interface AuthClient { * verified, else answers `verify_email`. Rejects with the server's `code` and * `status` otherwise (`INVALID_TOKEN` for any proof that does not admit). */ - acceptInvitationWithProof: (input: AuthInvitationProofInput) => Promise; + acceptInvitationOneStep: (input: AuthInvitationOneStepInput) => Promise; /** Reject an invitation as the current user */ rejectInvitation: (invitationId: string) => Promise; /** List invitations addressed to the current user */ @@ -732,7 +732,7 @@ export interface AuthInvitationPreview { } /** The body of the one-step invitation acceptance. */ -export interface AuthInvitationProofInput { +export interface AuthInvitationOneStepInput { invitationId: string; /** The mailbox proof from the invitation mail's link; absent for a signed-in session. */ proof?: string; @@ -741,7 +741,7 @@ export interface AuthInvitationProofInput { } /** What the one-step invitation acceptance answers. */ -export type AuthInvitationProofOutcome = +export type AuthInvitationOneStepOutcome = | { outcome: 'accepted'; organizationId: string } | { outcome: 'sign_in' } | { outcome: 'verify_email' }; diff --git a/ui/packages/auth/src/useAuth.ts b/ui/packages/auth/src/useAuth.ts index 434899834ba..75fc6517070 100644 --- a/ui/packages/auth/src/useAuth.ts +++ b/ui/packages/auth/src/useAuth.ts @@ -86,7 +86,7 @@ export function useAuth(): AuthContextValue { getInvitation: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, getInvitationPreview: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, acceptInvitation: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, - acceptInvitationWithProof: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, + acceptInvitationOneStep: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, rejectInvitation: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, listUserInvitations: async () => { throw new Error('useAuth must be used within an AuthProvider'); }, }; From 4de8ae8e7dbf810895895732b8eb5776162f99f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:37:24 +0000 Subject: [PATCH 18/26] test(auth): make the mismatched proof always differ from the real one The mismatch case changed the proof's last character to x, which equals the real proof whenever the random proof already ends in x. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../src/invitation-one-step-acceptance-34257.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 323796d55d4..28105e04517 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -320,7 +320,7 @@ describe('#34257 — accepting with the proof', () => { const { engine, manager, invite } = await boot(); const { invitation, proof } = await invite('guarded@example.com'); await expectRefused( - await door(manager, { invitationId: invitation.id, proof: `${proof.slice(0, -1)}x`, name: 'G', password: PASSWORD }), + await door(manager, { invitationId: invitation.id, proof: `${proof.slice(0, -1)}${proof.endsWith('x') ? 'y' : 'x'}`, name: 'G', password: PASSWORD }), ); expect(userRow(engine, 'guarded@example.com')).toBeUndefined(); const good = await door(manager, { invitationId: invitation.id, proof, name: 'G', password: PASSWORD }); From 0e8a0d37b2388c41d03b9480b666ad1c6ff55876 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:57:35 +0000 Subject: [PATCH 19/26] fix(auth): the one-step door's closing rule is an allow-list, and it keeps the password history The judge sets a password only when every value it reads is positively the one that carries no other claim; a verified phone number is a claim, and a value no rule names answers sign_in. On the arm that replaces a password the history is consulted before the proof is spent and extended after, as the reset door does. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../34257-one-step-invitation-acceptance.md | 4 +- ...principal-doors-grants-and-organization.md | 7 +- .../src/auth-manager-plugin-list.ts | 4 + .../plugins/plugin-auth/src/auth-manager.ts | 2 + .../src/invitation-mailbox-proof.ts | 123 +++++++++++++----- ...vitation-one-step-acceptance-34257.test.ts | 73 +++++++++++ 6 files changed, 180 insertions(+), 33 deletions(-) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index c0ac2600689..28296da6fd5 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -13,8 +13,8 @@ Clause-②: yes (widening) Metadata-protocol: none - **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row. -- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. -- **An address with an account signs in as today.** The door sets a password on an existing account only when the account's address is not verified and the mailbox is its one claim: an account that is verified, linked to a provider, enrolled in a second factor, provisioned by an identity provider, waiting for its first single sign-on or whose source cannot be read, or a server in SSO-only mode or with email and password off, answers `sign_in`, and the proof stays unspent. +- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. +- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor and no verified phone number, its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent. - **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. - **`SendTemplateInput.deliverOnlyData`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row, which gives no sign they were overlaid. Required template variables are checked against `data` alone. A send carrying them is delivered inline, never through the durable queue, so its sender gives up queued delivery where a queue is mounted. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index 79f29791b3c..94c089dc886 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -311,8 +311,11 @@ and a session for that account. The proof is never at rest in clear, the stored bound to the invitation, its address and its expiry; a resend retires the old one. It is spent only by a request that passed every gate, and one server process serializes concurrent redemptions of it; across processes, single use is as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check -failed. An address whose account is verified, is linked to a provider, or otherwise takes no password from this door -is answered "sign in", with the proof unspent. A cloud-managed environment sets no local password, so there the door +failed. The door sets a password on an existing account only when it reads that the mailbox is the account's one +claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, +it has no second factor and no verified phone number, its identity source is local, and the server allows a local +password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, +answers `sign_in`, and the proof stays unspent. A cloud-managed environment sets no local password, so there the door refuses every request that carries a proof. It carries a rate limit per client network address and per invitation, as ADR-0121 D6 requires. Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index e2a4564d7e6..50c200e9a07 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -132,6 +132,8 @@ export interface PluginListHost { resolveAuthSecret: AuthManager['resolveAuthSecret']; resolveMembershipRole: AuthManager['resolveMembershipRole']; resolveTwoFactorAccountLockout: AuthManager['resolveTwoFactorAccountLockout']; + assertPasswordNotReused: AuthManager['assertPasswordNotReused']; + recordPasswordHistory: AuthManager['recordPasswordHistory']; stampPasswordChangedAt: AuthManager['stampPasswordChangedAt']; storedRecipientLocale: AuthManager['storedRecipientLocale']; validateAudienceAdmission: AuthManager['validateAudienceAdmission']; @@ -308,6 +310,8 @@ export async function buildPluginList(this: PluginListHost): Promise { getDataEngine: () => this.getDataEngine(), counterStore: () => this.config.sharedCounterStore?.() ?? Promise.reject(new Error('no shared counter store')), stampPasswordChangedAt: (userId) => this.stampPasswordChangedAt(userId), + assertPasswordNotReused: (userId, candidate, verify) => this.assertPasswordNotReused(userId, candidate, verify), + recordPasswordHistory: (userId, oldHash) => this.recordPasswordHistory(userId, oldHash), })); } diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 90f5c6b6c97..bfe06d9c1f6 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -2455,6 +2455,8 @@ export class AuthManager { resolveAuthSecret: (...a) => this.resolveAuthSecret(...a), resolveMembershipRole: (...a) => this.resolveMembershipRole(...a), resolveTwoFactorAccountLockout: (...a) => this.resolveTwoFactorAccountLockout(...a), + assertPasswordNotReused: (...a) => this.assertPasswordNotReused(...a), + recordPasswordHistory: (...a) => this.recordPasswordHistory(...a), stampPasswordChangedAt: (...a) => this.stampPasswordChangedAt(...a), storedRecipientLocale: (...a) => this.storedRecipientLocale(...a), validateAudienceAdmission: (...a) => this.validateAudienceAdmission(...a), diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 79ff3d9172c..698b710b7a3 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -57,17 +57,25 @@ * * ## Which existing account the door sets a password on * - * The closing rule: the door sets a password on an existing account only when - * the mailbox the proof establishes is the account's one and only claim, and - * the server lets a local password be set here at all. Every other existing - * account answers `sign_in` with the proof unspent. The states, each one a - * reason the account holds a claim the proof does not outrank or the server - * sets no local password, are {@link ONE_STEP_SIGN_IN_STATES}, judged by - * {@link oneStepSignInState}; the card's test pins one case per state. + * The door sets a password on an existing account only when it reads that the + * mailbox is the account's one claim: the address is not verified, the + * account's only sign-in account is its email and password one or it has + * none, it has no second factor and no verified phone number, its identity + * source is local, and the server allows a local password here (not SSO-only, + * email and password on). Every other account, including one in a state no + * rule names, answers `sign_in`, and the proof stays unspent. + * + * The judge, {@link oneStepSignInState}, is an allow-list: it lets the + * password be set only when every value it reads is positively the one that + * carries no other claim, and a value no rule names answers `sign_in` as + * `unrecognised`. Its reasons are {@link ONE_STEP_SIGN_IN_STATES}; the card's + * test pins one case per reason. * * An account that passes gets the typed password in place of its own, and * every one of its sessions is revoked with the reason a password reset - * records (`session-tombstone.ts`). A new account is created through the + * records (`session-tombstone.ts`). The password history is consulted before + * the proof is spent and extended after, as the reset door does (ADR-0069 + * D1): a reused password is refused with the proof unspent. A new account is created through the * internal adapter, so the sign-up gates that run on every creation (audience * admission and the database hooks) run here too; the door itself refuses * where email sign-up is off. Either way the password-age stamp and the @@ -198,12 +206,26 @@ export interface InvitationProofDoorHost { counterStore?: () => Promise; /** The ADR-0069 D1 after-effects of a password set (`AuthManager#stampPasswordChangedAt`). */ stampPasswordChangedAt(userId: string): Promise; + /** + * ADR-0069 D1, the reset door's reuse check (`AuthManager#assertPasswordNotReused`): + * throws `PASSWORD_REUSE`, or answers the current hash for the history. + */ + assertPasswordNotReused( + userId: string, + candidate: string, + verify?: (data: { password: string; hash: string }) => Promise, + ): Promise; + /** ADR-0069 D1, the reset door's history append (`AuthManager#recordPasswordHistory`). */ + recordPasswordHistory(userId: string, oldHash: string): Promise; } /** - * The states of an existing account that answer `sign_in`, in the order they - * are judged. Each is either a claim on the account the mailbox proof does not - * outrank, or a server that sets no local password here. + * Why an existing account answers `sign_in`. The judge + * ({@link oneStepSignInState}) is an allow-list: these name the reasons it + * reports, and `unrecognised` is every value it does not positively read as + * carrying no other claim. Each named state is either a claim on the account + * the mailbox proof does not outrank, or a server that sets no local password + * here. */ export const ONE_STEP_SIGN_IN_STATES = [ /** The address is already verified: its holder signs in. */ @@ -212,6 +234,8 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'linked_provider', /** The account has a second factor enrolled. */ 'second_factor', + /** The account has a verified phone number. */ + 'verified_phone', /** The account is provisioned by an identity provider. */ 'idp_provisioned', /** The account is waiting for its first single sign-on. */ @@ -222,27 +246,58 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'sso_only', /** Email and password sign-in is off. */ 'email_password_off', + /** A stored value the judge does not read as carrying no other claim, such as an identity source no rule names. */ + 'unrecognised', ] as const; export type OneStepSignInState = (typeof ONE_STEP_SIGN_IN_STATES)[number]; -/** The first state of {@link ONE_STEP_SIGN_IN_STATES} the account is in, or `undefined` when the door may set its password. */ -export function oneStepSignInState(account: { - emailVerified: boolean; - linkedProvider: boolean; - twoFactorEnabled: boolean; +/** The `sys_user.source` values of a local account: the declared one, and none recorded. */ +const LOCAL_SOURCES: ReadonlySet = new Set(['env_native', null]); + +/** A flag that is positively off: false, or absent because its plugin is not mounted. */ +function isOff(value: unknown): boolean { + return value === false || value === null || value === undefined; +} + +/** What the judge reads of an existing account and the server. */ +export interface OneStepAccountReading { + /** `user.emailVerified`, as stored. */ + emailVerified: unknown; + /** The `providerId` of each of the user's account rows. */ + accountProviders: readonly unknown[]; + /** `user.twoFactorEnabled`, as stored (absent without the plugin). */ + twoFactorEnabled: unknown; + /** `user.phoneNumberVerified`, as stored (absent without the plugin). */ + phoneNumberVerified: unknown; + /** `sys_user.source`, or `ok: false` when it cannot be read. */ source: { ok: true; value: string | null } | { ok: false }; + /** SSO-only mode. */ ssoOnly: boolean; - emailPasswordEnabled: boolean; -}): OneStepSignInState | undefined { - if (account.emailVerified) return 'verified'; - if (account.linkedProvider) return 'linked_provider'; - if (account.twoFactorEnabled) return 'second_factor'; - if (account.source.ok && isIdpProvisionedSource(account.source.value)) return 'idp_provisioned'; - if (account.source.ok && isPendingSsoSource(account.source.value)) return 'pending_sso'; + /** `emailAndPassword.enabled`. */ + emailPasswordEnabled: unknown; +} + +/** + * The judge of the closing rule, an allow-list: `undefined` (the door may set + * the password) only when every reading is positively the no-other-claim + * value, and otherwise the reason the account answers `sign_in`. A value no + * rule here names is `unrecognised`, never a pass. + */ +export function oneStepSignInState(account: OneStepAccountReading): OneStepSignInState | undefined { + if (account.emailVerified !== false) return account.emailVerified === true ? 'verified' : 'unrecognised'; + if (!account.accountProviders.every((providerId) => providerId === 'credential')) return 'linked_provider'; + if (!isOff(account.twoFactorEnabled)) return account.twoFactorEnabled === true ? 'second_factor' : 'unrecognised'; + if (!isOff(account.phoneNumberVerified)) return account.phoneNumberVerified === true ? 'verified_phone' : 'unrecognised'; if (!account.source.ok) return 'source_unreadable'; - if (account.ssoOnly) return 'sso_only'; - if (!account.emailPasswordEnabled) return 'email_password_off'; + const source = account.source.value; + if (!LOCAL_SOURCES.has(source)) { + if (isIdpProvisionedSource(source)) return 'idp_provisioned'; + if (isPendingSsoSource(source)) return 'pending_sso'; + return 'unrecognised'; + } + if (account.ssoOnly !== false) return 'sso_only'; + if (account.emailPasswordEnabled !== true) return 'email_password_off'; return undefined; } @@ -352,12 +407,13 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo const existing = found?.user; if (existing) { const state = oneStepSignInState({ - emailVerified: existing.emailVerified === true, - linkedProvider: (found.accounts ?? []).some((a: any) => a?.providerId !== 'credential'), - twoFactorEnabled: existing.twoFactorEnabled === true, + emailVerified: existing.emailVerified, + accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId), + twoFactorEnabled: existing.twoFactorEnabled, + phoneNumberVerified: existing.phoneNumberVerified, source: await readUserSource(host.getDataEngine() as never, String(existing.id)), ssoOnly: host.isSsoOnlyMode(), - emailPasswordEnabled: Boolean(ctx.context.options.emailAndPassword?.enabled), + emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled, }); if (state) return ctx.json({ success: true, data: { outcome: 'sign_in' } }); } @@ -390,6 +446,14 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo } } + // ADR-0069 D1, as the reset door: the password history is consulted + // before the proof is spent, so a reused password leaves it usable. + let historyHash: string | undefined; + if (existing) { + const pw = ctx.context.password; + historyHash = await host.assertPasswordNotReused(String(existing.id), password, pw.verify.bind(pw)); + } + // Hashed before the proof is spent: a password the hash step refuses // (a breached one) leaves the proof usable. const passwordHash = await ctx.context.password.hash(password); @@ -406,6 +470,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo await internal.deleteUserSessions(userId); if (await internal.findCredentialAccount(userId)) { await internal.updatePassword(userId, passwordHash); + if (historyHash) await host.recordPasswordHistory(userId, historyHash); } else { await internal.createAccount({ userId, providerId: 'credential', accountId: userId, password: passwordHash }); } diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 28105e04517..a0dce96df9e 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -19,6 +19,8 @@ import { ACCEPT_INVITATION_ONE_STEP_PATH, ONE_STEP_SIGN_IN_STATES, invitationProofIdentifier, + oneStepSignInState, + type OneStepAccountReading, type OneStepSignInState, } from './invitation-mailbox-proof'; import { BREACH_CHECK_VENDOR_DEFAULT_PATHS } from './auth-manager-plugin-list'; @@ -698,6 +700,16 @@ describe('#34257 — the door sets a password only where the mailbox is the acco }; }, }, + verified_phone: { + options: { plugins: { phoneNumber: true } }, + enter: async ({ engine }, email) => { + userRow(engine, email)!.phone_number = '+15550134257'; + userRow(engine, email)!.phone_number_verified = true; + return () => { + userRow(engine, email)!.phone_number_verified = false; + }; + }, + }, idp_provisioned: { enter: async ({ engine }, email) => { userRow(engine, email)!.source = 'idp_provisioned'; @@ -729,8 +741,54 @@ describe('#34257 — the door sets a password only where the mailbox is the acco return () => manager.applyConfigPatch({ emailAndPassword: { enabled: true } } as never); }, }, + // An identity source no rule names: a mark the judge cannot read as local. + unrecognised: { + enter: async ({ engine }, email) => { + userRow(engine, email)!.source = 'directory_federated'; + return () => { + userRow(engine, email)!.source = 'env_native'; + }; + }, + }, }; + // The allow-list read: the one reading that lets the password be set, and + // one step off it on each value the judge reads answers a reason. + const ALLOWED: OneStepAccountReading = { + emailVerified: false, + accountProviders: ['credential'], + twoFactorEnabled: false, + phoneNumberVerified: undefined, + source: { ok: true, value: 'env_native' }, + ssoOnly: false, + emailPasswordEnabled: true, + }; + + it('the judge lets the password be set only on the reading that carries no other claim', () => { + expect(oneStepSignInState(ALLOWED)).toBeUndefined(); + expect(oneStepSignInState({ ...ALLOWED, accountProviders: [], source: { ok: true, value: null }, twoFactorEnabled: null })).toBeUndefined(); + }); + + it.each<[string, Partial, OneStepSignInState]>([ + ['an address verified', { emailVerified: true }, 'verified'], + ['a verified flag stored in no form the judge reads', { emailVerified: 0 }, 'unrecognised'], + ['a provider account', { accountProviders: ['credential', 'github'] }, 'linked_provider'], + ['an account with no provider recorded', { accountProviders: [undefined] }, 'linked_provider'], + ['a second factor', { twoFactorEnabled: true }, 'second_factor'], + ['a second-factor flag stored in no form the judge reads', { twoFactorEnabled: 'true' }, 'unrecognised'], + ['a verified phone number', { phoneNumberVerified: true }, 'verified_phone'], + ['a phone flag stored in no form the judge reads', { phoneNumberVerified: 1 }, 'unrecognised'], + ['an identity-provider source', { source: { ok: true, value: 'idp_provisioned' } }, 'idp_provisioned'], + ['a pending single sign-on', { source: { ok: true, value: 'idp_pending' } }, 'pending_sso'], + ['an unreadable source', { source: { ok: false } }, 'source_unreadable'], + ['a source no rule names', { source: { ok: true, value: 'directory_federated' } }, 'unrecognised'], + ['SSO-only mode', { ssoOnly: true }, 'sso_only'], + ['email and password off', { emailPasswordEnabled: false }, 'email_password_off'], + ['email and password not declared on', { emailPasswordEnabled: undefined }, 'email_password_off'], + ])('the judge answers sign_in for %s', (_label, change, reason) => { + expect(oneStepSignInState({ ...ALLOWED, ...change })).toBe(reason); + }); + it('every state the closing rule names has a case, and no case names another state', () => { expect(Object.keys(CASES).sort()).toEqual([...ONE_STEP_SIGN_IN_STATES].sort()); }); @@ -778,6 +836,21 @@ describe('#34257 — a password the door sets starts the password-age clock and expect(new Date(user.password_changed_at).getTime()).toBeGreaterThan(Date.now() - 60_000); }); + it('a password in the history is refused with the proof unspent, and the replaced one is recorded', async () => { + const { engine, manager, invite } = await boot({ passwordHistoryCount: 3 }); + const { invitation, proof } = await invite('history@example.com'); + const { userId } = await signUp(manager, engine, 'history@example.com'); + const credential = () => (engine.tables.get('sys_account') ?? []).find((a) => a.user_id === userId && a.provider_id === 'credential'); + const replacedHash = credential()!.password; + const before = writtenState(engine); + + await expectAnswer(await door(manager, { invitationId: invitation.id, proof, name: 'H', password: PASSWORD }), 400, 'PASSWORD_REUSE'); + expect(writtenState(engine)).toBe(before); + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'H', password: NEW_PASSWORD })); + expect(JSON.parse(credential()!.previous_password_hashes)).toEqual([replacedHash]); + }); + it('the sessions the door ends are ledgered with the reason a password reset records', () => { expect(INTERACTIVE_REVOKE_REASON[ACCEPT_INVITATION_ONE_STEP_PATH]).toBe('password_reset'); }); From 518f1d6ba0779bc2f1f8107a8ea02a151233c338 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:13:47 +0000 Subject: [PATCH 20/26] fix(auth): standing grants count as claims in the one-step door's closing rule The allow-list also requires that the user holds no sys_api_key row and no sys_oauth_consent row, revoked or not. A missing table holds no rows; a failed read answers sign_in as grant_unreadable. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-Authored-By: Claude --- .../34257-one-step-invitation-acceptance.md | 2 +- ...principal-doors-grants-and-organization.md | 10 +-- .../src/invitation-mailbox-proof.ts | 70 +++++++++++++++++-- ...vitation-one-step-acceptance-34257.test.ts | 65 ++++++++++++++++- 4 files changed, 133 insertions(+), 14 deletions(-) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index 28296da6fd5..4a2321a5ea7 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -14,7 +14,7 @@ Metadata-protocol: none - **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row. - **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. -- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor and no verified phone number, its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent. +- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor, no verified phone number, no API key and no OAuth client consent, its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent. - **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. - **`SendTemplateInput.deliverOnlyData`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row, which gives no sign they were overlaid. Required template variables are checked against `data` alone. A send carrying them is delivered inline, never through the durable queue, so its sender gives up queued delivery where a queue is mounted. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index 94c089dc886..c24a68ae829 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -313,11 +313,11 @@ passed every gate, and one server process serializes concurrent redemptions of i as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check failed. The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, -it has no second factor and no verified phone number, its identity source is local, and the server allows a local -password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, -answers `sign_in`, and the proof stays unspent. A cloud-managed environment sets no local password, so there the door -refuses every request that carries a proof. It carries a rate limit per client network address and per invitation, -as ADR-0121 D6 requires. Enforced by +it has no second factor, no verified phone number, no API key and no OAuth client consent, its identity source is +local, and the server allows a local password here (not SSO-only, email and password on). Every other account, +including one in a state no rule names, answers `sign_in`, and the proof stays unspent. A cloud-managed environment +sets no local password, so there the door refuses every request that carries a proof. It carries a rate limit per +client network address and per invitation, as ADR-0121 D6 requires. Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in `packages/plugins/plugin-auth/src/auth-route-ledger.ts`. It is a better-auth endpoint, so it rides the `/auth` catch-all, which no route table lists door by door: the anonymous sweep's classification names it under class 2 as a diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 698b710b7a3..32e119d701f 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -60,10 +60,11 @@ * The door sets a password on an existing account only when it reads that the * mailbox is the account's one claim: the address is not verified, the * account's only sign-in account is its email and password one or it has - * none, it has no second factor and no verified phone number, its identity - * source is local, and the server allows a local password here (not SSO-only, - * email and password on). Every other account, including one in a state no - * rule names, answers `sign_in`, and the proof stays unspent. + * none, it has no second factor, no verified phone number, no API key and no + * OAuth client consent, its identity source is local, and the server allows a + * local password here (not SSO-only, email and password on). Every other + * account, including one in a state no rule names, answers `sign_in`, and the + * proof stays unspent. * * The judge, {@link oneStepSignInState}, is an allow-list: it lets the * password be set only when every value it reads is positively the one that @@ -71,6 +72,11 @@ * `unrecognised`. Its reasons are {@link ONE_STEP_SIGN_IN_STATES}; the card's * test pins one case per reason. * + * Standing grants count as claims ({@link readStandingGrant}): any + * `sys_api_key` or `sys_oauth_consent` row of the user, revoked or not, + * answers `sign_in`. A table that does not exist holds no rows; a read that + * fails answers `sign_in` as `grant_unreadable`. + * * An account that passes gets the typed password in place of its own, and * every one of its sessions is revoked with the reason a password reset * records (`session-tombstone.ts`). The password history is consulted before @@ -91,11 +97,12 @@ */ import { isCloudManaged } from '@objectstack/core'; +import { isMissingTableError } from '@objectstack/types'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { incrementFixedWindow, InProcessCounterStore, type CounterStore } from './rate-limit-storage.js'; import { readRequestClientAddress } from './request-client-address.js'; import { isPendingSsoSource } from './pending-sso-marker.js'; -import { isIdpProvisionedSource, readUserSource } from './sso-only-local-password.js'; +import { isIdpProvisionedSource, readUserSource, type UserSourceReader } from './sso-only-local-password.js'; /** The door's path, under the auth mount. */ export const ACCEPT_INVITATION_ONE_STEP_PATH = '/organization/accept-invitation-one-step'; @@ -236,6 +243,12 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'second_factor', /** The account has a verified phone number. */ 'verified_phone', + /** The account holds an API key, revoked or not. */ + 'api_key', + /** The account holds an OAuth client consent, revoked or not. */ + 'oauth_consent', + /** The account's standing grants cannot be read. */ + 'grant_unreadable', /** The account is provisioned by an identity provider. */ 'idp_provisioned', /** The account is waiting for its first single sign-on. */ @@ -260,6 +273,35 @@ function isOff(value: unknown): boolean { return value === false || value === null || value === undefined; } +/** The objects whose rows are a user's standing grants, each read by `user_id`. */ +export const STANDING_GRANT_OBJECTS = ['sys_api_key', 'sys_oauth_consent'] as const; + +/** Whether a user holds any row of one standing-grant object; `ok: false` when it cannot be read. */ +export type StandingGrantReading = { ok: true; held: boolean } | { ok: false }; + +const SYSTEM_READ = { context: { isSystem: true, positions: [], permissions: [] } } as const; + +/** + * Does `userId` hold any row of `object`, revoked or not? One indexed read by + * `user_id`, `id` only, as the system. A table that does not exist holds no + * rows; any other failure, or no read surface, is `ok: false`. + */ +export async function readStandingGrant( + engine: UserSourceReader | undefined, + object: (typeof STANDING_GRANT_OBJECTS)[number], + userId: string, +): Promise { + if (!engine?.find) return { ok: false }; + try { + const rows = await engine.find(object, { where: { user_id: userId }, fields: ['id'], limit: 1 }, SYSTEM_READ); + if (!Array.isArray(rows)) return { ok: false }; + return { ok: true, held: rows.length > 0 }; + } catch (e) { + if (isMissingTableError(e, object)) return { ok: true, held: false }; + return { ok: false }; + } +} + /** What the judge reads of an existing account and the server. */ export interface OneStepAccountReading { /** `user.emailVerified`, as stored. */ @@ -270,6 +312,10 @@ export interface OneStepAccountReading { twoFactorEnabled: unknown; /** `user.phoneNumberVerified`, as stored (absent without the plugin). */ phoneNumberVerified: unknown; + /** Any `sys_api_key` row of the user ({@link readStandingGrant}). */ + apiKeys: StandingGrantReading; + /** Any `sys_oauth_consent` row of the user ({@link readStandingGrant}). */ + oauthConsents: StandingGrantReading; /** `sys_user.source`, or `ok: false` when it cannot be read. */ source: { ok: true; value: string | null } | { ok: false }; /** SSO-only mode. */ @@ -289,6 +335,9 @@ export function oneStepSignInState(account: OneStepAccountReading): OneStepSignI if (!account.accountProviders.every((providerId) => providerId === 'credential')) return 'linked_provider'; if (!isOff(account.twoFactorEnabled)) return account.twoFactorEnabled === true ? 'second_factor' : 'unrecognised'; if (!isOff(account.phoneNumberVerified)) return account.phoneNumberVerified === true ? 'verified_phone' : 'unrecognised'; + if (!account.apiKeys.ok || !account.oauthConsents.ok) return 'grant_unreadable'; + if (account.apiKeys.held !== false) return 'api_key'; + if (account.oauthConsents.held !== false) return 'oauth_consent'; if (!account.source.ok) return 'source_unreadable'; const source = account.source.value; if (!LOCAL_SOURCES.has(source)) { @@ -406,12 +455,21 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo const found = await internal.findUserByEmail(email, { includeAccounts: true }); const existing = found?.user; if (existing) { + const engine = host.getDataEngine() as UserSourceReader | undefined; + const userId = String(existing.id); + const [apiKeys, oauthConsents, source] = await Promise.all([ + readStandingGrant(engine, 'sys_api_key', userId), + readStandingGrant(engine, 'sys_oauth_consent', userId), + readUserSource(engine, userId), + ]); const state = oneStepSignInState({ emailVerified: existing.emailVerified, accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId), twoFactorEnabled: existing.twoFactorEnabled, phoneNumberVerified: existing.phoneNumberVerified, - source: await readUserSource(host.getDataEngine() as never, String(existing.id)), + apiKeys, + oauthConsents, + source, ssoOnly: host.isSsoOnlyMode(), emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled, }); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index a0dce96df9e..63b763b459c 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -458,8 +458,18 @@ describe('#34257 — a signed-in return accepts only a verified address', () => // The tables a redemption writes: the account, its credential, its sessions, -// the membership, the invitation and the proof row. -const WRITTEN_TABLES = ['sys_user', 'sys_account', 'sys_session', 'sys_member', 'sys_invitation', 'sys_verification']; +// the membership, the invitation and the proof row; and the standing grants +// the judge reads, which nothing here writes. +const WRITTEN_TABLES = [ + 'sys_user', + 'sys_account', + 'sys_session', + 'sys_member', + 'sys_invitation', + 'sys_verification', + 'sys_api_key', + 'sys_oauth_consent', +]; const writtenState = (engine: MemoryEngine) => JSON.stringify(WRITTEN_TABLES.map((table) => [table, engine.tables.get(table) ?? []])); @@ -661,6 +671,16 @@ describe('#34257 — the door sets a password only where the mailbox is the acco /** Put the account into the state, and answer how to take it out again. */ enter(booted: Booted, email: string): Promise<() => Promise | void>; } + const findThrowsFor = (engine: MemoryEngine, object: string, error: Error) => { + const find = engine.find.bind(engine); + engine.find = async (name: string, q: any = {}) => { + if (name === object) throw error; + return find(name, q); + }; + return () => { + engine.find = find; + }; + }; const findThrowsForSource = (engine: MemoryEngine) => { const find = engine.find.bind(engine); engine.find = async (name: string, q: any = {}) => { @@ -710,6 +730,26 @@ describe('#34257 — the door sets a password only where the mailbox is the acco }; }, }, + // A standing grant counts as a claim, a revoked one included. + api_key: { + enter: async ({ engine }, email) => { + await engine.insert('sys_api_key', { id: `key_${email}`, user_id: userRow(engine, email)!.id, revoked: true }); + return () => { + engine.tables.set('sys_api_key', (engine.tables.get('sys_api_key') ?? []).filter((k) => k.id !== `key_${email}`)); + }; + }, + }, + oauth_consent: { + enter: async ({ engine }, email) => { + await engine.insert('sys_oauth_consent', { id: `consent_${email}`, user_id: userRow(engine, email)!.id, client_id: 'client_34257', scopes: '["openid"]' }); + return () => { + engine.tables.set('sys_oauth_consent', (engine.tables.get('sys_oauth_consent') ?? []).filter((c) => c.id !== `consent_${email}`)); + }; + }, + }, + grant_unreadable: { + enter: async ({ engine }) => findThrowsFor(engine, 'sys_oauth_consent', new Error('store unavailable')), + }, idp_provisioned: { enter: async ({ engine }, email) => { userRow(engine, email)!.source = 'idp_provisioned'; @@ -759,6 +799,8 @@ describe('#34257 — the door sets a password only where the mailbox is the acco accountProviders: ['credential'], twoFactorEnabled: false, phoneNumberVerified: undefined, + apiKeys: { ok: true, held: false }, + oauthConsents: { ok: true, held: false }, source: { ok: true, value: 'env_native' }, ssoOnly: false, emailPasswordEnabled: true, @@ -778,6 +820,10 @@ describe('#34257 — the door sets a password only where the mailbox is the acco ['a second-factor flag stored in no form the judge reads', { twoFactorEnabled: 'true' }, 'unrecognised'], ['a verified phone number', { phoneNumberVerified: true }, 'verified_phone'], ['a phone flag stored in no form the judge reads', { phoneNumberVerified: 1 }, 'unrecognised'], + ['an API key', { apiKeys: { ok: true, held: true } }, 'api_key'], + ['an OAuth client consent', { oauthConsents: { ok: true, held: true } }, 'oauth_consent'], + ['API keys that cannot be read', { apiKeys: { ok: false } }, 'grant_unreadable'], + ['OAuth client consents that cannot be read', { oauthConsents: { ok: false } }, 'grant_unreadable'], ['an identity-provider source', { source: { ok: true, value: 'idp_provisioned' } }, 'idp_provisioned'], ['a pending single sign-on', { source: { ok: true, value: 'idp_pending' } }, 'pending_sso'], ['an unreadable source', { source: { ok: false } }, 'source_unreadable'], @@ -789,6 +835,21 @@ describe('#34257 — the door sets a password only where the mailbox is the acco expect(oneStepSignInState({ ...ALLOWED, ...change })).toBe(reason); }); + it('a grant table that does not exist holds no grant: the account is accepted', async () => { + const booted = await boot(); + const { engine, manager, invite } = booted; + const email = 'grants-absent@example.com'; + const { invitation, proof } = await invite(email); + await signUp(manager, engine, email); + const leaveKeys = findThrowsFor(engine, 'sys_api_key', new Error('SQLITE_ERROR: no such table: sys_api_key')); + findThrowsFor(engine, 'sys_oauth_consent', new Error('SQLITE_ERROR: no such table: sys_oauth_consent')); + try { + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'G', password: NEW_PASSWORD })); + } finally { + leaveKeys(); + } + }); + it('every state the closing rule names has a case, and no case names another state', () => { expect(Object.keys(CASES).sort()).toEqual([...ONE_STEP_SIGN_IN_STATES].sort()); }); From 3e35729bbdd4de8d047a5a68d5fdf698a4c03417 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 20:07:31 +0000 Subject: [PATCH 21/26] fix(auth): every user-keyed store the plugin mounts is classified for the one-step door The closing rule's standing grants now cover every store the plugin mounts that grants an account standing access: API keys, OAuth client consents, OAuth access and refresh tokens, OAuth clients, device authorizations, second-factor enrolments, SSO providers, SCIM credentials and identity provider directory links. Each is one indexed read by user_id, limit 1, revoked rows included; a missing table holds no rows and any other failure answers sign_in as grant_unreadable. Every other user-keyed store is classified as no claim, and a test holds the classification to the list the plugin mounts. The session revocation and the password write match the vendor's order, pinned. sys_device_code gains an index on user_id. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../34257-one-step-invitation-acceptance.md | 6 +- ...principal-doors-grants-and-organization.md | 8 +- .../src/identity/sys-device-code.object.ts | 3 + .../src/invitation-mailbox-proof.ts | 134 ++++++++++++---- ...vitation-one-step-acceptance-34257.test.ts | 144 ++++++++++++++---- 5 files changed, 239 insertions(+), 56 deletions(-) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index 4a2321a5ea7..4365a82a04d 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -2,6 +2,7 @@ '@objectstack/spec': patch '@objectstack/plugin-email': patch '@objectstack/plugin-auth': patch +'@objectstack/platform-objects': patch '@object-ui/auth': patch '@object-ui/app-shell': patch '@object-ui/i18n': patch @@ -13,8 +14,9 @@ Clause-②: yes (widening) Metadata-protocol: none - **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row. -- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. -- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor, no verified phone number, no API key and no OAuth client consent, its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent. +- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records, in an order that matches the vendor's order), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. +- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor, enabled or enrolled, no verified phone number and no standing grant (an API key, an OAuth client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an identity provider's directory, revoked or expired ones included), its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent. Every store the plugin mounts that is keyed by a user is classified as a claim the judge reads or as no claim, and a test holds that classification to the mounted list. +- **`sys_device_code` gains an index on `user_id`** (`@objectstack/platform-objects`), so the door reads a user's device authorizations by an indexed lookup, as it reads every other standing grant. - **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. - **`SendTemplateInput.deliverOnlyData`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row, which gives no sign they were overlaid. Required template variables are checked against `data` alone. A send carrying them is delivered inline, never through the durable queue, so its sender gives up queued delivery where a queue is mounted. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none. diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index c24a68ae829..dd655f0e4bc 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -313,9 +313,13 @@ passed every gate, and one server process serializes concurrent redemptions of i as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check failed. The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, -it has no second factor, no verified phone number, no API key and no OAuth client consent, its identity source is +it has no second factor, enabled or enrolled, no verified phone number and no standing grant (an API key, an OAuth +client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM +credential or a link to an identity provider's directory, revoked or expired ones included), its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, -including one in a state no rule names, answers `sign_in`, and the proof stays unspent. A cloud-managed environment +including one in a state no rule names, answers `sign_in`, and the proof stays unspent. Every store the plugin mounts +that is keyed by a user is classified as a claim the judge reads or as no claim, and a test holds that classification +to the mounted list. A cloud-managed environment sets no local password, so there the door refuses every request that carries a proof. It carries a rate limit per client network address and per invitation, as ADR-0121 D6 requires. Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in diff --git a/packages/platform-objects/src/identity/sys-device-code.object.ts b/packages/platform-objects/src/identity/sys-device-code.object.ts index b5f2291f1f2..10a228bd889 100644 --- a/packages/platform-objects/src/identity/sys-device-code.object.ts +++ b/packages/platform-objects/src/identity/sys-device-code.object.ts @@ -161,6 +161,9 @@ export const SysDeviceCode = ObjectSchema.create({ { fields: ['device_code'], unique: 'global' }, { fields: ['user_code'], unique: 'global' }, { fields: ['status'], unique: false }, + // The one-step invitation door reads a user's device authorizations by + // this column (`plugin-auth` `invitation-mailbox-proof.ts`). + { fields: ['user_id'], unique: false }, ], enable: { diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 32e119d701f..63530132c7c 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -50,7 +50,7 @@ * account the one-step path does not set a password on (the closing rule * below). The proof is not spent; the person signs in as today. * - `{ outcome: 'verify_email' }` — session mode, and the session's address is - * not verified. Nothing is accepted. + * not the invited one, or is not verified. Nothing is accepted. * - `400 INVALID_TOKEN` — any proof that does not admit: unknown, used, * expired, for another invitation or address, or an invitation that is no * longer pending. One answer, which does not say which check failed. @@ -60,11 +60,16 @@ * The door sets a password on an existing account only when it reads that the * mailbox is the account's one claim: the address is not verified, the * account's only sign-in account is its email and password one or it has - * none, it has no second factor, no verified phone number, no API key and no - * OAuth client consent, its identity source is local, and the server allows a - * local password here (not SSO-only, email and password on). Every other - * account, including one in a state no rule names, answers `sign_in`, and the - * proof stays unspent. + * none, it has no second factor, enabled or enrolled, no verified phone + * number and no standing grant (an API key, an OAuth client consent, an OAuth + * access or refresh token, an OAuth client, a device authorization, an SSO + * provider, a SCIM credential or a link to an identity provider's directory, + * revoked or expired ones included), its identity source is local, and the + * server allows a local password here (not SSO-only, email and password on). + * Every other account, including one in a state no rule names, answers + * `sign_in`, and the proof stays unspent. Every store the plugin mounts that + * is keyed by a user is classified as a claim the judge reads or as no claim, + * and a test holds that classification to the mounted list. * * The judge, {@link oneStepSignInState}, is an allow-list: it lets the * password be set only when every value it reads is positively the one that @@ -72,14 +77,16 @@ * `unrecognised`. Its reasons are {@link ONE_STEP_SIGN_IN_STATES}; the card's * test pins one case per reason. * - * Standing grants count as claims ({@link readStandingGrant}): any - * `sys_api_key` or `sys_oauth_consent` row of the user, revoked or not, - * answers `sign_in`. A table that does not exist holds no rows; a read that - * fails answers `sign_in` as `grant_unreadable`. + * Standing grants count as claims ({@link USER_KEYED_STORES}, + * {@link readStandingGrant}): any row of the user in a standing-grant object, + * revoked or not, answers `sign_in`. A table that does not exist holds no + * rows; a read that fails answers `sign_in` as `grant_unreadable`. The + * plugin's `passkeys` flag is not wired today; if it is ever wired, a passkey + * is a claim the judge must read. * * An account that passes gets the typed password in place of its own, and * every one of its sessions is revoked with the reason a password reset - * records (`session-tombstone.ts`). The password history is consulted before + * records (`session-tombstone.ts`); the two writes match the vendor's order. The password history is consulted before * the proof is spent and extended after, as the reset door does (ADR-0069 * D1): a reused password is refused with the proof unspent. A new account is created through the * internal adapter, so the sign-up gates that run on every creation (audience @@ -239,7 +246,7 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'verified', /** The account is linked to a sign-in provider. */ 'linked_provider', - /** The account has a second factor enrolled. */ + /** The account has a second factor enabled or enrolled. */ 'second_factor', /** The account has a verified phone number. */ 'verified_phone', @@ -247,6 +254,18 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'api_key', /** The account holds an OAuth client consent, revoked or not. */ 'oauth_consent', + /** The account holds an OAuth access or refresh token, expired or not. */ + 'oauth_token', + /** The account registered an OAuth client. */ + 'oauth_client', + /** The account approved a device authorization, expired or not. */ + 'device_code', + /** The account registered an SSO provider. */ + 'sso_provider', + /** The account minted a SCIM credential, revoked or not. */ + 'scim_credential', + /** The account is linked to an identity provider's directory (a SCIM user, subject, projected grant or tombstone). */ + 'idp_linked', /** The account's standing grants cannot be read. */ 'grant_unreadable', /** The account is provisioned by an identity provider. */ @@ -273,8 +292,69 @@ function isOff(value: unknown): boolean { return value === false || value === null || value === undefined; } +/** + * Every store the plugin mounts that is keyed by a user: each column of an + * object in `authIdentityManifest` (`manifest.ts`) that references `sys_user` + * or is named `user_id`, classified. A test derives that set from the + * manifest and holds it equal to this table's keys, so a store mounted later + * fails it until it is classified here. + * + * - `{ grant }`: a standing grant, a claim. The door reads it by + * {@link readStandingGrant}, and any row answers `sign_in` as `grant`. + * - `{ accounts }`: a claim the judge reads from the account rows the vendor + * loads with the user (`accountProviders`). + * - `{ notAClaim }`: why a row of it is no claim on the account. + * + * The plugin's `passkeys` flag is not wired to any plugin today, so no passkey + * store is mounted; if it is ever wired, a passkey is a claim the judge must + * read, and this table must classify its store. + */ +export const USER_KEYED_STORES = { + 'sys_account.user_id': { accounts: 'linked_provider' }, + 'sys_api_key.user_id': { grant: 'api_key' }, + 'sys_oauth_consent.user_id': { grant: 'oauth_consent' }, + 'sys_oauth_access_token.user_id': { grant: 'oauth_token' }, + 'sys_oauth_refresh_token.user_id': { grant: 'oauth_token' }, + 'sys_oauth_application.user_id': { grant: 'oauth_client' }, + 'sys_device_code.user_id': { grant: 'device_code' }, + 'sys_two_factor.user_id': { grant: 'second_factor' }, + 'sys_sso_provider.user_id': { grant: 'sso_provider' }, + 'sys_scim_connection_credential.user_id': { grant: 'scim_credential' }, + 'sys_scim_user.user_id': { grant: 'idp_linked' }, + 'sys_scim_subject.user_id': { grant: 'idp_linked' }, + 'sys_scim_projection_grant.user_id': { grant: 'idp_linked' }, + 'sys_scim_identity_tombstone.user_id': { grant: 'idp_linked' }, + 'sys_session.user_id': { notAClaim: 'The door revokes every session of the account before it sets the password.' }, + 'sys_session.impersonated_by': { notAClaim: 'A session of another account, acting as that account and never as this one.' }, + 'sys_member.user_id': { notAClaim: 'A membership authorizes a signed-in session and signs no one in.' }, + 'sys_team_member.user_id': { notAClaim: 'A team membership authorizes a signed-in session and signs no one in.' }, + 'sys_invitation.inviter_id': { notAClaim: 'An invitation the account sent grants the account nothing.' }, + 'sys_user.manager_id': { notAClaim: 'Names the account as another user\'s manager and grants the account nothing.' }, + 'sys_user.accountable_user_id': { notAClaim: 'Names the account as accountable for another user and signs no one in as this account.' }, + 'sys_user_preference.user_id': { notAClaim: 'The account\'s own settings, which grant no access.' }, + 'sys_personal_view.user_id': { notAClaim: 'The account\'s own saved list views, which grant no access.' }, +} as const satisfies Record< + string, + { grant: OneStepSignInState } | { accounts: OneStepSignInState } | { notAClaim: string } +>; + +type UserKeyedStore = keyof typeof USER_KEYED_STORES; +type GrantStore = { + [K in UserKeyedStore]: (typeof USER_KEYED_STORES)[K] extends { grant: OneStepSignInState } ? K : never; +}[UserKeyedStore]; +type ObjectOf = S extends `${infer O}.user_id` ? O : never; +/** An object whose rows are a user's standing grants. */ +export type StandingGrantObject = ObjectOf; + +/** The standing grants, in the order the judge reports them: each object, read by `user_id`, and its reason. */ +export const STANDING_GRANTS: ReadonlyArray<{ object: StandingGrantObject; reason: OneStepSignInState }> = Object.entries( + USER_KEYED_STORES, +).flatMap(([store, cls]) => + 'grant' in cls ? [{ object: store.slice(0, -'.user_id'.length) as StandingGrantObject, reason: cls.grant }] : [], +); + /** The objects whose rows are a user's standing grants, each read by `user_id`. */ -export const STANDING_GRANT_OBJECTS = ['sys_api_key', 'sys_oauth_consent'] as const; +export const STANDING_GRANT_OBJECTS: readonly StandingGrantObject[] = STANDING_GRANTS.map((g) => g.object); /** Whether a user holds any row of one standing-grant object; `ok: false` when it cannot be read. */ export type StandingGrantReading = { ok: true; held: boolean } | { ok: false }; @@ -288,7 +368,7 @@ const SYSTEM_READ = { context: { isSystem: true, positions: [], permissions: [] */ export async function readStandingGrant( engine: UserSourceReader | undefined, - object: (typeof STANDING_GRANT_OBJECTS)[number], + object: StandingGrantObject, userId: string, ): Promise { if (!engine?.find) return { ok: false }; @@ -312,10 +392,8 @@ export interface OneStepAccountReading { twoFactorEnabled: unknown; /** `user.phoneNumberVerified`, as stored (absent without the plugin). */ phoneNumberVerified: unknown; - /** Any `sys_api_key` row of the user ({@link readStandingGrant}). */ - apiKeys: StandingGrantReading; - /** Any `sys_oauth_consent` row of the user ({@link readStandingGrant}). */ - oauthConsents: StandingGrantReading; + /** Any row of the user in each standing-grant object ({@link readStandingGrant}). */ + standingGrants: Readonly>; /** `sys_user.source`, or `ok: false` when it cannot be read. */ source: { ok: true; value: string | null } | { ok: false }; /** SSO-only mode. */ @@ -335,9 +413,10 @@ export function oneStepSignInState(account: OneStepAccountReading): OneStepSignI if (!account.accountProviders.every((providerId) => providerId === 'credential')) return 'linked_provider'; if (!isOff(account.twoFactorEnabled)) return account.twoFactorEnabled === true ? 'second_factor' : 'unrecognised'; if (!isOff(account.phoneNumberVerified)) return account.phoneNumberVerified === true ? 'verified_phone' : 'unrecognised'; - if (!account.apiKeys.ok || !account.oauthConsents.ok) return 'grant_unreadable'; - if (account.apiKeys.held !== false) return 'api_key'; - if (account.oauthConsents.held !== false) return 'oauth_consent'; + const grants = STANDING_GRANTS.map((grant) => ({ ...grant, reading: account.standingGrants[grant.object] })); + if (grants.some(({ reading }) => reading?.ok !== true)) return 'grant_unreadable'; + const held = grants.find(({ reading }) => reading.ok && reading.held !== false); + if (held) return held.reason; if (!account.source.ok) return 'source_unreadable'; const source = account.source.value; if (!LOCAL_SOURCES.has(source)) { @@ -457,18 +536,19 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo if (existing) { const engine = host.getDataEngine() as UserSourceReader | undefined; const userId = String(existing.id); - const [apiKeys, oauthConsents, source] = await Promise.all([ - readStandingGrant(engine, 'sys_api_key', userId), - readStandingGrant(engine, 'sys_oauth_consent', userId), + const [source, grantReadings] = await Promise.all([ readUserSource(engine, userId), + Promise.all(STANDING_GRANT_OBJECTS.map((object) => readStandingGrant(engine, object, userId))), ]); + const standingGrants = Object.fromEntries( + STANDING_GRANT_OBJECTS.map((object, i) => [object, grantReadings[i]]), + ) as Record; const state = oneStepSignInState({ emailVerified: existing.emailVerified, accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId), twoFactorEnabled: existing.twoFactorEnabled, phoneNumberVerified: existing.phoneNumberVerified, - apiKeys, - oauthConsents, + standingGrants, source, ssoOnly: host.isSsoOnlyMode(), emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled, @@ -525,6 +605,8 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo await internal.linkAccount({ userId: user.id, providerId: 'credential', accountId: user.id, password: passwordHash }); } else { const userId = String(existing.id); + // The sessions are revoked before the password is written, which + // matches the vendor's order on its own password doors. await internal.deleteUserSessions(userId); if (await internal.findCredentialAccount(userId)) { await internal.updatePassword(userId, passwordHash); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 63b763b459c..2cb009a3258 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -18,11 +18,17 @@ import { createCopyInvitationLinkHandler } from './invitation-link-action'; import { ACCEPT_INVITATION_ONE_STEP_PATH, ONE_STEP_SIGN_IN_STATES, + STANDING_GRANTS, + STANDING_GRANT_OBJECTS, + USER_KEYED_STORES, invitationProofIdentifier, oneStepSignInState, type OneStepAccountReading, type OneStepSignInState, + type StandingGrantObject, + type StandingGrantReading, } from './invitation-mailbox-proof'; +import { authIdentityManifest } from './manifest'; import { BREACH_CHECK_VENDOR_DEFAULT_PATHS } from './auth-manager-plugin-list'; import { INTERACTIVE_REVOKE_REASON } from './session-tombstone'; @@ -467,8 +473,7 @@ const WRITTEN_TABLES = [ 'sys_member', 'sys_invitation', 'sys_verification', - 'sys_api_key', - 'sys_oauth_consent', + ...STANDING_GRANT_OBJECTS, ]; const writtenState = (engine: MemoryEngine) => JSON.stringify(WRITTEN_TABLES.map((table) => [table, engine.tables.get(table) ?? []])); @@ -681,6 +686,14 @@ describe('#34257 — the door sets a password only where the mailbox is the acco engine.find = find; }; }; + // Give the account a row in one standing-grant object; answers how to take it away. + const holdGrant = async (engine: MemoryEngine, object: StandingGrantObject, email: string, extra: Record = {}) => { + const id = `${object}_${email}`; + await engine.insert(object, { id, user_id: userRow(engine, email)!.id, ...extra }); + return () => { + engine.tables.set(object, (engine.tables.get(object) ?? []).filter((row) => row.id !== id)); + }; + }; const findThrowsForSource = (engine: MemoryEngine) => { const find = engine.find.bind(engine); engine.find = async (name: string, q: any = {}) => { @@ -730,23 +743,23 @@ describe('#34257 — the door sets a password only where the mailbox is the acco }; }, }, - // A standing grant counts as a claim, a revoked one included. - api_key: { - enter: async ({ engine }, email) => { - await engine.insert('sys_api_key', { id: `key_${email}`, user_id: userRow(engine, email)!.id, revoked: true }); - return () => { - engine.tables.set('sys_api_key', (engine.tables.get('sys_api_key') ?? []).filter((k) => k.id !== `key_${email}`)); - }; - }, - }, + // A standing grant counts as a claim, a revoked or expired one included. + api_key: { enter: async ({ engine }, email) => holdGrant(engine, 'sys_api_key', email, { revoked: true }) }, oauth_consent: { - enter: async ({ engine }, email) => { - await engine.insert('sys_oauth_consent', { id: `consent_${email}`, user_id: userRow(engine, email)!.id, client_id: 'client_34257', scopes: '["openid"]' }); - return () => { - engine.tables.set('sys_oauth_consent', (engine.tables.get('sys_oauth_consent') ?? []).filter((c) => c.id !== `consent_${email}`)); - }; - }, + enter: async ({ engine }, email) => holdGrant(engine, 'sys_oauth_consent', email, { client_id: 'client_34257', scopes: '["openid"]' }), + }, + oauth_token: { + enter: async ({ engine }, email) => holdGrant(engine, 'sys_oauth_refresh_token', email, { client_id: 'client_34257', revoked: new Date() }), + }, + oauth_client: { enter: async ({ engine }, email) => holdGrant(engine, 'sys_oauth_application', email, { client_id: 'client_34257' }) }, + device_code: { + enter: async ({ engine }, email) => holdGrant(engine, 'sys_device_code', email, { status: 'approved', expires_at: new Date(0) }), }, + sso_provider: { enter: async ({ engine }, email) => holdGrant(engine, 'sys_sso_provider', email, { provider_id: 'sso_34257' }) }, + scim_credential: { + enter: async ({ engine }, email) => holdGrant(engine, 'sys_scim_connection_credential', email, { revoked_at: new Date() }), + }, + idp_linked: { enter: async ({ engine }, email) => holdGrant(engine, 'sys_scim_user', email, { connection_user_key: 'scim-34257' }) }, grant_unreadable: { enter: async ({ engine }) => findThrowsFor(engine, 'sys_oauth_consent', new Error('store unavailable')), }, @@ -799,8 +812,10 @@ describe('#34257 — the door sets a password only where the mailbox is the acco accountProviders: ['credential'], twoFactorEnabled: false, phoneNumberVerified: undefined, - apiKeys: { ok: true, held: false }, - oauthConsents: { ok: true, held: false }, + standingGrants: Object.fromEntries(STANDING_GRANT_OBJECTS.map((object) => [object, { ok: true, held: false }])) as Record< + StandingGrantObject, + StandingGrantReading + >, source: { ok: true, value: 'env_native' }, ssoOnly: false, emailPasswordEnabled: true, @@ -820,10 +835,6 @@ describe('#34257 — the door sets a password only where the mailbox is the acco ['a second-factor flag stored in no form the judge reads', { twoFactorEnabled: 'true' }, 'unrecognised'], ['a verified phone number', { phoneNumberVerified: true }, 'verified_phone'], ['a phone flag stored in no form the judge reads', { phoneNumberVerified: 1 }, 'unrecognised'], - ['an API key', { apiKeys: { ok: true, held: true } }, 'api_key'], - ['an OAuth client consent', { oauthConsents: { ok: true, held: true } }, 'oauth_consent'], - ['API keys that cannot be read', { apiKeys: { ok: false } }, 'grant_unreadable'], - ['OAuth client consents that cannot be read', { oauthConsents: { ok: false } }, 'grant_unreadable'], ['an identity-provider source', { source: { ok: true, value: 'idp_provisioned' } }, 'idp_provisioned'], ['a pending single sign-on', { source: { ok: true, value: 'idp_pending' } }, 'pending_sso'], ['an unreadable source', { source: { ok: false } }, 'source_unreadable'], @@ -835,18 +846,79 @@ describe('#34257 — the door sets a password only where the mailbox is the acco expect(oneStepSignInState({ ...ALLOWED, ...change })).toBe(reason); }); + const withGrant = (object: StandingGrantObject, reading: StandingGrantReading | undefined): Partial => ({ + standingGrants: { ...ALLOWED.standingGrants, [object]: reading } as Record, + }); + + it.each(STANDING_GRANTS.map(({ object, reason }) => [object, reason] as const))( + 'the judge answers sign_in for a row of %s, as %s, and as grant_unreadable when it cannot be read or was not read', + (object, reason) => { + expect(oneStepSignInState({ ...ALLOWED, ...withGrant(object, { ok: true, held: true }) })).toBe(reason); + expect(oneStepSignInState({ ...ALLOWED, ...withGrant(object, { ok: false }) })).toBe('grant_unreadable'); + expect(oneStepSignInState({ ...ALLOWED, ...withGrant(object, undefined) })).toBe('grant_unreadable'); + }, + ); + + it('every user-keyed store the plugin mounts is classified, as a claim the judge reads or as no claim', () => { + // Derived from the manifest the plugin registers: every column that + // references sys_user or is named user_id, on its objects and on the + // fields it adds to them. + const manifest = authIdentityManifest(); + const userKeyed = (fields: Record) => + Object.entries(fields ?? {}) + .filter(([name, field]) => field?.reference === 'sys_user' || name === 'user_id') + .map(([name]) => name); + const mounted = [ + ...manifest.objects.flatMap((object: any) => userKeyed(object.fields).map((column) => `${object.name}.${column}`)), + ...manifest.objectExtensions.flatMap((extension: any) => userKeyed(extension.fields).map((column) => `${extension.extend}.${column}`)), + ]; + expect([...new Set(mounted)].sort()).toEqual(Object.keys(USER_KEYED_STORES).sort()); + // Each claim store is read by an indexed lookup on its user column. + for (const object of STANDING_GRANT_OBJECTS) { + const declared = manifest.objects.find((o: any) => o.name === object); + expect(declared?.fields?.user_id, object).toBeDefined(); + expect((declared?.indexes ?? []).some((index: any) => index.fields?.[0] === 'user_id'), `${object} has no index led by user_id`).toBe(true); + } + }); + + // One boot for every store: each store has its own invitation, account and + // client address, so no window counts another's requests. + let shared: Promise>> | undefined; + it.each(STANDING_GRANT_OBJECTS.map((object, i) => [object, i] as const))( + 'an unverified account holding a row of %s signs in as today, and is accepted once the row is gone', + async (object, i) => { + shared ??= boot(); + const { engine, manager, invite } = await shared; + const email = `grant-${object.replace(/_/g, '-')}@example.com`; + const address = `198.51.100.${i + 1}`; + const { invitation, proof } = await invite(email); + await signUp(manager, engine, email); + const leave = await holdGrant(engine, object, email); + const before = writtenState(engine); + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'G', password: NEW_PASSWORD }, undefined, address)); + expect(writtenState(engine)).toBe(before); + + leave(); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'G', password: NEW_PASSWORD }, undefined, address)); + }, + ); + it('a grant table that does not exist holds no grant: the account is accepted', async () => { const booted = await boot(); const { engine, manager, invite } = booted; const email = 'grants-absent@example.com'; const { invitation, proof } = await invite(email); await signUp(manager, engine, email); - const leaveKeys = findThrowsFor(engine, 'sys_api_key', new Error('SQLITE_ERROR: no such table: sys_api_key')); - findThrowsFor(engine, 'sys_oauth_consent', new Error('SQLITE_ERROR: no such table: sys_oauth_consent')); + const find = engine.find.bind(engine); + engine.find = async (name: string, q: any = {}) => { + if ((STANDING_GRANT_OBJECTS as readonly string[]).includes(name)) throw new Error(`SQLITE_ERROR: no such table: ${name}`); + return find(name, q); + }; try { await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'G', password: NEW_PASSWORD })); } finally { - leaveKeys(); + engine.find = find; } }); @@ -912,6 +984,26 @@ describe('#34257 — a password the door sets starts the password-age clock and expect(JSON.parse(credential()!.previous_password_hashes)).toEqual([replacedHash]); }); + it('the sessions are revoked before the password is written, which matches the vendor\'s order', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('ordered@example.com'); + await signUp(manager, engine, 'ordered@example.com'); + const writes: string[] = []; + for (const op of ['insert', 'update', 'delete'] as const) { + const original = (engine as any)[op].bind(engine); + (engine as any)[op] = async (name: string, ...rest: unknown[]) => { + writes.push(name); + return original(name, ...rest); + }; + } + + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'O', password: NEW_PASSWORD })); + const sessionsRevoked = writes.indexOf('sys_session'); + const passwordWritten = writes.indexOf('sys_account'); + expect(sessionsRevoked, writes.join(' ')).toBeGreaterThanOrEqual(0); + expect(passwordWritten, writes.join(' ')).toBeGreaterThan(sessionsRevoked); + }); + it('the sessions the door ends are ledgered with the reason a password reset records', () => { expect(INTERACTIVE_REVOKE_REASON[ACCEPT_INVITATION_ONE_STEP_PATH]).toBe('password_reset'); }); From 3c499592c60a19fb23f1668e1da4de6cbcbe2b1d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 20:10:39 +0000 Subject: [PATCH 22/26] test(auth): pin the one-step door's claim stores by name The judge and door cases iterate a written-out list of the claim stores, and a pin holds the module's standing grants equal to it, so a store moved out of the claims turns its own cases red. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- ...vitation-one-step-acceptance-34257.test.ts | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 2cb009a3258..1fbc262ddb6 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -846,11 +846,35 @@ describe('#34257 — the door sets a password only where the mailbox is the acco expect(oneStepSignInState({ ...ALLOWED, ...change })).toBe(reason); }); + // The claim stores, written out: each standing-grant object and the reason + // its row answers. The module derives what it reads from its classification + // table; this list pins that table's claims, so a store moved out of the + // claims turns its cases below red. + const CLAIM_STORES: ReadonlyArray = [ + ['sys_api_key', 'api_key'], + ['sys_oauth_consent', 'oauth_consent'], + ['sys_oauth_access_token', 'oauth_token'], + ['sys_oauth_refresh_token', 'oauth_token'], + ['sys_oauth_application', 'oauth_client'], + ['sys_device_code', 'device_code'], + ['sys_two_factor', 'second_factor'], + ['sys_sso_provider', 'sso_provider'], + ['sys_scim_connection_credential', 'scim_credential'], + ['sys_scim_user', 'idp_linked'], + ['sys_scim_subject', 'idp_linked'], + ['sys_scim_projection_grant', 'idp_linked'], + ['sys_scim_identity_tombstone', 'idp_linked'], + ]; + + it('the standing grants the door reads are the claim stores', () => { + expect(STANDING_GRANTS.map(({ object, reason }) => [object, reason])).toEqual(CLAIM_STORES.map(([o, r]) => [o, r])); + }); + const withGrant = (object: StandingGrantObject, reading: StandingGrantReading | undefined): Partial => ({ standingGrants: { ...ALLOWED.standingGrants, [object]: reading } as Record, }); - it.each(STANDING_GRANTS.map(({ object, reason }) => [object, reason] as const))( + it.each(CLAIM_STORES)( 'the judge answers sign_in for a row of %s, as %s, and as grant_unreadable when it cannot be read or was not read', (object, reason) => { expect(oneStepSignInState({ ...ALLOWED, ...withGrant(object, { ok: true, held: true }) })).toBe(reason); @@ -884,7 +908,7 @@ describe('#34257 — the door sets a password only where the mailbox is the acco // One boot for every store: each store has its own invitation, account and // client address, so no window counts another's requests. let shared: Promise>> | undefined; - it.each(STANDING_GRANT_OBJECTS.map((object, i) => [object, i] as const))( + it.each(CLAIM_STORES.map(([object], i) => [object, i] as const))( 'an unverified account holding a row of %s signs in as today, and is accepted once the row is gone', async (object, i) => { shared ??= boot(); From bdc48121bc290d76e6ef454f15e3dce4a5d1fa68 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:51:57 +0000 Subject: [PATCH 23/26] fix(auth): the one-step door reads a sign-in identity on the user row as a claim The judge reads the presence of a sign-in phone number on the stored user row, verified or not, as a claim (phone_number); a row it cannot read answers identity_unreadable. Every column of the vendor's user model with every plugin this plugin can mount is classified, and a test holds that classification to the composed instance. The user-keyed store pin also finds a column whose name ends in user_id. The rule text in the module doc, the ADR-0138 note and the changeset states the list and the classification. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../34257-one-step-invitation-acceptance.md | 2 +- ...principal-doors-grants-and-organization.md | 41 ++--- .../src/invitation-mailbox-proof.ts | 140 +++++++++++++++--- ...vitation-one-step-acceptance-34257.test.ts | 132 ++++++++++++++++- 4 files changed, 269 insertions(+), 46 deletions(-) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index 4365a82a04d..e4133942a12 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -15,7 +15,7 @@ Metadata-protocol: none - **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row. - **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records, in an order that matches the vendor's order), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. -- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor, enabled or enrolled, no verified phone number and no standing grant (an API key, an OAuth client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an identity provider's directory, revoked or expired ones included), its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent. Every store the plugin mounts that is keyed by a user is classified as a claim the judge reads or as no claim, and a test holds that classification to the mounted list. +- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads all of these: the address is not verified; the account's only sign-in account is its email and password one, or it has none; it has no second factor, enabled or enrolled; its user row holds no phone number, verified or not; it holds no standing grant (an API key, an OAuth client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an identity provider's directory, revoked or expired ones included); its identity source is local; and the server allows a local password here (not SSO-only, email and password on). Every other account answers `sign_in`, including one in a state no rule names and one whose reading fails, and the proof stays unspent. Every store this plugin mounts that is keyed by a user, and every column of the vendor's user model with every plugin this plugin can mount, is classified as a claim the judge reads or as no claim, and a test holds each classification to what is mounted. The classification covers what this plugin mounts and nothing another package mounts. - **`sys_device_code` gains an index on `user_id`** (`@objectstack/platform-objects`), so the door reads a user's device authorizations by an indexed lookup, as it reads every other standing grant. - **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index dd655f0e4bc..44281352f38 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -302,26 +302,27 @@ invitation-link sign-up still owes the verification mail. **Amended 2026-11-16 — the one-step invitation acceptance and the OAuth client-name read, class-2-shaped doors.** Card [#34257](https://github.com/objectstack-ai/objectstack/issues/34257) admits one more door of class 2's shape, not a -seventh class: `POST /api/v1/auth/organization/accept-invitation-one-step`. What admits the request: the mailbox -proof the invitation mail carries, a capability token minted per send. The invitation id alone, which the copied link -and the invitation row carry, admits nothing. What it runs as: after validation, the creation of the invited -address's account (or the replacement of the password of an unverified account whose mailbox is its one claim, -revoking its sessions), the address marked verified, the invitation accepted through the vendor's own accept route, -and a session for that account. The proof is never at rest in clear, the stored mail row never holds it, and it is -bound to the invitation, its address and its expiry; a resend retires the old one. It is spent only by a request that -passed every gate, and one server process serializes concurrent redemptions of it; across processes, single use is -as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check -failed. The door sets a password on an existing account only when it reads that the mailbox is the account's one -claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, -it has no second factor, enabled or enrolled, no verified phone number and no standing grant (an API key, an OAuth -client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM -credential or a link to an identity provider's directory, revoked or expired ones included), its identity source is -local, and the server allows a local password here (not SSO-only, email and password on). Every other account, -including one in a state no rule names, answers `sign_in`, and the proof stays unspent. Every store the plugin mounts -that is keyed by a user is classified as a claim the judge reads or as no claim, and a test holds that classification -to the mounted list. A cloud-managed environment -sets no local password, so there the door refuses every request that carries a proof. It carries a rate limit per -client network address and per invitation, as ADR-0121 D6 requires. Enforced by +seventh class: `POST /api/v1/auth/organization/accept-invitation-one-step`. What admits the request: the mailbox proof +the invitation mail carries, a capability token minted per send. The invitation id alone, which the copied link and +the invitation row carry, admits nothing. What it runs as: after validation, the creation of the invited address's +account (or the replacement of the password of an unverified account the rule below admits, revoking its sessions), +the address marked verified, the invitation accepted through the vendor's own accept route, and a session for that +account. The proof is never at rest in clear, the stored mail row never holds it, and it is bound to the invitation, +its address and its expiry; a resend retires the old one. It is spent only by a request that passed every gate, and +one server process serializes concurrent redemptions of it; across processes, single use is as strong as the store's +consume. Every proof that does not admit gets one refusal that does not say which check failed. The door sets a +password on an existing account only when it reads all of these: the address is not verified; the account's only +sign-in account is its email and password one, or it has none; it has no second factor, enabled or enrolled; its user +row holds no phone number, verified or not; it holds no standing grant (an API key, an OAuth client consent, an OAuth +access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an +identity provider's directory, revoked or expired ones included); its identity source is local; and the server allows +a local password here (not SSO-only, email and password on). Every other account answers `sign_in`, including one in a +state no rule names and one whose reading fails, and the proof stays unspent. Every store this plugin mounts that is +keyed by a user, and every column of the vendor's user model with every plugin this plugin can mount, is classified as +a claim the judge reads or as no claim, and a test holds each classification to what is mounted. The classification +covers what this plugin mounts and nothing another package mounts. A cloud-managed environment sets no local password, +so there the door refuses every request that carries a proof. It carries a rate limit per client network address and +per invitation, as ADR-0121 D6 requires. Enforced by `packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in `packages/plugins/plugin-auth/src/auth-route-ledger.ts`. It is a better-auth endpoint, so it rides the `/auth` catch-all, which no route table lists door by door: the anonymous sweep's classification names it under class 2 as a diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 63530132c7c..5df10a624f6 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -57,23 +57,26 @@ * * ## Which existing account the door sets a password on * - * The door sets a password on an existing account only when it reads that the - * mailbox is the account's one claim: the address is not verified, the - * account's only sign-in account is its email and password one or it has - * none, it has no second factor, enabled or enrolled, no verified phone - * number and no standing grant (an API key, an OAuth client consent, an OAuth + * The door sets a password on an existing account only when it reads all of + * these: the address is not verified; the account's only sign-in account is + * its email and password one, or it has none; it has no second factor, + * enabled or enrolled; its user row holds no phone number, verified or not; + * it holds no standing grant (an API key, an OAuth client consent, an OAuth * access or refresh token, an OAuth client, a device authorization, an SSO * provider, a SCIM credential or a link to an identity provider's directory, - * revoked or expired ones included), its identity source is local, and the + * revoked or expired ones included); its identity source is local; and the * server allows a local password here (not SSO-only, email and password on). - * Every other account, including one in a state no rule names, answers - * `sign_in`, and the proof stays unspent. Every store the plugin mounts that - * is keyed by a user is classified as a claim the judge reads or as no claim, - * and a test holds that classification to the mounted list. + * Every other account answers `sign_in`, including one in a state no rule + * names and one whose reading fails, and the proof stays unspent. Every store + * this plugin mounts that is keyed by a user, and every column of the + * vendor's user model with every plugin this plugin can mount, is classified + * as a claim the judge reads or as no claim, and a test holds each + * classification to what is mounted. The classification covers what this + * plugin mounts and nothing another package mounts. * * The judge, {@link oneStepSignInState}, is an allow-list: it lets the * password be set only when every value it reads is positively the one that - * carries no other claim, and a value no rule names answers `sign_in` as + * carries no claim it reads, and a value no rule names answers `sign_in` as * `unrecognised`. Its reasons are {@link ONE_STEP_SIGN_IN_STATES}; the card's * test pins one case per reason. * @@ -84,6 +87,12 @@ * plugin's `passkeys` flag is not wired today; if it is ever wired, a passkey * is a claim the judge must read. * + * A sign-in identity on the user row counts as a claim whether or not it is + * verified ({@link USER_ROW_COLUMNS}, {@link readUserRowSignIn}): its presence + * answers `sign_in`. It is read from the stored row, so a value written while + * its sign-in plugin is not mounted counts too; a read that fails answers + * `sign_in` as `identity_unreadable`. + * * An account that passes gets the typed password in place of its own, and * every one of its sessions is revoked with the reason a password reset * records (`session-tombstone.ts`); the two writes match the vendor's order. The password history is consulted before @@ -237,9 +246,9 @@ export interface InvitationProofDoorHost { * Why an existing account answers `sign_in`. The judge * ({@link oneStepSignInState}) is an allow-list: these name the reasons it * reports, and `unrecognised` is every value it does not positively read as - * carrying no other claim. Each named state is either a claim on the account - * the mailbox proof does not outrank, or a server that sets no local password - * here. + * carrying no claim. Each named state is either a claim on the account the + * mailbox proof does not outrank, a reading that failed, or a server that sets + * no local password here. */ export const ONE_STEP_SIGN_IN_STATES = [ /** The address is already verified: its holder signs in. */ @@ -250,6 +259,10 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'second_factor', /** The account has a verified phone number. */ 'verified_phone', + /** The account's user row holds a sign-in phone number, verified or not. */ + 'phone_number', + /** The account's user row cannot be read for its sign-in identities. */ + 'identity_unreadable', /** The account holds an API key, revoked or not. */ 'api_key', /** The account holds an OAuth client consent, revoked or not. */ @@ -278,7 +291,7 @@ export const ONE_STEP_SIGN_IN_STATES = [ 'sso_only', /** Email and password sign-in is off. */ 'email_password_off', - /** A stored value the judge does not read as carrying no other claim, such as an identity source no rule names. */ + /** A stored value the judge does not read as carrying no claim, such as an identity source no rule names. */ 'unrecognised', ] as const; @@ -295,9 +308,12 @@ function isOff(value: unknown): boolean { /** * Every store the plugin mounts that is keyed by a user: each column of an * object in `authIdentityManifest` (`manifest.ts`) that references `sys_user` - * or is named `user_id`, classified. A test derives that set from the - * manifest and holds it equal to this table's keys, so a store mounted later - * fails it until it is classified here. + * or whose name ends in `user_id`, classified. A test derives that set from + * the manifest and holds it equal to this table's keys, so a store mounted + * later fails it until it is classified here. The test finds a user column by + * that reference or that name only: a store that held a user's id in a plain + * column under another name would pass it unclassified. It covers the + * manifest this plugin registers, and no store another package mounts. * * - `{ grant }`: a standing grant, a claim. The door reads it by * {@link readStandingGrant}, and any row answers `sign_in` as `grant`. @@ -333,6 +349,15 @@ export const USER_KEYED_STORES = { 'sys_user.accountable_user_id': { notAClaim: 'Names the account as accountable for another user and signs no one in as this account.' }, 'sys_user_preference.user_id': { notAClaim: 'The account\'s own settings, which grant no access.' }, 'sys_personal_view.user_id': { notAClaim: 'The account\'s own saved list views, which grant no access.' }, + 'sys_scim_group_member.scim_user_id': { + notAClaim: 'Names a SCIM directory user, not an account; the account\'s own link is `sys_scim_user.user_id`, a claim.', + }, + 'sys_scim_projection_grant.scim_user_id': { + notAClaim: 'Names a SCIM directory user, not an account; the same row\'s `user_id` is the claim.', + }, + 'sys_scim_connection_binding.decommission_cursor_user_id': { + notAClaim: 'A resumable cursor of a directory connection\'s decommission pass, which grants the account nothing.', + }, } as const satisfies Record< string, { grant: OneStepSignInState } | { accounts: OneStepSignInState } | { notAClaim: string } @@ -382,6 +407,73 @@ export async function readStandingGrant( } } +/** + * Every column of the vendor's user model (`sys_user`), its core model and + * every column the plugins this plugin can mount add to it, classified. A + * test composes the auth manager with every plugin flag on, derives the user + * model's columns from it, and holds that set equal to this table's keys, so + * a column a plugin adds later fails it until it is classified here. + * + * - `{ signIn }`: a sign-in identity, a claim whether or not it is verified. + * The door reads it from the stored row ({@link readUserRowSignIn}), and its + * presence answers `sign_in` as `signIn`. + * - `{ judged }`: a value the judge reads off the user the vendor loads, and + * the reason it answers. + * - `{ proven }`: the invited address, which the proof proves. + * - `{ notASignIn }`: why the column signs no one in as the account. + */ +export const USER_ROW_COLUMNS = { + email: { proven: 'The invited address: the proof is what proves the mailbox.' }, + email_verified: { judged: 'verified' }, + phone_number: { signIn: 'phone_number' }, + phone_number_verified: { judged: 'verified_phone' }, + two_factor_enabled: { judged: 'second_factor' }, + name: { notASignIn: 'A display name, which signs no one in.' }, + image: { notASignIn: 'A picture, which signs no one in.' }, + created_at: { notASignIn: 'A timestamp.' }, + updated_at: { notASignIn: 'A timestamp.' }, + role: { notASignIn: 'A platform role authorizes a signed-in session and signs no one in.' }, + banned: { notASignIn: 'A ban refuses sign-in and signs no one in.' }, + ban_reason: { notASignIn: 'The reason of a ban, which signs no one in.' }, + ban_expires: { notASignIn: 'The end of a ban, which signs no one in.' }, +} as const satisfies Record< + string, + { signIn: OneStepSignInState } | { judged: OneStepSignInState } | { proven: string } | { notASignIn: string } +>; + +type UserRowColumn = keyof typeof USER_ROW_COLUMNS; +/** A sign-in identity column of the user row. */ +export type UserRowSignInColumn = { + [K in UserRowColumn]: (typeof USER_ROW_COLUMNS)[K] extends { signIn: OneStepSignInState } ? K : never; +}[UserRowColumn]; + +/** The sign-in identities of the user row, in the order the judge reports them: each column and its reason. */ +export const USER_ROW_SIGN_IN: ReadonlyArray<{ column: UserRowSignInColumn; reason: OneStepSignInState }> = Object.entries( + USER_ROW_COLUMNS, +).flatMap(([column, cls]) => ('signIn' in cls ? [{ column: column as UserRowSignInColumn, reason: cls.signIn }] : [])); + +/** The user row's sign-in identity columns, as stored; `ok: false` when the row cannot be read. */ +export type UserRowSignInReading = + | { ok: true; values: Readonly>> } + | { ok: false }; + +/** + * The sign-in identity columns of `userId`'s stored row. One read by `id` as + * the system. No read surface, a failed read, or no row is `ok: false`. + */ +export async function readUserRowSignIn(engine: UserSourceReader | undefined, userId: string): Promise { + if (!engine?.find) return { ok: false }; + try { + const columns = USER_ROW_SIGN_IN.map(({ column }) => column); + const rows = await engine.find('sys_user', { where: { id: userId }, fields: ['id', ...columns], limit: 1 }, SYSTEM_READ); + if (!Array.isArray(rows) || rows.length !== 1) return { ok: false }; + const row = rows[0] as Record; + return { ok: true, values: Object.fromEntries(columns.map((column) => [column, row[column]])) }; + } catch { + return { ok: false }; + } +} + /** What the judge reads of an existing account and the server. */ export interface OneStepAccountReading { /** `user.emailVerified`, as stored. */ @@ -392,6 +484,8 @@ export interface OneStepAccountReading { twoFactorEnabled: unknown; /** `user.phoneNumberVerified`, as stored (absent without the plugin). */ phoneNumberVerified: unknown; + /** The sign-in identity columns of the stored user row ({@link readUserRowSignIn}). */ + userRowSignIn: UserRowSignInReading; /** Any row of the user in each standing-grant object ({@link readStandingGrant}). */ standingGrants: Readonly>; /** `sys_user.source`, or `ok: false` when it cannot be read. */ @@ -413,6 +507,12 @@ export function oneStepSignInState(account: OneStepAccountReading): OneStepSignI if (!account.accountProviders.every((providerId) => providerId === 'credential')) return 'linked_provider'; if (!isOff(account.twoFactorEnabled)) return account.twoFactorEnabled === true ? 'second_factor' : 'unrecognised'; if (!isOff(account.phoneNumberVerified)) return account.phoneNumberVerified === true ? 'verified_phone' : 'unrecognised'; + if (account.userRowSignIn?.ok !== true) return 'identity_unreadable'; + for (const { column, reason } of USER_ROW_SIGN_IN) { + const value = account.userRowSignIn.values[column]; + if (value === null || value === undefined) continue; + return typeof value === 'string' && value.trim().length > 0 ? reason : 'unrecognised'; + } const grants = STANDING_GRANTS.map((grant) => ({ ...grant, reading: account.standingGrants[grant.object] })); if (grants.some(({ reading }) => reading?.ok !== true)) return 'grant_unreadable'; const held = grants.find(({ reading }) => reading.ok && reading.held !== false); @@ -536,8 +636,9 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo if (existing) { const engine = host.getDataEngine() as UserSourceReader | undefined; const userId = String(existing.id); - const [source, grantReadings] = await Promise.all([ + const [source, userRowSignIn, grantReadings] = await Promise.all([ readUserSource(engine, userId), + readUserRowSignIn(engine, userId), Promise.all(STANDING_GRANT_OBJECTS.map((object) => readStandingGrant(engine, object, userId))), ]); const standingGrants = Object.fromEntries( @@ -548,6 +649,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId), twoFactorEnabled: existing.twoFactorEnabled, phoneNumberVerified: existing.phoneNumberVerified, + userRowSignIn, standingGrants, source, ssoOnly: host.isSsoOnlyMode(), diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 1fbc262ddb6..bfec3d59c36 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -9,6 +9,7 @@ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; +import { getAuthTables } from 'better-auth/db'; import { resetCloudManagedForTesting } from '@objectstack/core'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql'; @@ -21,6 +22,8 @@ import { STANDING_GRANTS, STANDING_GRANT_OBJECTS, USER_KEYED_STORES, + USER_ROW_COLUMNS, + USER_ROW_SIGN_IN, invitationProofIdentifier, oneStepSignInState, type OneStepAccountReading, @@ -667,7 +670,7 @@ describe('#34257 — every gate refuses before anything is written, and the proo }); }); -describe('#34257 — the door sets a password only where the mailbox is the account\'s one claim', () => { +describe('#34257 — the door sets a password on an existing account only where it reads no claim', () => { quietConsole(); type Booted = Awaited>; @@ -694,6 +697,16 @@ describe('#34257 — the door sets a password only where the mailbox is the acco engine.tables.set(object, (engine.tables.get(object) ?? []).filter((row) => row.id !== id)); }; }; + const findThrowsForUserRowSignIn = (engine: MemoryEngine) => { + const find = engine.find.bind(engine); + engine.find = async (name: string, q: any = {}) => { + if (name === 'sys_user' && Array.isArray(q.fields) && q.fields.includes('phone_number')) throw new Error('store unavailable'); + return find(name, q); + }; + return () => { + engine.find = find; + }; + }; const findThrowsForSource = (engine: MemoryEngine) => { const find = engine.find.bind(engine); engine.find = async (name: string, q: any = {}) => { @@ -739,10 +752,25 @@ describe('#34257 — the door sets a password only where the mailbox is the acco userRow(engine, email)!.phone_number = '+15550134257'; userRow(engine, email)!.phone_number_verified = true; return () => { + userRow(engine, email)!.phone_number = null; userRow(engine, email)!.phone_number_verified = false; }; }, }, + // A sign-in phone number on the user row, not verified, with phone + // sign-in not mounted: read from the stored row all the same. + phone_number: { + enter: async ({ engine }, email) => { + userRow(engine, email)!.phone_number = '+15550134258'; + userRow(engine, email)!.phone_number_verified = false; + return () => { + userRow(engine, email)!.phone_number = null; + }; + }, + }, + identity_unreadable: { + enter: async ({ engine }) => findThrowsForUserRowSignIn(engine), + }, // A standing grant counts as a claim, a revoked or expired one included. api_key: { enter: async ({ engine }, email) => holdGrant(engine, 'sys_api_key', email, { revoked: true }) }, oauth_consent: { @@ -812,6 +840,7 @@ describe('#34257 — the door sets a password only where the mailbox is the acco accountProviders: ['credential'], twoFactorEnabled: false, phoneNumberVerified: undefined, + userRowSignIn: { ok: true, values: { phone_number: null } }, standingGrants: Object.fromEntries(STANDING_GRANT_OBJECTS.map((object) => [object, { ok: true, held: false }])) as Record< StandingGrantObject, StandingGrantReading @@ -821,9 +850,17 @@ describe('#34257 — the door sets a password only where the mailbox is the acco emailPasswordEnabled: true, }; - it('the judge lets the password be set only on the reading that carries no other claim', () => { + it('the judge lets the password be set only on the reading that carries no claim', () => { expect(oneStepSignInState(ALLOWED)).toBeUndefined(); - expect(oneStepSignInState({ ...ALLOWED, accountProviders: [], source: { ok: true, value: null }, twoFactorEnabled: null })).toBeUndefined(); + expect( + oneStepSignInState({ + ...ALLOWED, + accountProviders: [], + source: { ok: true, value: null }, + twoFactorEnabled: null, + userRowSignIn: { ok: true, values: {} }, + }), + ).toBeUndefined(); }); it.each<[string, Partial, OneStepSignInState]>([ @@ -835,6 +872,12 @@ describe('#34257 — the door sets a password only where the mailbox is the acco ['a second-factor flag stored in no form the judge reads', { twoFactorEnabled: 'true' }, 'unrecognised'], ['a verified phone number', { phoneNumberVerified: true }, 'verified_phone'], ['a phone flag stored in no form the judge reads', { phoneNumberVerified: 1 }, 'unrecognised'], + ['a phone number on the user row, not verified', { userRowSignIn: { ok: true, values: { phone_number: '+15550134257' } } }, 'phone_number'], + ['a phone number on the user row, verified flag unread', { phoneNumberVerified: undefined, userRowSignIn: { ok: true, values: { phone_number: '+1 555 013' } } }, 'phone_number'], + ['a phone number stored in no form the judge reads', { userRowSignIn: { ok: true, values: { phone_number: 15550134257 } } }, 'unrecognised'], + ['an empty phone number', { userRowSignIn: { ok: true, values: { phone_number: ' ' } } }, 'unrecognised'], + ['a user row that cannot be read', { userRowSignIn: { ok: false } }, 'identity_unreadable'], + ['a user row reading that is missing', { userRowSignIn: undefined as never }, 'identity_unreadable'], ['an identity-provider source', { source: { ok: true, value: 'idp_provisioned' } }, 'idp_provisioned'], ['a pending single sign-on', { source: { ok: true, value: 'idp_pending' } }, 'pending_sso'], ['an unreadable source', { source: { ok: false } }, 'source_unreadable'], @@ -885,12 +928,15 @@ describe('#34257 — the door sets a password only where the mailbox is the acco it('every user-keyed store the plugin mounts is classified, as a claim the judge reads or as no claim', () => { // Derived from the manifest the plugin registers: every column that - // references sys_user or is named user_id, on its objects and on the - // fields it adds to them. + // references sys_user or whose name ends in user_id, on its objects and on + // the fields it adds to them. It finds a user column by that reference or + // that name only, so a store holding a user's id in a plain column under + // another name would pass it unclassified; and it reads this plugin's + // manifest only, so a store another package mounts is outside it. const manifest = authIdentityManifest(); const userKeyed = (fields: Record) => Object.entries(fields ?? {}) - .filter(([name, field]) => field?.reference === 'sys_user' || name === 'user_id') + .filter(([name, field]) => field?.reference === 'sys_user' || name.endsWith('user_id')) .map(([name]) => name); const mounted = [ ...manifest.objects.flatMap((object: any) => userKeyed(object.fields).map((column) => `${object.name}.${column}`)), @@ -905,6 +951,80 @@ describe('#34257 — the door sets a password only where the mailbox is the acco } }); + // Every plugin flag the plugin list reads, on, plus the two mounts gated by + // configuration rather than a flag: generic OAuth providers and the + // one-time token's app scheme. + const EVERY_PLUGIN_ON = { + plugins: { + organization: true, + twoFactor: true, + passwordRejectBreached: true, + passkeys: true, + magicLink: true, + oidcProvider: true, + deviceAuthorization: true, + admin: true, + phoneNumber: true, + sso: true, + ssoDomainVerification: true, + scim: true, + }, + oidcProviders: [{ providerId: 'idp34257', clientId: 'client34257', clientSecret: 'secret34257', discoveryUrl: 'https://idp.example.com/.well-known/openid-configuration' }], + trustedAppSchemes: ['com.example.app34257'], + }; + + it('every column of the vendor user model with every plugin mounted is classified, and the judge reads each sign-in identity', async () => { + // The flags the plugin list reads: each one is on in EVERY_PLUGIN_ON, so + // a flag added later reds here until it is. + const listSource = readFileSync(new URL('./auth-manager-plugin-list.ts', import.meta.url), 'utf8'); + const enabledBlock = /const enabled = \{([\s\S]*?)\n \};/.exec(listSource)?.[1] ?? ''; + const flags = [...enabledBlock.matchAll(/^\s{4}([A-Za-z]+):/gm)].map(([, flag]) => flag); + expect(flags.length, 'the scan of the plugin list found no flag').toBeGreaterThan(5); + expect(flags.filter((flag) => (EVERY_PLUGIN_ON.plugins as Record)[flag] !== true)).toEqual([]); + + // The composed instance: what the plugin list mounts with all of them on. + const engine = createMemoryEngine(); + const manager = new AuthManager({ secret: SECRET, baseUrl: BASE, dataEngine: engine as any, ...EVERY_PLUGIN_ON } as any); + const auth: any = await manager.getAuthInstance(); + const ids = (auth.options.plugins ?? []).map((plugin: any) => plugin.id); + for (const id of ['two-factor', 'admin', 'phone-number', 'magic-link', 'generic-oauth', 'oauth-provider', 'sso', 'scim', 'device-authorization', 'one-time-token']) { + expect(ids, id).toContain(id); + } + const userFields = (getAuthTables(auth.options) as any).user.fields as Record; + const columns = Object.entries(userFields).map(([key, field]) => field.fieldName ?? key); + expect([...new Set(columns)].sort()).toEqual(Object.keys(USER_ROW_COLUMNS).sort()); + + // The classification, written out: the sign-in identities the door reads + // off the stored row, and the values the judge reads off the vendor's user. + expect(USER_ROW_SIGN_IN.map(({ column, reason }) => [column, reason])).toEqual([['phone_number', 'phone_number']]); + expect( + Object.entries(USER_ROW_COLUMNS) + .filter(([, cls]) => 'judged' in cls) + .map(([column, cls]) => [column, (cls as { judged: string }).judged]) + .sort(), + ).toEqual([ + ['email_verified', 'verified'], + ['phone_number_verified', 'verified_phone'], + ['two_factor_enabled', 'second_factor'], + ]); + }); + + it('a phone number on the user row answers sign_in with phone sign-in mounted, and is accepted once it is cleared', async () => { + const { engine, manager, invite } = await boot({ plugins: { phoneNumber: true } }); + const email = 'phone-mounted@example.com'; + const { invitation, proof } = await invite(email); + await signUp(manager, engine, email); + userRow(engine, email)!.phone_number = '+15550134259'; + userRow(engine, email)!.phone_number_verified = false; + const before = writtenState(engine); + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'P', password: NEW_PASSWORD })); + expect(writtenState(engine)).toBe(before); + + userRow(engine, email)!.phone_number = null; + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'P', password: NEW_PASSWORD })); + }); + // One boot for every store: each store has its own invitation, account and // client address, so no window counts another's requests. let shared: Promise>> | undefined; From 7774f4a976d26305c19d2c62c3f31acb50d355f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:52:18 +0000 Subject: [PATCH 24/26] test(auth): pin the user row reading of the one-step door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../invitation-one-step-acceptance-34257.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index bfec3d59c36..b34ab0f9db3 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -26,6 +26,7 @@ import { USER_ROW_SIGN_IN, invitationProofIdentifier, oneStepSignInState, + readUserRowSignIn, type OneStepAccountReading, type OneStepSignInState, type StandingGrantObject, @@ -1009,6 +1010,19 @@ describe('#34257 — the door sets a password on an existing account only where ]); }); + it('the user row reading is ok only for the one stored row; no read surface, a failed read or no row is not', async () => { + const engine = createMemoryEngine(); + await engine.insert('sys_user', { id: 'u_row', email: 'row@example.com', phone_number: '+15550134260' }); + await engine.insert('sys_user', { id: 'u_bare', email: 'bare@example.com' }); + expect(await readUserRowSignIn(engine, 'u_row')).toEqual({ ok: true, values: { phone_number: '+15550134260' } }); + expect(await readUserRowSignIn(engine, 'u_bare')).toEqual({ ok: true, values: { phone_number: undefined } }); + expect(await readUserRowSignIn(engine, 'u_missing')).toEqual({ ok: false }); + expect(await readUserRowSignIn(undefined, 'u_row')).toEqual({ ok: false }); + const leave = findThrowsForUserRowSignIn(engine); + expect(await readUserRowSignIn(engine, 'u_row')).toEqual({ ok: false }); + leave(); + }); + it('a phone number on the user row answers sign_in with phone sign-in mounted, and is accepted once it is cleared', async () => { const { engine, manager, invite } = await boot({ plugins: { phoneNumber: true } }); const email = 'phone-mounted@example.com'; From 2633dc175313f3393741b6507fdb8c8a38509e92 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:23:15 +0000 Subject: [PATCH 25/26] fix(auth): the one-step door takes every reading again once the sessions are revoked The readings of the closing rule are taken a second time after the account's sessions are revoked and before the password is written. A claim made after the first reading, a reading that fails, or another account at the address answers sign_in with the sessions revoked and the proof unspent. The revocation runs only while the admitted proof is still at rest. A user row that carries no value for the phone column reads as no phone number, the same as a null; the user-row read is pinned to the system context. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../34257-one-step-invitation-acceptance.md | 2 +- ...principal-doors-grants-and-organization.md | 4 +- .../src/invitation-mailbox-proof.ts | 64 +++++++++++++------ ...vitation-one-step-acceptance-34257.test.ts | 46 +++++++++++++ 4 files changed, 95 insertions(+), 21 deletions(-) diff --git a/.changeset/34257-one-step-invitation-acceptance.md b/.changeset/34257-one-step-invitation-acceptance.md index e4133942a12..784022d6b9c 100644 --- a/.changeset/34257-one-step-invitation-acceptance.md +++ b/.changeset/34257-one-step-invitation-acceptance.md @@ -15,7 +15,7 @@ Metadata-protocol: none - **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row. - **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records, in an order that matches the vendor's order), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable. -- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads all of these: the address is not verified; the account's only sign-in account is its email and password one, or it has none; it has no second factor, enabled or enrolled; its user row holds no phone number, verified or not; it holds no standing grant (an API key, an OAuth client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an identity provider's directory, revoked or expired ones included); its identity source is local; and the server allows a local password here (not SSO-only, email and password on). Every other account answers `sign_in`, including one in a state no rule names and one whose reading fails, and the proof stays unspent. Every store this plugin mounts that is keyed by a user, and every column of the vendor's user model with every plugin this plugin can mount, is classified as a claim the judge reads or as no claim, and a test holds each classification to what is mounted. The classification covers what this plugin mounts and nothing another package mounts. +- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads all of these: the address is not verified; the account's only sign-in account is its email and password one, or it has none; it has no second factor, enabled or enrolled; its user row holds no phone number, verified or not; it holds no standing grant (an API key, an OAuth client consent, an OAuth access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an identity provider's directory, revoked or expired ones included); its identity source is local; and the server allows a local password here (not SSO-only, email and password on). Every other account answers `sign_in`, including one in a state no rule names and one whose reading fails, and the proof stays unspent. Every reading is taken again once the account's sessions are revoked and before the password is written; an account that no longer passes then answers `sign_in` with its sessions revoked, and the proof stays unspent. Every store this plugin mounts that is keyed by a user, and every column of the vendor's user model with every plugin this plugin can mount, is classified as a claim the judge reads or as no claim, and a test holds each classification to what is mounted. The classification covers what this plugin mounts and nothing another package mounts. - **`sys_device_code` gains an index on `user_id`** (`@objectstack/platform-objects`), so the door reads a user's device authorizations by an indexed lookup, as it reads every other standing grant. - **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected. - **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail. diff --git a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md index 44281352f38..72779a67285 100644 --- a/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md +++ b/docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md @@ -317,7 +317,9 @@ row holds no phone number, verified or not; it holds no standing grant (an API k access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an identity provider's directory, revoked or expired ones included); its identity source is local; and the server allows a local password here (not SSO-only, email and password on). Every other account answers `sign_in`, including one in a -state no rule names and one whose reading fails, and the proof stays unspent. Every store this plugin mounts that is +state no rule names and one whose reading fails, and the proof stays unspent. Every reading is taken again once the +account's sessions are revoked and before the password is written; an account that no longer passes then answers +`sign_in` with its sessions revoked, and the proof stays unspent. Every store this plugin mounts that is keyed by a user, and every column of the vendor's user model with every plugin this plugin can mount, is classified as a claim the judge reads or as no claim, and a test holds each classification to what is mounted. The classification covers what this plugin mounts and nothing another package mounts. A cloud-managed environment sets no local password, diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 5df10a624f6..0c669336e80 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -28,9 +28,10 @@ * verification value. * - Bound to the invitation, its address and its expiry: the door requires * all three to match the invitation as it stands. - * - Single-use: spent through the internal adapter's consume before any - * write, and only by a request that passed every gate; a proof that does - * not match, or a request a gate refuses, leaves it unspent. Within one + * - Single-use: spent through the internal adapter's consume before the + * account or its password is written, and only by a request that passed + * every gate; a proof that does not match, or a request a gate refuses, + * leaves it unspent. Within one * server process concurrent redemptions of one proof are serialized, so * exactly one succeeds. Across server processes the guarantee is the * store's: on the platform's own adapter the consume reads the row and @@ -67,7 +68,10 @@ * revoked or expired ones included); its identity source is local; and the * server allows a local password here (not SSO-only, email and password on). * Every other account answers `sign_in`, including one in a state no rule - * names and one whose reading fails, and the proof stays unspent. Every store + * names and one whose reading fails, and the proof stays unspent. Every + * reading is taken again once the account's sessions are revoked and before + * the password is written; an account that no longer passes then answers + * `sign_in` with its sessions revoked, and the proof stays unspent. Every store * this plugin mounts that is keyed by a user, and every column of the * vendor's user model with every plugin this plugin can mount, is classified * as a claim the judge reads or as no claim, and a test holds each @@ -459,7 +463,9 @@ export type UserRowSignInReading = /** * The sign-in identity columns of `userId`'s stored row. One read by `id` as - * the system. No read surface, a failed read, or no row is `ok: false`. + * the system. No read surface, a failed read, or no row is `ok: false`. A row + * that carries no value for a column reads as holding no phone number, the + * same as a null. */ export async function readUserRowSignIn(engine: UserSourceReader | undefined, userId: string): Promise { if (!engine?.find) return { ok: false }; @@ -631,11 +637,12 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo if (!(await admits(parseStored(stored?.value), proof, invitation))) return refuseProof(); const email = invitation.email.toLowerCase(); - const found = await internal.findUserByEmail(email, { includeAccounts: true }); - const existing = found?.user; - if (existing) { + const signIn = () => ctx.json({ success: true, data: { outcome: 'sign_in' } }); + // Every reading of the closing rule, judged. Taken before anything is + // written, and again once the account's sessions are revoked. + const judge = async (found: any): Promise => { const engine = host.getDataEngine() as UserSourceReader | undefined; - const userId = String(existing.id); + const userId = String(found.user.id); const [source, userRowSignIn, grantReadings] = await Promise.all([ readUserSource(engine, userId), readUserRowSignIn(engine, userId), @@ -644,19 +651,21 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo const standingGrants = Object.fromEntries( STANDING_GRANT_OBJECTS.map((object, i) => [object, grantReadings[i]]), ) as Record; - const state = oneStepSignInState({ - emailVerified: existing.emailVerified, + return oneStepSignInState({ + emailVerified: found.user.emailVerified, accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId), - twoFactorEnabled: existing.twoFactorEnabled, - phoneNumberVerified: existing.phoneNumberVerified, + twoFactorEnabled: found.user.twoFactorEnabled, + phoneNumberVerified: found.user.phoneNumberVerified, userRowSignIn, standingGrants, source, ssoOnly: host.isSsoOnlyMode(), emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled, }); - if (state) return ctx.json({ success: true, data: { outcome: 'sign_in' } }); - } + }; + const found = await internal.findUserByEmail(email, { includeAccounts: true }); + const existing = found?.user; + if (existing && (await judge(found))) return signIn(); const password = typeof body.password === 'string' ? body.password : ''; const passwordConfig = ctx.context.password.config; @@ -698,8 +707,28 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo // (a breached one) leaves the proof usable. const passwordHash = await ctx.context.password.hash(password); + const sameProof = (row: { value: string } | null | undefined) => + !!row && parseStored(row.value)?.h === parseStored(stored?.value)?.h; + if (existing) { + const userId = String(existing.id); + // The sessions are revoked before the password is written, which + // matches the vendor's order on its own password doors, and only while + // the proof this request admitted is still at rest. + if (!sameProof(await internal.findVerificationValue(identifier))) return refuseProof(); + await internal.deleteUserSessions(userId); + // Every reading again, now that no session of the account can make a + // claim: one made after the first reading, a reading that fails, or + // another account at the address answers `sign_in`. Taken before the + // proof is spent, so it stays unspent; the sessions stay revoked. + const again: OneStepSignInState | undefined = await internal + .findUserByEmail(email, { includeAccounts: true }) + .then((reread: any) => (String(reread?.user?.id) === userId ? judge(reread) : 'unrecognised')) + .catch(() => 'identity_unreadable'); + if (again) return signIn(); + } + const consumed = await internal.consumeVerificationValue(identifier); - if (!consumed || parseStored(consumed.value)?.h !== parseStored(stored?.value)?.h) return refuseProof(); + if (!sameProof(consumed)) return refuseProof(); let user: any; if (!existing) { @@ -707,9 +736,6 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo await internal.linkAccount({ userId: user.id, providerId: 'credential', accountId: user.id, password: passwordHash }); } else { const userId = String(existing.id); - // The sessions are revoked before the password is written, which - // matches the vendor's order on its own password doors. - await internal.deleteUserSessions(userId); if (await internal.findCredentialAccount(userId)) { await internal.updatePassword(userId, passwordHash); if (historyHash) await host.recordPasswordHistory(userId, historyHash); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index b34ab0f9db3..adac6b588d2 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -1021,6 +1021,16 @@ describe('#34257 — the door sets a password on an existing account only where const leave = findThrowsForUserRowSignIn(engine); expect(await readUserRowSignIn(engine, 'u_row')).toEqual({ ok: false }); leave(); + // The door reads the row as the system, so no caller's permissions narrow it. + const seen: unknown[] = []; + const find = engine.find.bind(engine); + engine.find = async (name: string, q: any = {}, options?: unknown) => { + seen.push(options); + return find(name, q); + }; + await readUserRowSignIn(engine, 'u_row'); + expect(seen).toHaveLength(1); + expect(seen[0]).toMatchObject({ context: { isSystem: true } }); }); it('a phone number on the user row answers sign_in with phone sign-in mounted, and is accepted once it is cleared', async () => { @@ -1100,6 +1110,42 @@ describe('#34257 — the door sets a password on an existing account only where await leave(); await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD })); }); + + // The readings are taken again once the sessions are revoked: a grant made + // after the first reading, or a reading that fails on the second take, + // answers sign_in with no password written and the proof unspent. + it.each(['a grant appears', 'a reading fails'] as const)( + 'when %s between the first reading and the write, the door answers sign_in, writes no password and leaves the proof unspent', + async (race) => { + const { engine, manager, invite } = await boot(); + const email = `raced-${race.replace(/ /g, '-')}@example.com`; + const { invitation, proof } = await invite(email); + const { userId, cookie } = await signUp(manager, engine, email); + const credential = () => (engine.tables.get('sys_account') ?? []).find((a) => a.user_id === userId && a.provider_id === 'credential'); + const password = credential()!.password; + const find = engine.find.bind(engine); + let reads = 0; + let leave = () => {}; + engine.find = async (name: string, q: any = {}) => { + if (name !== 'sys_api_key') return find(name, q); + reads += 1; + if (race === 'a reading fails' && reads > 1) throw new Error('store unavailable'); + const rows = await find(name, q); + if (race === 'a grant appears' && reads === 1) leave = await holdGrant(engine, 'sys_api_key', email); + return rows; + }; + + await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD })); + expect(credential()!.password).toBe(password); + expect(userRow(engine, email)!.email_verified).toBeFalsy(); + // The sessions were revoked before the second reading, and stay revoked. + expect(await sessionUser(manager, cookie)).toBeNull(); + + engine.find = find; + leave(); + await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD })); + }, + ); }); describe('#34257 — a password the door sets starts the password-age clock and clears a forced change', () => { From 9bb1e6ad52c7830ff808d47255ce3ea37641d556 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:25:13 +0000 Subject: [PATCH 26/26] test(auth): a proof spent after admission revokes no session at the one-step door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- ...vitation-one-step-acceptance-34257.test.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index adac6b588d2..eed2e028e33 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -1146,6 +1146,29 @@ describe('#34257 — the door sets a password on an existing account only where await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD })); }, ); + + it('a proof spent by another redemption after this one was admitted revokes no session and writes no password', async () => { + const { engine, manager, invite } = await boot(); + const email = 'raced-spent@example.com'; + const { invitation, proof } = await invite(email); + const { userId, cookie } = await signUp(manager, engine, email); + const credential = () => (engine.tables.get('sys_account') ?? []).find((a) => a.user_id === userId && a.provider_id === 'credential'); + const password = credential()!.password; + const find = engine.find.bind(engine); + engine.find = async (name: string, q: any = {}) => { + const rows = await find(name, q); + if (name === 'sys_api_key') { + const identifier = invitationProofIdentifier(invitation.id); + engine.tables.set('sys_verification', (engine.tables.get('sys_verification') ?? []).filter((v) => v.identifier !== identifier)); + } + return rows; + }; + + await expectRefused(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD })); + engine.find = find; + expect(credential()!.password).toBe(password); + expect(await sessionUser(manager, cookie)).not.toBeNull(); + }); }); describe('#34257 — a password the door sets starts the password-age clock and clears a forced change', () => {