@ultimat3/auth 31.50.0 → 31.52.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 +1 -1
- package/README.md +23 -5
- package/package.json +4 -5
- package/src/adapter.ts +7 -0
- package/src/builtin-adapter.ts +2 -2
- package/src/index.ts +2 -0
- package/src/link-login.ts +171 -0
- package/src/member-invite.ts +4 -5
- package/src/memory-adapter.ts +1 -1
- package/src/verification-purposes.ts +4 -0
- package/src/verify.ts +38 -2
package/CLAUDE.md
CHANGED
|
@@ -196,7 +196,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
|
|
|
196
196
|
| `jwt-bearer-resolver.ts` | an external bearer JWT → `{ actor, scopes } \| null` |
|
|
197
197
|
| `revocation.ts` | per-user, per-org and before-an-instant sweeps; `disableUser` (sessions and api keys) |
|
|
198
198
|
| `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 |
|
|
199
|
-
| `link-login.ts` | `signInWithLink
|
|
199
|
+
| `link-login.ts` | `signInWithLink`: a consumed link → `LoginResult`, or `X_MFA_REQUIRED` and no session. Refuses a purpose not declared `signIn: true` (the built-ins never are) and an unverified account |
|
|
200
200
|
| `mfa-challenge.ts` | the sealed challenge `X_MFA_REQUIRED` carries, and `completeMfa` |
|
|
201
201
|
| `mfa-handoff.ts` | `mfaPath`: the challenge from a built-in callback to the app's page — path check, `__Host-x_mfa` cookie, reader |
|
|
202
202
|
| `mfa-replay-postgres.ts` | the shared replay guard: the claim and the sweep. Its DDL is in `tables.ts` |
|
package/README.md
CHANGED
|
@@ -695,12 +695,12 @@ const verification = await consumeVerification(runtime, {
|
|
|
695
695
|
| Name | Is |
|
|
696
696
|
|---|---|
|
|
697
697
|
| `VERIFICATION_PURPOSES` | `['email-verify', 'password-reset']` — the two built in. `VerificationPurpose` is `string` (`As of 2026-11`): any declared name |
|
|
698
|
-
| `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 |
|
|
698
|
+
| `defineVerificationPurpose({ name, template, ttlMs, identifier?, signIn? })` | `{ name, issue, consume }` on the same code path — an invite, an email change, an account deletion. `signIn: true` declares the one purpose whose link signs its holder in (`signInWithLink`); absent, it never does. Twice or with no template: `X_VERIFICATION_PURPOSE_INVALID`. `emailVerification` and `passwordReset` are the built-in instances |
|
|
699
699
|
| `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 |
|
|
700
700
|
| `VERIFICATION_TEMPLATES` | purpose → **catalog key** (`auth.email-verify`, `auth.password-reset`), never copy: the body lives in the app's i18n catalog |
|
|
701
701
|
| `DEFAULT_VERIFICATION_TTL_MS` | 24 h for `email-verify`, 1 h for `password-reset` — a reset link is a password |
|
|
702
702
|
| `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 |
|
|
703
|
-
| `issueVerification(runtime, input)` | `{ token, expiresAt }`. The token comes back for a test or a CLI; production only ever mails it |
|
|
703
|
+
| `issueVerification(runtime, input)` | `{ token, expiresAt }`. The token comes back for a test or a CLI; production only ever mails it. `to?` names the recipient, and only on a purpose declared `recipient: 'explicit'` (the member invite: its identifier is tenant + address, not an address): mail goes to that `to`, never normalised, and it is required. On any other purpose, `passwordReset` and every sign-in purpose included, a `to` is `X_CONFIG_INVALID` before any row is written, so a request body spread into `issue` cannot redirect a reset link |
|
|
704
704
|
| `consumeVerification(runtime, input)` | the `AuthVerification` row, or `X_UNAUTHENTICATED`. Unknown, spent, expired and mismatched are one answer. Reads only `{ store, clock }` of the runtime. An undeclared purpose on either door is `X_VERIFICATION_PURPOSE_UNKNOWN` |
|
|
705
705
|
|
|
706
706
|
One live token per `(purpose, identifier)`. A wrong guess destroys nothing: the store's
|
|
@@ -709,9 +709,27 @@ unauthenticated POST with any token cannot kill the victim's live link.
|
|
|
709
709
|
|
|
710
710
|
### Signing in with a mailed link
|
|
711
711
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
`
|
|
712
|
+
`As of 2026-11`. `signInWithLink(auth, { purpose, identifier, token, ip?, userAgent?, signUp? })`
|
|
713
|
+
consumes a link issued under a purpose declared `signIn: true` and answers what `login()` answers.
|
|
714
|
+
With TOTP enrolled it answers `X_MFA_REQUIRED` and writes no session:
|
|
715
|
+
`completeMfa(auth, challenge, code, { ip, userAgent })` finishes it, as after a password. `ip` and
|
|
716
|
+
`userAgent` go on the session the call writes: the link's, or with TOTP the second leg's.
|
|
717
|
+
|
|
718
|
+
Redemption needs the address as well as the token. The mailed URL carries the token only, so the
|
|
719
|
+
page it opens asks for the address (prefilled where the same browser asked for the link) and posts
|
|
720
|
+
both: an address in the URL lands in every log and referrer the link passes through.
|
|
721
|
+
|
|
722
|
+
| Case | Answer |
|
|
723
|
+
|---|---|
|
|
724
|
+
| valid link, no second factor | `LoginResult`, the session `mfaSatisfied` |
|
|
725
|
+
| valid link, TOTP enrolled | `X_MFA_REQUIRED` with `meta.challenge`; no session row. A fresh link never clears the count of wrong codes |
|
|
726
|
+
| a link already consumed (its own address and token), whatever that attempt ended in | `X_UNAUTHENTICATED`: the link is spent before anything else is read. A try with the wrong address consumes nothing, so the link stays live for the right one |
|
|
727
|
+
| unknown, expired, mismatched or another purpose's token | `X_UNAUTHENTICATED`, and a wrong guess leaves the mailed link live |
|
|
728
|
+
| no account at the address | `X_UNAUTHENTICATED`, and the link is spent: enabling `signUp` takes a freshly mailed one. With `signUp: { id?, orgId?, roles?, scopes?, externalId? }` a passwordless account is created verified: in the creating write on an adapter that stores `CreateUserInput.emailVerifiedAt` (both built-in ones do). An app adapter that drops it gets a second `updateUser` stamp; if that write fails the call is `X_AUTH_WRITE_FAILED`, the account exists unverified, and the next link is refused as one that never verified its address. `signUp` never changes an account that exists |
|
|
729
|
+
| a disabled account | `X_UNAUTHENTICATED`, naming nothing |
|
|
730
|
+
| an account that never verified its address | `X_UNAUTHENTICATED`, named: whoever registered it chose its password. A verification stamp alone leaves their credentials intact. Recovery requires an app-owned flow: consume a `passwordReset` to prove the inbox, keep the account disabled while clearing every credential and session, and atomically verify recovery still owns the disable before stamping and reopening. Coordinate every administrative disable with that ownership check; `updateUser` and `enableUser` do not provide it. If ownership is lost or cleanup fails, leave the account disabled |
|
|
731
|
+
| `purpose` is `'email-verify'` or `'password-reset'`, is not declared `signIn: true`, or declares an `identifier` other than the exported `normaliseEmail` | `X_CONFIG_INVALID`, before the store is asked: the token stays live for its own job |
|
|
732
|
+
| `purpose` names nothing `defineVerificationPurpose` declared | `X_VERIFICATION_PURPOSE_UNKNOWN`, before the store is asked |
|
|
715
733
|
|
|
716
734
|
## Passkeys — WebAuthn sign-in and digest-bound step-up
|
|
717
735
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/auth",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.52.0",
|
|
4
4
|
"description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -38,7 +38,6 @@
|
|
|
38
38
|
"src",
|
|
39
39
|
"!src/**/*.test.ts",
|
|
40
40
|
"!src/**/*-fixture.ts",
|
|
41
|
-
"!src/link-login.ts",
|
|
42
41
|
"CLAUDE.md",
|
|
43
42
|
"README.md",
|
|
44
43
|
"LICENSE"
|
|
@@ -51,8 +50,8 @@
|
|
|
51
50
|
"test": "bun test"
|
|
52
51
|
},
|
|
53
52
|
"dependencies": {
|
|
54
|
-
"@ultimat3/core": "31.
|
|
55
|
-
"@ultimat3/db": "31.
|
|
56
|
-
"@ultimat3/schema": "31.
|
|
53
|
+
"@ultimat3/core": "31.52.0",
|
|
54
|
+
"@ultimat3/db": "31.52.0",
|
|
55
|
+
"@ultimat3/schema": "31.52.0"
|
|
57
56
|
}
|
|
58
57
|
}
|
package/src/adapter.ts
CHANGED
|
@@ -46,6 +46,13 @@ export interface CreateUserInput {
|
|
|
46
46
|
readonly roles: readonly string[];
|
|
47
47
|
readonly scopes?: readonly string[] | undefined;
|
|
48
48
|
readonly externalId?: string | null | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* The address proven at creation (a sign-in link's sign-up). An adapter that stores it in the
|
|
51
|
+
* same write as the row leaves no failure between the account and its stamp. Absent is
|
|
52
|
+
* unverified. An adapter that drops it gets a second `updateUser` stamp, and if that write fails
|
|
53
|
+
* the account exists unverified (`X_AUTH_WRITE_FAILED`), refused by every later link.
|
|
54
|
+
*/
|
|
55
|
+
readonly emailVerifiedAt?: Date | null | undefined;
|
|
49
56
|
readonly createdAt: Date;
|
|
50
57
|
}
|
|
51
58
|
|
package/src/builtin-adapter.ts
CHANGED
|
@@ -101,10 +101,10 @@ export class PostgresAuthAdapter implements AuthAdapter {
|
|
|
101
101
|
'createUser',
|
|
102
102
|
sql`
|
|
103
103
|
insert into x_users (id, email, password_hash, org_id, roles, scopes, external_id,
|
|
104
|
-
created_at)
|
|
104
|
+
email_verified_at, created_at)
|
|
105
105
|
values (${input.id}, ${input.email}, ${input.passwordHash}, ${input.orgId},
|
|
106
106
|
${[...input.roles]}, ${[...(input.scopes ?? [])]}, ${input.externalId ?? null},
|
|
107
|
-
${input.createdAt})
|
|
107
|
+
${input.emailVerifiedAt ?? null}, ${input.createdAt})
|
|
108
108
|
returning *`,
|
|
109
109
|
);
|
|
110
110
|
// An empty `returning` means no row landed. A user fabricated from `{}` would travel back
|
package/src/index.ts
CHANGED
|
@@ -172,6 +172,8 @@ export { boundedKdfGate, kdfGate } from './kdf-gate';
|
|
|
172
172
|
// The installers and their factory types are `@ultimat3/auth/adapter`'s, and only its: the boot
|
|
173
173
|
// calls them with what `apps/<app>/runtime.ts` named.
|
|
174
174
|
export { purgeAuthLimits } from './limiter-install';
|
|
175
|
+
export type { LinkSignInInput, LinkSignUp } from './link-login';
|
|
176
|
+
export { signInWithLink } from './link-login';
|
|
175
177
|
export type { HandleDirectory } from './login-identity';
|
|
176
178
|
export { normaliseHandle } from './login-identity';
|
|
177
179
|
export type {
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Single responsibility: `signInWithLink` — a mailed link as a sign-in door. The link is consumed
|
|
2
|
+
// (single-use, expiring, hashed at rest: `consumeVerification`), its address resolved to a user,
|
|
3
|
+
// and the answer is the `LoginResult` every other door gives — or `X_MFA_REQUIRED` and no session
|
|
4
|
+
// when a second factor is enrolled. One call, so the second factor is not the caller's to forget.
|
|
5
|
+
|
|
6
|
+
import { ConfigInvalidError, renderFixLiteral, uuidV7 } from '@ultimat3/core';
|
|
7
|
+
import type { AuthUser } from './adapter';
|
|
8
|
+
import type { Auth, LoginResult } from './auth';
|
|
9
|
+
import { normaliseEmail } from './email';
|
|
10
|
+
import { AuthError, authWriteFailed } from './errors';
|
|
11
|
+
import { mfaChallengeRequired } from './mfa-challenge';
|
|
12
|
+
import { resolveActor } from './policy-bridge';
|
|
13
|
+
import { createSession, sessionCookie } from './session';
|
|
14
|
+
import { verificationPurpose } from './verification-purposes';
|
|
15
|
+
import { consumeWith, VERIFICATION_PURPOSES, type VerificationPurpose } from './verify';
|
|
16
|
+
|
|
17
|
+
/** What a proven address with no account becomes. Business convention, so the app states it. */
|
|
18
|
+
export interface LinkSignUp {
|
|
19
|
+
/** The user's id, when the app already chose one — as `register(auth, { id })` takes it. */
|
|
20
|
+
readonly id?: string | undefined;
|
|
21
|
+
readonly orgId?: string | null | undefined;
|
|
22
|
+
readonly roles?: readonly string[] | undefined;
|
|
23
|
+
readonly scopes?: readonly string[] | undefined;
|
|
24
|
+
readonly externalId?: string | null | undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface LinkSignInInput {
|
|
28
|
+
/**
|
|
29
|
+
* The purpose the link was issued under: one the app declared for signing in
|
|
30
|
+
* (`defineVerificationPurpose({ …, signIn: true })`). Never `'email-verify'`,
|
|
31
|
+
* `'password-reset'` or any purpose not declared `signIn` — a token mailed to do one job is not
|
|
32
|
+
* a session.
|
|
33
|
+
*/
|
|
34
|
+
readonly purpose: VerificationPurpose;
|
|
35
|
+
/** The address the link was mailed to. */
|
|
36
|
+
readonly identifier: string;
|
|
37
|
+
readonly token: string;
|
|
38
|
+
/**
|
|
39
|
+
* Stamped on the session this call writes. With TOTP enrolled it writes none: hand them to
|
|
40
|
+
* `completeMfa(auth, challenge, code, { ip, userAgent })`, the leg that does.
|
|
41
|
+
*/
|
|
42
|
+
readonly ip?: string | null | undefined;
|
|
43
|
+
readonly userAgent?: string | null | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Declared: an address no account holds becomes a verified, passwordless one. Absent: it is
|
|
46
|
+
* refused. Never applied to an account that exists.
|
|
47
|
+
*/
|
|
48
|
+
readonly signUp?: LinkSignUp | undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One answer for "no account" and "disabled account", carrying nothing: the caller proved an
|
|
53
|
+
* inbox, which is not a reason to describe the account behind it.
|
|
54
|
+
*/
|
|
55
|
+
const linkSignInRefused = (purpose: string): AuthError =>
|
|
56
|
+
new AuthError({
|
|
57
|
+
code: 'X_UNAUTHENTICATED',
|
|
58
|
+
cause: 'the sign-in link was valid, and its address has no account that may sign in',
|
|
59
|
+
fix: `signInWithLink(auth, { purpose: ${renderFixLiteral(purpose, "'<purpose>'")}, identifier, token, signUp: {} }) // only where a proven address with no account should become one, and with a freshly mailed link: this one is spent. A disabled account stays refused`,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* An account holds the address and never proved it, so whoever registered it chose its password.
|
|
64
|
+
* Signing the inbox's owner into that account hands them a session somebody else can also open —
|
|
65
|
+
* and so does merely verifying it: the registrant's password, second factor, passkeys, API keys and
|
|
66
|
+
* sessions survive a stamp. Recovery needs app-owned coordination with every administrative
|
|
67
|
+
* disable, including an atomic ownership check when reopening. Named,
|
|
68
|
+
* because this caller owns the address — the rule `oauthAccountNotLinked` follows.
|
|
69
|
+
*/
|
|
70
|
+
const linkAccountUnverified = (): AuthError =>
|
|
71
|
+
new AuthError({
|
|
72
|
+
code: 'X_UNAUTHENTICATED',
|
|
73
|
+
cause:
|
|
74
|
+
'an account holds this address but never verified it, so whoever registered it may hold its password, and a sign-in link may not claim it',
|
|
75
|
+
fix: 'await passwordReset.issue(runtime, { identifier: email, locale }) // consuming the reset proves only the inbox; use an app-owned recovery flow that coordinates disableUser and every administrative disable, clears all credentials, and atomically verifies ownership before reopening',
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
/** The one purpose a refusal's fix names: its own, so no outstanding link of another job is promoted. */
|
|
79
|
+
const SIGN_IN_PURPOSE_FIX =
|
|
80
|
+
"defineVerificationPurpose({ name: 'sign-in', template: 'auth.sign-in', ttlMs: 15 * 60 * 1000, signIn: true }) // a purpose of its own, never one that already mails another job's links; then issue a fresh link under it and signInWithLink(auth, { purpose: 'sign-in', identifier, token })";
|
|
81
|
+
|
|
82
|
+
/** Before the store is asked, so a refused purpose leaves its token live for its own job. */
|
|
83
|
+
function assertSignInPurpose(name: string): void {
|
|
84
|
+
if ((VERIFICATION_PURPOSES as readonly string[]).includes(name)) {
|
|
85
|
+
throw new ConfigInvalidError({
|
|
86
|
+
cause: `signInWithLink() was given the built-in purpose '${name}', whose token is mailed to do that one job and is not a sign-in credential`,
|
|
87
|
+
fix: SIGN_IN_PURPOSE_FIX,
|
|
88
|
+
meta: { purpose: name },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
const purpose = verificationPurpose(name);
|
|
92
|
+
// Opt-in, never inferred from the identifier: an email-change or account-deletion link keys on
|
|
93
|
+
// the address too, and was mailed to do that one job.
|
|
94
|
+
if (purpose.signIn !== true) {
|
|
95
|
+
throw new ConfigInvalidError({
|
|
96
|
+
cause: `the verification purpose ${renderFixLiteral(name, "'<purpose>'")} is not declared a sign-in credential, so its link was mailed to do another job`,
|
|
97
|
+
fix: SIGN_IN_PURPOSE_FIX,
|
|
98
|
+
meta: { purpose: name },
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
// The stored identifier is looked up as `x_users.email`, so it must be keyed the way that is:
|
|
102
|
+
// the exported `normaliseEmail` itself, the default, not a function that happens to agree.
|
|
103
|
+
if (purpose.identifier !== normaliseEmail) {
|
|
104
|
+
throw new ConfigInvalidError({
|
|
105
|
+
cause: `the verification purpose ${renderFixLiteral(name, "'<purpose>'")} declares its own identifier, so what its link proves is not known to be an account's address`,
|
|
106
|
+
fix: SIGN_IN_PURPOSE_FIX,
|
|
107
|
+
meta: { purpose: name },
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function signUpWith(auth: Auth, email: string, signUp: LinkSignUp): Promise<AuthUser> {
|
|
113
|
+
const created = await auth.adapter.createUser({
|
|
114
|
+
id: signUp.id ?? uuidV7(auth.clock),
|
|
115
|
+
email,
|
|
116
|
+
// No password, and never a random one: a hash nobody knows the input to is still a
|
|
117
|
+
// credential a reset flow could hand over.
|
|
118
|
+
passwordHash: null,
|
|
119
|
+
orgId: signUp.orgId ?? null,
|
|
120
|
+
roles: signUp.roles ?? [],
|
|
121
|
+
scopes: signUp.scopes ?? [],
|
|
122
|
+
externalId: signUp.externalId ?? null,
|
|
123
|
+
// In the creating write: a stamp written second could fail after the row landed, leaving an
|
|
124
|
+
// account this same door refuses on every later link.
|
|
125
|
+
emailVerifiedAt: auth.clock.now(),
|
|
126
|
+
createdAt: auth.clock.now(),
|
|
127
|
+
});
|
|
128
|
+
if (created.emailVerifiedAt !== null) return created;
|
|
129
|
+
// An app's own adapter that predates the field: the second write, failing closed.
|
|
130
|
+
const stamped = await auth.adapter.updateUser(created.id, { emailVerifiedAt: auth.clock.now() });
|
|
131
|
+
if (stamped === null) throw authWriteFailed('updateUser', 'x_users');
|
|
132
|
+
return stamped;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A consumed link → a session, or the second factor's challenge.
|
|
137
|
+
*
|
|
138
|
+
* The link is spent FIRST, in the store's one atomic step: every refusal below this line has
|
|
139
|
+
* already used it, so a link is good for one attempt whatever the attempt ends in. With a second
|
|
140
|
+
* factor enrolled the answer is `X_MFA_REQUIRED` carrying the sealed challenge `completeMfa`
|
|
141
|
+
* takes; no session row is written, and a fresh link never clears the count of wrong codes.
|
|
142
|
+
*/
|
|
143
|
+
export async function signInWithLink(auth: Auth, input: LinkSignInInput): Promise<LoginResult> {
|
|
144
|
+
assertSignInPurpose(input.purpose);
|
|
145
|
+
const record = await consumeWith(
|
|
146
|
+
{ store: auth.adapter, clock: auth.clock },
|
|
147
|
+
{ purpose: input.purpose, identifier: input.identifier, token: input.token },
|
|
148
|
+
);
|
|
149
|
+
const email = normaliseEmail(record.identifier);
|
|
150
|
+
const existing = await auth.adapter.findUserByEmail(email);
|
|
151
|
+
if (existing === null && input.signUp === undefined) throw linkSignInRefused(input.purpose);
|
|
152
|
+
if (existing !== null && existing.disabledAt !== null) throw linkSignInRefused(input.purpose);
|
|
153
|
+
if (existing !== null && existing.emailVerifiedAt === null) throw linkAccountUnverified();
|
|
154
|
+
const user = existing ?? (await signUpWith(auth, email, input.signUp ?? {}));
|
|
155
|
+
|
|
156
|
+
// The inbox is proven, the second factor is not: the user's rule, whichever door they used.
|
|
157
|
+
if (user.mfaSecret !== null) throw await mfaChallengeRequired(auth, user.id);
|
|
158
|
+
|
|
159
|
+
const issued = await createSession(auth.sessions, {
|
|
160
|
+
userId: user.id,
|
|
161
|
+
ip: input.ip ?? null,
|
|
162
|
+
userAgent: input.userAgent,
|
|
163
|
+
mfaSatisfied: true,
|
|
164
|
+
});
|
|
165
|
+
return {
|
|
166
|
+
actor: resolveActor({ kind: 'user', user, session: issued.session }),
|
|
167
|
+
session: issued.session,
|
|
168
|
+
token: issued.token,
|
|
169
|
+
cookie: sessionCookie(issued.token, auth.sessions.policy),
|
|
170
|
+
};
|
|
171
|
+
}
|
package/src/member-invite.ts
CHANGED
|
@@ -92,6 +92,7 @@ export function defineMemberInvite(input: DefineMemberInviteInput): MemberInvite
|
|
|
92
92
|
template: input.template,
|
|
93
93
|
ttlMs: input.ttlMs,
|
|
94
94
|
identifier: (raw) => raw,
|
|
95
|
+
recipient: 'explicit',
|
|
95
96
|
});
|
|
96
97
|
const runtime = (auth: Auth, mail: MailSender): VerificationRuntime => ({
|
|
97
98
|
store: auth.adapter,
|
|
@@ -105,12 +106,10 @@ export function defineMemberInvite(input: DefineMemberInviteInput): MemberInvite
|
|
|
105
106
|
async invite(auth, mail, invite) {
|
|
106
107
|
const orgId = tenantOf(invite.orgId);
|
|
107
108
|
const to = normaliseEmail(invite.email);
|
|
108
|
-
|
|
109
|
-
const addressed: MailSender = {
|
|
110
|
-
send: (template, _key, data, locale) => mail.send(template, to, data, locale),
|
|
111
|
-
};
|
|
112
|
-
return purpose.issue(runtime(auth, addressed), {
|
|
109
|
+
return purpose.issue(runtime(auth, mail), {
|
|
113
110
|
identifier: storeKey(orgId, to),
|
|
111
|
+
// The store key is not an address; the mail goes to the address it was built from.
|
|
112
|
+
to,
|
|
114
113
|
locale: invite.locale,
|
|
115
114
|
link: invite.link,
|
|
116
115
|
data: invite.data,
|
package/src/memory-adapter.ts
CHANGED
|
@@ -128,7 +128,7 @@ export class MemoryAuthAdapter implements AuthAdapter {
|
|
|
128
128
|
id: input.id,
|
|
129
129
|
// Stored as handed over, exactly as the `insert into x_users` binds it.
|
|
130
130
|
email: input.email,
|
|
131
|
-
emailVerifiedAt: null,
|
|
131
|
+
emailVerifiedAt: input.emailVerifiedAt ?? null,
|
|
132
132
|
passwordHash: input.passwordHash,
|
|
133
133
|
orgId: input.orgId,
|
|
134
134
|
roles: [...input.roles],
|
|
@@ -13,6 +13,10 @@ export interface VerificationPurposeDef {
|
|
|
13
13
|
readonly ttlMs: number;
|
|
14
14
|
/** How the identifier becomes the store key and the mail address. */
|
|
15
15
|
readonly identifier: (raw: string) => string;
|
|
16
|
+
/** Declared a sign-in credential: the one thing `signInWithLink` consumes. Absent is no. */
|
|
17
|
+
readonly signIn?: boolean | undefined;
|
|
18
|
+
/** `'explicit'`: `issueVerification` mails `to`, not the identifier (an invite). Absent refuses `to`. */
|
|
19
|
+
readonly recipient?: 'explicit' | undefined;
|
|
16
20
|
}
|
|
17
21
|
|
|
18
22
|
// A Map, never a record keyed by an attacker-reachable string: `consumeVerification` looks a
|
package/src/verify.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// tier 4 and auth is tier 2, so the app wires mail's `send` in and auth imports nothing upward.
|
|
5
5
|
|
|
6
6
|
import type { Clock } from '@ultimat3/core';
|
|
7
|
-
import { renderFixLiteral, timingSafeEqual } from '@ultimat3/core';
|
|
7
|
+
import { renderCauseValue, renderFixLiteral, timingSafeEqual } from '@ultimat3/core';
|
|
8
8
|
import type { AuthVerification, VerificationStore } from './adapter';
|
|
9
9
|
import { normaliseEmail } from './email';
|
|
10
10
|
import { AuthError } from './errors';
|
|
@@ -58,6 +58,8 @@ export interface IssueVerificationInput {
|
|
|
58
58
|
readonly purpose: VerificationPurpose;
|
|
59
59
|
/** The email address. Also the store key — one live token per purpose per address. */
|
|
60
60
|
readonly identifier: string;
|
|
61
|
+
/** Only on a purpose declared `recipient: 'explicit'`; refused on any other. Never normalised. */
|
|
62
|
+
readonly to?: string | undefined;
|
|
61
63
|
readonly locale: string;
|
|
62
64
|
readonly ttlMs?: number | undefined;
|
|
63
65
|
/** Builds the URL that carries the token. Defaults to the token alone. */
|
|
@@ -98,6 +100,13 @@ export async function issueVerification(
|
|
|
98
100
|
// the case, and each one of them is a password. It is also the address the mail is sent to, so
|
|
99
101
|
// the link goes to the inbox the account is keyed by rather than to whatever a form posted.
|
|
100
102
|
const identifier = purpose.identifier(input.identifier);
|
|
103
|
+
// Refused above the write, like the TTL: a blank recipient would leave a live row nobody can read.
|
|
104
|
+
// `to` is a door only a purpose that declared `recipient: 'explicit'` opens: a reset or sign-in
|
|
105
|
+
// link must reach the inbox the account is keyed by, even when an app spreads a request body in.
|
|
106
|
+
const explicit = purpose.recipient === 'explicit';
|
|
107
|
+
if (!explicit && input.to !== undefined) throw recipientRefused(purpose.name, 'undeclared');
|
|
108
|
+
const to = explicit ? (input.to ?? '') : identifier;
|
|
109
|
+
if (to.trim() === '') throw recipientRefused(purpose.name, 'blank');
|
|
101
110
|
await runtime.store.putVerification({
|
|
102
111
|
id: randomToken(12),
|
|
103
112
|
purpose: purpose.name,
|
|
@@ -109,7 +118,7 @@ export async function issueVerification(
|
|
|
109
118
|
});
|
|
110
119
|
await runtime.mail.send(
|
|
111
120
|
purpose.template,
|
|
112
|
-
|
|
121
|
+
to,
|
|
113
122
|
{
|
|
114
123
|
...(input.data ?? {}),
|
|
115
124
|
link: input.link?.(token) ?? token,
|
|
@@ -120,6 +129,20 @@ export async function issueVerification(
|
|
|
120
129
|
return { token, expiresAt };
|
|
121
130
|
}
|
|
122
131
|
|
|
132
|
+
const recipientRefused = (purpose: string, why: 'blank' | 'undeclared'): AuthError =>
|
|
133
|
+
new AuthError({
|
|
134
|
+
code: 'X_CONFIG_INVALID',
|
|
135
|
+
cause:
|
|
136
|
+
why === 'blank'
|
|
137
|
+
? `the ${renderCauseValue(purpose)} purpose mails to an explicit \`to\`, and it is blank or absent, so the credential has nowhere to go`
|
|
138
|
+
: `issueVerification({ to }) on the ${renderCauseValue(purpose)} purpose, which mails to the address it is keyed by; a \`to\` there could send the link to another inbox`,
|
|
139
|
+
fix:
|
|
140
|
+
why === 'blank'
|
|
141
|
+
? `await issueVerification(runtime, { purpose: ${renderFixLiteral(purpose, "'<purpose>'")}, identifier: key, to: 'ada@example.com', locale }) // name the address`
|
|
142
|
+
: "defineVerificationPurpose({ name, template, ttlMs, recipient: 'explicit' }) // or drop `to`: the identifier is the address",
|
|
143
|
+
meta: { option: 'verification.to' },
|
|
144
|
+
});
|
|
145
|
+
|
|
123
146
|
/**
|
|
124
147
|
* One error for "no such token", "already used", "expired" and "wrong token". Distinguishing
|
|
125
148
|
* them tells an attacker which address has a live reset in flight.
|
|
@@ -190,6 +213,17 @@ export interface DefineVerificationPurposeInput {
|
|
|
190
213
|
readonly ttlMs: number;
|
|
191
214
|
/** The identifier's one normalisation. Defaults to `normaliseEmail`, the address door's. */
|
|
192
215
|
readonly identifier?: ((raw: string) => string) | undefined;
|
|
216
|
+
/**
|
|
217
|
+
* `true`: this purpose's link signs its holder in (`signInWithLink`). Stated, never inferred:
|
|
218
|
+
* an email-change or account-deletion link proves the same inbox but was mailed to do one job.
|
|
219
|
+
*/
|
|
220
|
+
readonly signIn?: boolean | undefined;
|
|
221
|
+
/**
|
|
222
|
+
* `'explicit'`: the mail goes to the `to` each issue names, because the identifier is a store key
|
|
223
|
+
* and not an address (a member invite's tenant + address). Required then, never normalised.
|
|
224
|
+
* Absent: `issue` refuses a `to`, so a reset link cannot be redirected by a caller's input.
|
|
225
|
+
*/
|
|
226
|
+
readonly recipient?: 'explicit' | undefined;
|
|
193
227
|
}
|
|
194
228
|
|
|
195
229
|
export interface VerificationPurposeHandle {
|
|
@@ -223,6 +257,8 @@ export function defineVerificationPurpose(
|
|
|
223
257
|
template: input.template,
|
|
224
258
|
ttlMs,
|
|
225
259
|
identifier: input.identifier ?? normaliseEmail,
|
|
260
|
+
signIn: input.signIn === true,
|
|
261
|
+
...(input.recipient === 'explicit' ? { recipient: 'explicit' as const } : {}),
|
|
226
262
|
});
|
|
227
263
|
const name = input.name;
|
|
228
264
|
return {
|