@ultimat3/auth 31.23.0 → 31.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -187,6 +187,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
187
187
  | `workload.ts` | a workload JWT (K8s SA / SPIFFE / IMDS / RFC 8693) → a `ServiceIdentity`; `checkWorkloadToken`, the verdict form |
188
188
  | `jwt-bearer-resolver.ts` | an external bearer JWT → `{ actor, scopes } \| null` |
189
189
  | `revocation.ts` | per-user, per-org and before-an-instant sweeps; `disableUser` (sessions and api keys) |
190
+ | `member-invite.ts` / `member-invite-marks.ts` | `defineMemberInvite`: a verification purpose keyed on (tenant, address), accept into `orgId` via `updatePrivileges`; revoke = link, plus membership + sessions only where a `joined` mark proves an invite granted it. The `joined`/`revoked` marks make a racing revoke win without a transaction |
190
191
  | `mfa-challenge.ts` | the sealed challenge `X_MFA_REQUIRED` carries, and `completeMfa` |
191
192
  | `mfa-replay-postgres.ts` | the shared replay guard: the claim and the sweep. Its DDL is in `tables.ts` |
192
193
  | `mfa-secret.ts` | the TOTP secret at rest: seal on write, open on read, the one-shot that seals older rows |
package/README.md CHANGED
@@ -594,6 +594,7 @@ const verification = await consumeVerification(runtime, {
594
594
  |---|---|
595
595
  | `VERIFICATION_PURPOSES` | `['email-verify', 'password-reset']` — the two built in. `VerificationPurpose` is `string` (`As of 2026-11`): any declared name |
596
596
  | `defineVerificationPurpose({ name, template, ttlMs, identifier? })` | `{ name, issue, consume }` on the same code path — an invite, an email change, an account deletion. Twice or with no template: `X_VERIFICATION_PURPOSE_INVALID`. `emailVerification` and `passwordReset` are the built-in instances |
597
+ | `defineMemberInvite({ name?, template, ttlMs })` | `{ purpose, invite, accept, revoke }`: a single-use invite keyed on (tenant, address). `accept` consumes it under the signed-in account's own address, sets `orgId`/`roles` and rotates the session; `revoke` kills the link and, only where this flow granted it, the membership and that account's sessions; a revoke racing an accept wins. Every bad link is `X_UNAUTHENTICATED`; a member of another tenant is `X_FORBIDDEN`. Functions, not actions (tier 2): the app wraps each in its own `action()` — `x g invite` writes them |
597
598
  | `VERIFICATION_TEMPLATES` | purpose → **catalog key** (`auth.email-verify`, `auth.password-reset`), never copy: the body lives in the app's i18n catalog |
598
599
  | `DEFAULT_VERIFICATION_TTL_MS` | 24 h for `email-verify`, 1 h for `password-reset` — a reset link is a password |
599
600
  | `MailSender` | the injected port: `send(template, to, data, locale)`. `@ultimat3/mail` is tier 4 and this package is tier 2, so the app wires it |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/auth",
3
- "version": "31.23.0",
3
+ "version": "31.25.0",
4
4
  "description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -50,8 +50,8 @@
50
50
  "test": "bun test"
51
51
  },
52
52
  "dependencies": {
53
- "@ultimat3/core": "31.23.0",
54
- "@ultimat3/db": "31.23.0",
55
- "@ultimat3/schema": "31.23.0"
53
+ "@ultimat3/core": "31.25.0",
54
+ "@ultimat3/db": "31.25.0",
55
+ "@ultimat3/schema": "31.25.0"
56
56
  }
57
57
  }
package/src/index.ts CHANGED
@@ -173,6 +173,15 @@ export { boundedKdfGate, kdfGate } from './kdf-gate';
173
173
  export { purgeAuthLimits } from './limiter-install';
174
174
  export type { HandleDirectory } from './login-identity';
175
175
  export { normaliseHandle } from './login-identity';
176
+ export type {
177
+ AcceptInviteInput,
178
+ DefineMemberInviteInput,
179
+ InviteMemberInput,
180
+ MemberInviteFlow,
181
+ RevokedInvite,
182
+ RevokeInviteInput,
183
+ } from './member-invite';
184
+ export { defineMemberInvite } from './member-invite';
176
185
  export { type MemoryAuthAdapter, memoryAuthAdapter } from './memory-adapter';
