Skip to content

Commit 0e8a0d3

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw
1 parent b60bbe4 commit 0e8a0d3

6 files changed

Lines changed: 180 additions & 33 deletions

‎.changeset/34257-one-step-invitation-acceptance.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ Clause-②: yes (widening)
1313
Metadata-protocol: none
1414

1515
- **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.
16-
- **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.
17-
- **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.
16+
- **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.
17+
- **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.
1818
- **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.
1919
- **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.
2020
- **`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.

‎docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -311,8 +311,11 @@ and a session for that account. The proof is never at rest in clear, the stored
311311
bound to the invitation, its address and its expiry; a resend retires the old one. It is spent only by a request that
312312
passed every gate, and one server process serializes concurrent redemptions of it; across processes, single use is
313313
as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check
314-
failed. An address whose account is verified, is linked to a provider, or otherwise takes no password from this door
315-
is answered "sign in", with the proof unspent. A cloud-managed environment sets no local password, so there the door
314+
failed. The door sets a password on an existing account only when it reads that the mailbox is the account's one
315+
claim: the address is not verified, the account's only sign-in account is its email and password one or it has none,
316+
it has no second factor and no verified phone number, its identity source is local, and the server allows a local
317+
password here (not SSO-only, email and password on). Every other account, including one in a state no rule names,
318+
answers `sign_in`, and the proof stays unspent. A cloud-managed environment sets no local password, so there the door
316319
refuses every request that carries a proof. It carries a rate limit per client network address and per invitation,
317320
as ADR-0121 D6 requires. Enforced by
318321
`packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in

