Skip to content

Commit 2633dc1

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

4 files changed

Lines changed: 95 additions & 21 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Metadata-protocol: none
1515

1616
- **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.
1717
- **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.
18-
- **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.
18+
- **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.
1919
- **`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.
2020
- **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.
2121
- **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.

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,9 @@ row holds no phone number, verified or not; it holds no standing grant (an API k
317317
access or refresh token, an OAuth client, a device authorization, an SSO provider, a SCIM credential or a link to an
318318
identity provider's directory, revoked or expired ones included); its identity source is local; and the server allows
319319
a local password here (not SSO-only, email and password on). Every other account answers `sign_in`, including one in a
320-
state no rule names and one whose reading fails, and the proof stays unspent. Every store this plugin mounts that is
320+
state no rule names and one whose reading fails, and the proof stays unspent. Every reading is taken again once the
321+
account's sessions are revoked and before the password is written; an account that no longer passes then answers
322+
`sign_in` with its sessions revoked, and the proof stays unspent. Every store this plugin mounts that is
321323
keyed by a user, and every column of the vendor's user model with every plugin this plugin can mount, is classified as
322324
a claim the judge reads or as no claim, and a test holds each classification to what is mounted. The classification
323325
covers what this plugin mounts and nothing another package mounts. A cloud-managed environment sets no local password,

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

Lines changed: 45 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@
2828
* verification value.
2929
* - Bound to the invitation, its address and its expiry: the door requires
3030
* all three to match the invitation as it stands.
31-
* - Single-use: spent through the internal adapter's consume before any
32-
* write, and only by a request that passed every gate; a proof that does
33-
* not match, or a request a gate refuses, leaves it unspent. Within one
31+
* - Single-use: spent through the internal adapter's consume before the
32+
* account or its password is written, and only by a request that passed
33+
* every gate; a proof that does not match, or a request a gate refuses,
34+
* leaves it unspent. Within one
3435
* server process concurrent redemptions of one proof are serialized, so
3536
* exactly one succeeds. Across server processes the guarantee is the
3637
* store's: on the platform's own adapter the consume reads the row and
@@ -67,7 +68,10 @@
6768
* revoked or expired ones included); its identity source is local; and the
6869
* server allows a local password here (not SSO-only, email and password on).
6970
* Every other account answers `sign_in`, including one in a state no rule
70-
* names and one whose reading fails, and the proof stays unspent. Every store
71+
* names and one whose reading fails, and the proof stays unspent. Every
72+
* reading is taken again once the account's sessions are revoked and before
73+
* the password is written; an account that no longer passes then answers
74+
* `sign_in` with its sessions revoked, and the proof stays unspent. Every store
7175
* this plugin mounts that is keyed by a user, and every column of the
7276
* vendor's user model with every plugin this plugin can mount, is classified
7377
* as a claim the judge reads or as no claim, and a test holds each
@@ -459,7 +463,9 @@ export type UserRowSignInReading =
459463

460464
/**
461465
* The sign-in identity columns of `userId`'s stored row. One read by `id` as
462-
* the system. No read surface, a failed read, or no row is `ok: false`.
466+
* the system. No read surface, a failed read, or no row is `ok: false`. A row
467+
* that carries no value for a column reads as holding no phone number, the
468+
* same as a null.
463469
*/
464470
export async function readUserRowSignIn(engine: UserSourceReader | undefined, userId: string): Promise<UserRowSignInReading> {
465471
if (!engine?.find) return { ok: false };
@@ -631,11 +637,12 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
631637
if (!(await admits(parseStored(stored?.value), proof, invitation))) return refuseProof();
632638

633639
const email = invitation.email.toLowerCase();
634-
const found = await internal.findUserByEmail(email, { includeAccounts: true });
635-
const existing = found?.user;
636-
if (existing) {
640+
const signIn = () => ctx.json({ success: true, data: { outcome: 'sign_in' } });
641+
// Every reading of the closing rule, judged. Taken before anything is
642+
// written, and again once the account's sessions are revoked.
643+
const judge = async (found: any): Promise<OneStepSignInState | undefined> => {
637644
const engine = host.getDataEngine() as UserSourceReader | undefined;
638-
const userId = String(existing.id);
645+
const userId = String(found.user.id);
639646
const [source, userRowSignIn, grantReadings] = await Promise.all([
640647
readUserSource(engine, userId),
641648
readUserRowSignIn(engine, userId),
@@ -644,19 +651,21 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
644651
const standingGrants = Object.fromEntries(
645652
STANDING_GRANT_OBJECTS.map((object, i) => [object, grantReadings[i]]),
646653
) as Record<StandingGrantObject, StandingGrantReading>;
647-
const state = oneStepSignInState({
648-
emailVerified: existing.emailVerified,
654+
return oneStepSignInState({
655+
emailVerified: found.user.emailVerified,
649656
accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId),
650-
twoFactorEnabled: existing.twoFactorEnabled,
651-
phoneNumberVerified: existing.phoneNumberVerified,
657+
twoFactorEnabled: found.user.twoFactorEnabled,
658+
phoneNumberVerified: found.user.phoneNumberVerified,
652659
userRowSignIn,
653660
standingGrants,
654661
source,
655662
ssoOnly: host.isSsoOnlyMode(),
656663
emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled,
657664
});
658-
if (state) return ctx.json({ success: true, data: { outcome: 'sign_in' } });
659-
}
665+
};
666+
const found = await internal.findUserByEmail(email, { includeAccounts: true });
667+
const existing = found?.user;
668+
if (existing && (await judge(found))) return signIn();
660669

661670
const password = typeof body.password === 'string' ? body.password : '';
662671
const passwordConfig = ctx.context.password.config;
@@ -698,18 +707,35 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
698707
// (a breached one) leaves the proof usable.
699708
const passwordHash = await ctx.context.password.hash(password);
700709

710+
const sameProof = (row: { value: string } | null | undefined) =>
711+
!!row && parseStored(row.value)?.h === parseStored(stored?.value)?.h;
712+
if (existing) {
713+
const userId = String(existing.id);
714+
// The sessions are revoked before the password is written, which
715+
// matches the vendor's order on its own password doors, and only while
716+
// the proof this request admitted is still at rest.
717+
if (!sameProof(await internal.findVerificationValue(identifier))) return refuseProof();
718+
await internal.deleteUserSessions(userId);
719+
// Every reading again, now that no session of the account can make a
720+
// claim: one made after the first reading, a reading that fails, or
721+
// another account at the address answers `sign_in`. Taken before the
722+
// proof is spent, so it stays unspent; the sessions stay revoked.
723+
const again: OneStepSignInState | undefined = await internal
724+
.findUserByEmail(email, { includeAccounts: true })
725+
.then((reread: any) => (String(reread?.user?.id) === userId ? judge(reread) : 'unrecognised'))
726+
.catch(() => 'identity_unreadable');
727+
if (again) return signIn();
728+
}
729+
701730
const consumed = await internal.consumeVerificationValue(identifier);
702-
if (!consumed || parseStored(consumed.value)?.h !== parseStored(stored?.value)?.h) return refuseProof();
731+
if (!sameProof(consumed)) return refuseProof();
703732

704733
let user: any;
705734
if (!existing) {
706735
user = await internal.createUser({ email, name, emailVerified: true }, { method: 'email-password' });
707736
await internal.linkAccount({ userId: user.id, providerId: 'credential', accountId: user.id, password: passwordHash });
708737
} else {
709738
const userId = String(existing.id);
710-
// The sessions are revoked before the password is written, which
711-
// matches the vendor's order on its own password doors.
712-
await internal.deleteUserSessions(userId);
713739
if (await internal.findCredentialAccount(userId)) {
714740
await internal.updatePassword(userId, passwordHash);
715741
if (historyHash) await host.recordPasswordHistory(userId, historyHash);

‎packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1021,6 +1021,16 @@ describe('#34257 — the door sets a password on an existing account only where
10211021
const leave = findThrowsForUserRowSignIn(engine);
10221022
expect(await readUserRowSignIn(engine, 'u_row')).toEqual({ ok: false });
10231023
leave();
1024+
// The door reads the row as the system, so no caller's permissions narrow it.
1025+
const seen: unknown[] = [];
1026+
const find = engine.find.bind(engine);
1027+
engine.find = async (name: string, q: any = {}, options?: unknown) => {
1028+
seen.push(options);
1029+
return find(name, q);
1030+
};
1031+
await readUserRowSignIn(engine, 'u_row');
1032+
expect(seen).toHaveLength(1);
1033+
expect(seen[0]).toMatchObject({ context: { isSystem: true } });
10241034
});
10251035

10261036
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
11001110
await leave();
11011111
await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'S', password: NEW_PASSWORD }));
11021112
});
1113+
1114+
// The readings are taken again once the sessions are revoked: a grant made
1115+
// after the first reading, or a reading that fails on the second take,
1116+
// answers sign_in with no password written and the proof unspent.
1117+
it.each(['a grant appears', 'a reading fails'] as const)(
1118+
'when %s between the first reading and the write, the door answers sign_in, writes no password and leaves the proof unspent',
1119+
async (race) => {
1120+
const { engine, manager, invite } = await boot();
1121+
const email = `raced-${race.replace(/ /g, '-')}@example.com`;
1122+
const { invitation, proof } = await invite(email);
1123+
const { userId, cookie } = await signUp(manager, engine, email);
1124+
const credential = () => (engine.tables.get('sys_account') ?? []).find((a) => a.user_id === userId && a.provider_id === 'credential');
1125+
const password = credential()!.password;
1126+
const find = engine.find.bind(engine);
1127+
let reads = 0;
1128+
let leave = () => {};
1129+
engine.find = async (name: string, q: any = {}) => {
1130+
if (name !== 'sys_api_key') return find(name, q);
1131+
reads += 1;
1132+
if (race === 'a reading fails' && reads > 1) throw new Error('store unavailable');
1133+
const rows = await find(name, q);
1134+
if (race === 'a grant appears' && reads === 1) leave = await holdGrant(engine, 'sys_api_key', email);
1135+
return rows;
1136+
};
1137+
1138+
await expectSignIn(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD }));
1139+
expect(credential()!.password).toBe(password);
1140+
expect(userRow(engine, email)!.email_verified).toBeFalsy();
1141+
// The sessions were revoked before the second reading, and stay revoked.
1142+
expect(await sessionUser(manager, cookie)).toBeNull();
1143+
1144+
engine.find = find;
1145+
leave();
1146+
await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD }));
1147+
},
1148+
);
11031149
});
11041150

11051151
describe('#34257 — a password the door sets starts the password-age clock and clears a forced change', () => {

0 commit comments

Comments
 (0)