177
186
  export type {
178
187
  EnrolTotpInput,
@@ -0,0 +1,55 @@
1
+ // Single responsibility: the two marks that let an invite's accept and revoke agree without a
2
+ // transaction — `joined` (this address joined this org THROUGH an invite, so revoke may remove it)
3
+ // and `revoked` (a revoke replaced the invite's row). Both ride the verification store, the one
4
+ // seam both calls share, through its two atomic operations: an upsert and a take-on-hash-match.
5
+
6
+ import type { Clock } from '@ultimat3/core';
7
+ import type { VerificationStore } from './adapter';
8
+ import { randomToken, sha256Hex } from './tokens';
9
+
10
+ export type InviteMark = 'joined' | 'revoked';
11
+
12
+ /**
13
+ * Where a mark lives. `revoked` takes the invite's OWN row, so a re-invite (which upserts that row)
14
+ * clears it; `joined` lives under its own purpose, so it outlives the spent link. Neither purpose
15
+ * suffix is a registered purpose, so no `consume` can reach a `joined` row.
16
+ */
17
+ const slot = (purpose: string, mark: InviteMark): string =>
18
+ mark === 'revoked' ? purpose : `${purpose}:joined`;
19
+
20
+ /**
21
+ * The mark's stored hash. Prefixed, so it is never a `sha256Hex` output and no token redeems it —
22
+ * a deterministic hash in the invite's own row would otherwise be a link anyone could compute.
23
+ */
24
+ const markHash = (mark: InviteMark, key: string): string => `${mark}:${sha256Hex(key)}`;
25
+
26
+ export async function putMark(
27
+ store: VerificationStore,
28
+ clock: Clock,
29
+ purpose: string,
30
+ mark: InviteMark,
31
+ key: string,
32
+ ): Promise<void> {
33
+ const now = clock.now();
34
+ await store.putVerification({
35
+ id: randomToken(12),
36
+ purpose: slot(purpose, mark),
37
+ identifier: key,
38
+ tokenHash: markHash(mark, key),
39
+ // Never read as a lifetime: a mark is only ever taken, and `take` does not judge expiry.
40
+ expiresAt: now,
41
+ consumedAt: null,
42
+ createdAt: now,
43
+ });
44
+ }
45
+
46
+ /** Takes the mark if it is there, in the store's one atomic step. `true` when it was. */
47
+ export async function takeMark(
48
+ store: VerificationStore,
49
+ purpose: string,
50
+ mark: InviteMark,
51
+ key: string,
52
+ ): Promise<boolean> {
53
+ const taken = await store.takeVerification(slot(purpose, mark), key, markHash(mark, key));
54
+ return taken !== null;
55
+ }
@@ -0,0 +1,210 @@
1
+ // Single responsibility: the member invite — a mailed, single-use credential bound to ONE tenant
2
+ // that moves the account it was mailed to into that tenant. The tenant is half the store key, so a
3
+ // token minted for X has no row under Y to match: cross-tenant redemption is a miss in the store,
4
+ // not a check a caller can forget. Who may invite, seat limits and the roles offered are the app's.
5
+
6
+ import { logger } from '@ultimat3/core';
7
+ import type { AuthUser } from './adapter';
8
+ import type { Auth } from './auth';
9
+ import { normaliseEmail } from './email';
10
+ import { authForbidden, authWriteFailed } from './errors';
11
+ import { putMark, takeMark } from './member-invite-marks';
12
+ import { type UpdatePrivilegesResult, updatePrivileges } from './privileges';
13
+ import type { IssuedSession } from './session';
14
+ import {
15
+ defineVerificationPurpose,
16
+ type IssuedVerification,
17
+ type MailSender,
18
+ type VerificationRuntime,
19
+ } from './verify';
20
+
21
+ export interface DefineMemberInviteInput {
22
+ /** The verification purpose it registers. Unique, process-wide. Default `'member-invite'`. */
23
+ readonly name?: string | undefined;
24
+ /** The i18n catalog key of the invite mail. */
25
+ readonly template: string;
26
+ /** Required: how long an unredeemed invite stays a door is the app's call, stated once. */
27
+ readonly ttlMs: number;
28
+ }
29
+
30
+ export interface InviteMemberInput {
31
+ readonly orgId: string;
32
+ readonly email: string;
33
+ readonly locale: string;
34
+ /** Builds the URL that carries the token. It must carry `orgId` too: accept needs both. */
35
+ readonly link?: ((token: string) => string) | undefined;
36
+ readonly data?: Readonly<Record<string, unknown>> | undefined;
37
+ }
38
+
39
+ export interface AcceptInviteInput {
40
+ readonly orgId: string;
41
+ readonly token: string;
42
+ /** The signed-in account redeeming it. Only the account at the invited address can. */
43
+ readonly userId: string;
44
+ /** What the app's wrapper decided this invite grants. Replaces the account's roles; default none. */
45
+ readonly roles?: readonly string[] | undefined;
46
+ /** The caller's own session, rotated because membership is a privilege change. */
47
+ readonly session?: IssuedSession['session'] | undefined;
48
+ }
49
+
50
+ export interface RevokeInviteInput {
51
+ readonly orgId: string;
52
+ readonly email: string;
53
+ /** Logged as `auth.revocation` before the first write, like every revocation. */
54
+ readonly reason: string;
55
+ }
56
+
57
+ export interface RevokedInvite {
58
+ /** `true` when the address had already joined this tenant and has now been removed from it. */
59
+ readonly memberRemoved: boolean;
60
+ readonly sessionsRevoked: number;
61
+ }
62
+
63
+ export interface MemberInviteFlow {
64
+ readonly purpose: string;
65
+ /** Mint and mail the link. Re-inviting the address (a resend) supersedes the earlier link. */
66
+ invite(auth: Auth, mail: MailSender, input: InviteMemberInput): Promise<IssuedVerification>;
67
+ accept(auth: Auth, input: AcceptInviteInput): Promise<UpdatePrivilegesResult>;
68
+ /** Withdraw the link and, when it was accepted, the membership and every session it held. */
69
+ revoke(auth: Auth, input: RevokeInviteInput): Promise<RevokedInvite>;
70
+ }
71
+
72
+ /** JSON, not a separator: an org id is the app's string, and no character is safe to assume out. */
73
+ const storeKey = (orgId: string, email: string): string =>
74
+ JSON.stringify([orgId, normaliseEmail(email)]);
75
+
76
+ const tenantOf = (orgId: string): string => {
77
+ if (orgId.trim() !== '') return orgId;
78
+ throw authForbidden('member invite', 'it names no tenant, so accepting it would join nothing');
79
+ };
80
+
81
+ /**
82
+ * The sender accept's runtime carries: `consumeVerification` reads the store and the clock and
83
+ * never the sender, so there is nothing for this one to do — and nothing for it to throw either.
84
+ */
85
+ const consumeOnly: MailSender = { send: async () => {} };
86
+
87
+ /** Declare the flow once, at module scope. Registers its verification purpose. */
88
+ export function defineMemberInvite(input: DefineMemberInviteInput): MemberInviteFlow {
89
+ // The key is already normalised by `storeKey`; the purpose's own normalisation must not refold it.
90
+ const purpose = defineVerificationPurpose({
91
+ name: input.name ?? 'member-invite',
92
+ template: input.template,
93
+ ttlMs: input.ttlMs,
94
+ identifier: (raw) => raw,
95
+ });
96
+ const runtime = (auth: Auth, mail: MailSender): VerificationRuntime => ({
97
+ store: auth.adapter,
98
+ clock: auth.clock,
99
+ mail,
100
+ });
101
+
102
+ return {
103
+ purpose: purpose.name,
104
+
105
+ async invite(auth, mail, invite) {
106
+ const orgId = tenantOf(invite.orgId);
107
+ const to = normaliseEmail(invite.email);
108
+ // The store key is not an address; the mail goes to the address it was built from.
109
+ const addressed: MailSender = {
110
+ send: (template, _key, data, locale) => mail.send(template, to, data, locale),
111
+ };
112
+ return purpose.issue(runtime(auth, addressed), {
113
+ identifier: storeKey(orgId, to),
114
+ locale: invite.locale,
115
+ link: invite.link,
116
+ data: invite.data,
117
+ });
118
+ },
119
+
120
+ async accept(auth, accept) {
121
+ const consume = (identifier: string) =>
122
+ purpose.consume(runtime(auth, consumeOnly), { identifier, token: accept.token });
123
+ // The refusal a bad token gets, word for word, asked of the verification door itself under a
124
+ // key no invite can have (`storeKey` only ever writes strings): one factory, so a renamed
125
+ // purpose cannot make an unknown account read differently from a wrong link.
126
+ const refuse = async (): Promise<never> => {
127
+ await consume(JSON.stringify([accept.orgId, null]));
128
+ // Reached only by a store that answered a row for a key nothing wrote: it broke the seam.
129
+ throw authWriteFailed('takeVerification', 'x_verifications');
130
+ };
131
+ const user = await auth.adapter.findUserById(accept.userId);
132
+ // Which accounts exist, and which are disabled, is not this caller's to learn.
133
+ if (user === null || user.disabledAt !== null) return await refuse();
134
+ // Checked BEFORE the consume, so the refusal leaves the link live for after the move.
135
+ if (user.orgId !== null && user.orgId !== accept.orgId) {
136
+ throw authForbidden(
137
+ 'member invite',
138
+ 'the account is a member of another tenant; membership is one tenant per account',
139
+ );
140
+ }
141
+ // Keyed on THIS account's address: a link forwarded to another account finds no row.
142
+ const key = storeKey(accept.orgId, user.email);
143
+ await consume(key);
144
+ // Already a member of this org: the link is spent and nothing was granted, so there is
145
+ // nothing for a revoke to take back — no `joined` mark, which is what keeps a founder who
146
+ // redeems an invite to their own org out of revoke's reach.
147
+ if (user.orgId === accept.orgId) return updatePrivileges(auth, user.id, {}, accept.session);
148
+ // Marked BEFORE the grant and checked AFTER it; revoke marks before it reads. Whichever of
149
+ // the two lands second sees the other's mark, so a revoke racing this accept always wins.
150
+ await putMark(auth.adapter, auth.clock, purpose.name, 'joined', key);
151
+ const joined = await updatePrivileges(
152
+ auth,
153
+ user.id,
154
+ joinPatch(user, accept, auth),
155
+ accept.session,
156
+ );
157
+ if (await takeMark(auth.adapter, purpose.name, 'revoked', key)) {
158
+ await takeMark(auth.adapter, purpose.name, 'joined', key);
159
+ // As if the revoke had landed after: out of the org, every session ended, link refused.
160
+ await removeMember(auth, user.id);
161
+ return await refuse();
162
+ }
163
+ return joined;
164
+ },
165
+
166
+ async revoke(auth, revoke) {
167
+ logger.warn('auth.revocation', {
168
+ operation: 'revokeMemberInvite',
169
+ scope: revoke.orgId,
170
+ reason: revoke.reason,
171
+ });
172
+ const key = storeKey(revoke.orgId, revoke.email);
173
+ // Over the invite's own row: a pending link dies, and an accept in flight finds the mark.
174
+ await putMark(auth.adapter, auth.clock, purpose.name, 'revoked', key);
175
+ // Only what an invite granted is taken back: no `joined` mark, no removal — a member who
176
+ // arrived any other way (the org's founder, a seeded admin) is the app's to remove.
177
+ if (!(await takeMark(auth.adapter, purpose.name, 'joined', key))) {
178
+ return { memberRemoved: false, sessionsRevoked: 0 };
179
+ }
180
+ const user = await auth.adapter.findUserByEmail(normaliseEmail(revoke.email));
181
+ if (user === null || user.orgId !== revoke.orgId) {
182
+ return { memberRemoved: false, sessionsRevoked: 0 };
183
+ }
184
+ return { memberRemoved: true, sessionsRevoked: await removeMember(auth, user.id) };
185
+ },
186
+ };
187
+ }
188
+
189
+ /** Out of the org, with no role kept: a role is held in a tenant. Answers the sessions it ended. */
190
+ async function removeMember(auth: Auth, userId: string): Promise<number> {
191
+ const removed = await auth.adapter.updateUser(userId, {
192
+ orgId: null,
193
+ roles: [],
194
+ permissions: [],
195
+ });
196
+ if (removed === null) throw authWriteFailed('updateUser', 'x_users');
197
+ return await auth.adapter.deleteSessionsForUser(userId);
198
+ }
199
+
200
+ /** Re-accepting into the tenant already held changes nothing but the spent link. */
201
+ const joinPatch = (user: AuthUser, accept: AcceptInviteInput, auth: Auth) =>
202
+ user.orgId === accept.orgId
203
+ ? {}
204
+ : {
205
+ orgId: accept.orgId,
206
+ roles: [...(accept.roles ?? [])],
207
+ permissions: [],
208
+ // Redeeming a link mailed to the address is proof of the inbox.
209
+ emailVerifiedAt: user.emailVerifiedAt ?? auth.clock.now(),
210
+ };
@@ -46,8 +46,14 @@ const SQL_USER = `select id::text as id, email, email_verified_at::text as email
46
46
  array_to_string(roles, ',') as roles, created_at::text as created_at
47
47
  from x_users where id = $1::uuid`;
48
48
  const SQL_API_KEYS = 'delete from x_api_keys where user_id = $1::uuid';
49
- const SQL_VERIFICATIONS = `delete from x_verifications
50
- where identifier = (select email from x_users where id = $1::uuid)`;
49
+ // The address as an identifier, and as the last member of a `defineMemberInvite` key
50
+ // (`["<orgId>","<email>"]`, `JSON.stringify`): matched by exact suffix, never `like` — an `_` in an
51
+ // address is a `like` wildcard, and would erase someone else's invite.
52
+ const SQL_VERIFICATIONS = `delete from x_verifications v
53
+ using (select email, to_json(email)::text as quoted from x_users where id = $1::uuid) subject
54
+ where v.identifier = subject.email
55
+ or (left(v.identifier, 2) = '["'
56
+ and right(v.identifier, length(subject.quoted) + 2) = ',' || subject.quoted || ']')`;
51
57
  // Sessions and accounts reference the user `on delete cascade` (`tables.ts`): one statement.
52
58
  const SQL_USER_DELETE = 'delete from x_users where id = $1::uuid returning id';
53
59