‎packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ export interface PluginListHost {
132132
resolveAuthSecret: AuthManager['resolveAuthSecret'];
133133
resolveMembershipRole: AuthManager['resolveMembershipRole'];
134134
resolveTwoFactorAccountLockout: AuthManager['resolveTwoFactorAccountLockout'];
135+
assertPasswordNotReused: AuthManager['assertPasswordNotReused'];
136+
recordPasswordHistory: AuthManager['recordPasswordHistory'];
135137
stampPasswordChangedAt: AuthManager['stampPasswordChangedAt'];
136138
storedRecipientLocale: AuthManager['storedRecipientLocale'];
137139
validateAudienceAdmission: AuthManager['validateAudienceAdmission'];
@@ -308,6 +310,8 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
308310
getDataEngine: () => this.getDataEngine(),
309311
counterStore: () => this.config.sharedCounterStore?.() ?? Promise.reject(new Error('no shared counter store')),
310312
stampPasswordChangedAt: (userId) => this.stampPasswordChangedAt(userId),
313+
assertPasswordNotReused: (userId, candidate, verify) => this.assertPasswordNotReused(userId, candidate, verify),
314+
recordPasswordHistory: (userId, oldHash) => this.recordPasswordHistory(userId, oldHash),
311315
}));
312316
}
313317

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2455,6 +2455,8 @@ export class AuthManager {
24552455
resolveAuthSecret: (...a) => this.resolveAuthSecret(...a),
24562456
resolveMembershipRole: (...a) => this.resolveMembershipRole(...a),
24572457
resolveTwoFactorAccountLockout: (...a) => this.resolveTwoFactorAccountLockout(...a),
2458+
assertPasswordNotReused: (...a) => this.assertPasswordNotReused(...a),
2459+
recordPasswordHistory: (...a) => this.recordPasswordHistory(...a),
24582460
stampPasswordChangedAt: (...a) => this.stampPasswordChangedAt(...a),
24592461
storedRecipientLocale: (...a) => this.storedRecipientLocale(...a),
24602462
validateAudienceAdmission: (...a) => this.validateAudienceAdmission(...a),

‎packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts‎

Lines changed: 94 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -57,17 +57,25 @@
5757
*
5858
* ## Which existing account the door sets a password on
5959
*
60-
* The closing rule: the door sets a password on an existing account only when
61-
* the mailbox the proof establishes is the account's one and only claim, and
62-
* the server lets a local password be set here at all. Every other existing
63-
* account answers `sign_in` with the proof unspent. The states, each one a
64-
* reason the account holds a claim the proof does not outrank or the server
65-
* sets no local password, are {@link ONE_STEP_SIGN_IN_STATES}, judged by
66-
* {@link oneStepSignInState}; the card's test pins one case per state.
60+
* The door sets a password on an existing account only when it reads that the
61+
* mailbox is the account's one claim: the address is not verified, the
62+
* account's only sign-in account is its email and password one or it has
63+
* none, it has no second factor and no verified phone number, its identity
64+
* source is local, and the server allows a local password here (not SSO-only,
65+
* email and password on). Every other account, including one in a state no
66+
* rule names, answers `sign_in`, and the proof stays unspent.
67+
*
68+
* The judge, {@link oneStepSignInState}, is an allow-list: it lets the
69+
* password be set only when every value it reads is positively the one that
70+
* carries no other claim, and a value no rule names answers `sign_in` as
71+
* `unrecognised`. Its reasons are {@link ONE_STEP_SIGN_IN_STATES}; the card's
72+
* test pins one case per reason.
6773
*
6874
* An account that passes gets the typed password in place of its own, and
6975
* every one of its sessions is revoked with the reason a password reset
70-
* records (`session-tombstone.ts`). A new account is created through the
76+
* records (`session-tombstone.ts`). The password history is consulted before
77+
* the proof is spent and extended after, as the reset door does (ADR-0069
78+
* D1): a reused password is refused with the proof unspent. A new account is created through the
7179
* internal adapter, so the sign-up gates that run on every creation (audience
7280
* admission and the database hooks) run here too; the door itself refuses
7381
* where email sign-up is off. Either way the password-age stamp and the
@@ -198,12 +206,26 @@ export interface InvitationProofDoorHost {
198206
counterStore?: () => Promise<CounterStore>;
199207
/** The ADR-0069 D1 after-effects of a password set (`AuthManager#stampPasswordChangedAt`). */
200208
stampPasswordChangedAt(userId: string): Promise<void>;
209+
/**
210+
* ADR-0069 D1, the reset door's reuse check (`AuthManager#assertPasswordNotReused`):
211+
* throws `PASSWORD_REUSE`, or answers the current hash for the history.
212+
*/
213+
assertPasswordNotReused(
214+
userId: string,
215+
candidate: string,
216+
verify?: (data: { password: string; hash: string }) => Promise<boolean>,
217+
): Promise<string | undefined>;
218+
/** ADR-0069 D1, the reset door's history append (`AuthManager#recordPasswordHistory`). */
219+
recordPasswordHistory(userId: string, oldHash: string): Promise<void>;
201220
}
202221

203222
/**
204-
* The states of an existing account that answer `sign_in`, in the order they
205-
* are judged. Each is either a claim on the account the mailbox proof does not
206-
* outrank, or a server that sets no local password here.
223+
* Why an existing account answers `sign_in`. The judge
224+
* ({@link oneStepSignInState}) is an allow-list: these name the reasons it
225+
* reports, and `unrecognised` is every value it does not positively read as
226+
* carrying no other claim. Each named state is either a claim on the account
227+
* the mailbox proof does not outrank, or a server that sets no local password
228+
* here.
207229
*/
208230
export const ONE_STEP_SIGN_IN_STATES = [
209231
/** The address is already verified: its holder signs in. */
@@ -212,6 +234,8 @@ export const ONE_STEP_SIGN_IN_STATES = [
212234
'linked_provider',
213235
/** The account has a second factor enrolled. */
214236
'second_factor',
237+
/** The account has a verified phone number. */
238+
'verified_phone',
215239
/** The account is provisioned by an identity provider. */
216240
'idp_provisioned',
217241
/** The account is waiting for its first single sign-on. */
@@ -222,27 +246,58 @@ export const ONE_STEP_SIGN_IN_STATES = [
222246
'sso_only',
223247
/** Email and password sign-in is off. */
224248
'email_password_off',
249+
/** A stored value the judge does not read as carrying no other claim, such as an identity source no rule names. */
250+
'unrecognised',
225251
] as const;
226252

227253
export type OneStepSignInState = (typeof ONE_STEP_SIGN_IN_STATES)[number];
228254

229-
/** The first state of {@link ONE_STEP_SIGN_IN_STATES} the account is in, or `undefined` when the door may set its password. */
230-
export function oneStepSignInState(account: {
231-
emailVerified: boolean;
232-
linkedProvider: boolean;
233-
twoFactorEnabled: boolean;
255+
/** The `sys_user.source` values of a local account: the declared one, and none recorded. */
256+
const LOCAL_SOURCES: ReadonlySet<string | null> = new Set<string | null>(['env_native', null]);
257+
258+
/** A flag that is positively off: false, or absent because its plugin is not mounted. */
259+
function isOff(value: unknown): boolean {
260+
return value === false || value === null || value === undefined;
261+
}
262+
263+
/** What the judge reads of an existing account and the server. */
264+
export interface OneStepAccountReading {
265+
/** `user.emailVerified`, as stored. */
266+
emailVerified: unknown;
267+
/** The `providerId` of each of the user's account rows. */
268+
accountProviders: readonly unknown[];
269+
/** `user.twoFactorEnabled`, as stored (absent without the plugin). */
270+
twoFactorEnabled: unknown;
271+
/** `user.phoneNumberVerified`, as stored (absent without the plugin). */
272+
phoneNumberVerified: unknown;
273+
/** `sys_user.source`, or `ok: false` when it cannot be read. */
234274
source: { ok: true; value: string | null } | { ok: false };
275+
/** SSO-only mode. */
235276
ssoOnly: boolean;
236-
emailPasswordEnabled: boolean;
237-
}): OneStepSignInState | undefined {
238-
if (account.emailVerified) return 'verified';
239-
if (account.linkedProvider) return 'linked_provider';
240-
if (account.twoFactorEnabled) return 'second_factor';
241-
if (account.source.ok && isIdpProvisionedSource(account.source.value)) return 'idp_provisioned';
242-
if (account.source.ok && isPendingSsoSource(account.source.value)) return 'pending_sso';
277+
/** `emailAndPassword.enabled`. */
278+
emailPasswordEnabled: unknown;
279+
}
280+
281+
/**
282+
* The judge of the closing rule, an allow-list: `undefined` (the door may set
283+
* the password) only when every reading is positively the no-other-claim
284+
* value, and otherwise the reason the account answers `sign_in`. A value no
285+
* rule here names is `unrecognised`, never a pass.
286+
*/
287+
export function oneStepSignInState(account: OneStepAccountReading): OneStepSignInState | undefined {
288+
if (account.emailVerified !== false) return account.emailVerified === true ? 'verified' : 'unrecognised';
289+
if (!account.accountProviders.every((providerId) => providerId === 'credential')) return 'linked_provider';
290+
if (!isOff(account.twoFactorEnabled)) return account.twoFactorEnabled === true ? 'second_factor' : 'unrecognised';
291+
if (!isOff(account.phoneNumberVerified)) return account.phoneNumberVerified === true ? 'verified_phone' : 'unrecognised';
243292
if (!account.source.ok) return 'source_unreadable';
244-
if (account.ssoOnly) return 'sso_only';
245-
if (!account.emailPasswordEnabled) return 'email_password_off';
293+
const source = account.source.value;
294+
if (!LOCAL_SOURCES.has(source)) {
295+
if (isIdpProvisionedSource(source)) return 'idp_provisioned';
296+
if (isPendingSsoSource(source)) return 'pending_sso';
297+
return 'unrecognised';
298+
}
299+
if (account.ssoOnly !== false) return 'sso_only';
300+
if (account.emailPasswordEnabled !== true) return 'email_password_off';
246301
return undefined;
247302
}
248303

@@ -352,12 +407,13 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
352407
const existing = found?.user;
353408
if (existing) {
354409
const state = oneStepSignInState({
355-
emailVerified: existing.emailVerified === true,
356-
linkedProvider: (found.accounts ?? []).some((a: any) => a?.providerId !== 'credential'),
357-
twoFactorEnabled: existing.twoFactorEnabled === true,
410+
emailVerified: existing.emailVerified,
411+
accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId),
412+
twoFactorEnabled: existing.twoFactorEnabled,
413+
phoneNumberVerified: existing.phoneNumberVerified,
358414
source: await readUserSource(host.getDataEngine() as never, String(existing.id)),
359415
ssoOnly: host.isSsoOnlyMode(),
360-
emailPasswordEnabled: Boolean(ctx.context.options.emailAndPassword?.enabled),
416+
emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled,
361417
});
362418
if (state) return ctx.json({ success: true, data: { outcome: 'sign_in' } });
363419
}
@@ -390,6 +446,14 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
390446
}
391447
}
392448

449+
// ADR-0069 D1, as the reset door: the password history is consulted
450+
// before the proof is spent, so a reused password leaves it usable.
451+
let historyHash: string | undefined;
452+
if (existing) {
453+
const pw = ctx.context.password;
454+
historyHash = await host.assertPasswordNotReused(String(existing.id), password, pw.verify.bind(pw));
455+
}
456+
393457
// Hashed before the proof is spent: a password the hash step refuses
394458
// (a breached one) leaves the proof usable.
395459
const passwordHash = await ctx.context.password.hash(password);
@@ -406,6 +470,7 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
406470
await internal.deleteUserSessions(userId);
407471
if (await internal.findCredentialAccount(userId)) {
408472
await internal.updatePassword(userId, passwordHash);
473+
if (historyHash) await host.recordPasswordHistory(userId, historyHash);
409474
} else {
410475
await internal.createAccount({ userId, providerId: 'credential', accountId: userId, password: passwordHash });
411476
}

0 commit comments

Comments
 (0)