@ultimat3/auth 8.0.0 → 10.0.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.
@@ -8,12 +8,18 @@
8
8
  // is tier 4 and describes a rendered page. A bare `Request` in, a `Response` out, drivable from
9
9
  // a test and mountable by any router that can match a `:param`.
10
10
 
11
- import { type Clock, isUltimateError, renderThrowable, type UltimateError } from '@ultimat3/core';
11
+ import {
12
+ type Clock,
13
+ isUltimateError,
14
+ logger,
15
+ renderThrowable,
16
+ type UltimateError,
17
+ } from '@ultimat3/core';
12
18
  import type { Auth, LoginResult } from './auth';
13
- import { oauthDenied, oauthExchangeFailed, oauthProviderUnknown } from './errors';
14
19
  import { beginOAuth, type OAuthProviderId } from './oauth';
15
20
  import { BUILTIN_OAUTH_PROVIDER_IDS } from './oauth-builtins';
16
21
  import { clearHandshakeCookie, handshakeCookie, readHandshakeCookie } from './oauth-cookie';
22
+ import { oauthDenied, oauthExchangeFailed, oauthProviderUnknown } from './oauth-errors';
17
23
  import type { OAuthClientCredentials, OAuthFetch } from './oauth-exchange';
18
24
  import { oauthCredentials } from './oauth-exchange';
19
25
  import { completeOAuthLogin, type ResolveOAuthGrants } from './oauth-login';
@@ -101,6 +107,24 @@ export const OAUTH_ROUTE_STATUS: Readonly<Record<string, number>> = {
101
107
  X_CONFIG_INVALID: 500,
102
108
  };
103
109
 
110
+ /**
111
+ * The status for a code, read as an OWN key of the table above.
112
+ *
113
+ * `OAUTH_ROUTE_STATUS[code] ?? 502` is an index read on a plain object, so `Object.prototype`
114
+ * answered for `toString`, `constructor`, `hasOwnProperty` and `__proto__` — and `toString`
115
+ * yields a FUNCTION, which was handed straight to `ResponseInit.status`. `code` is a plain
116
+ * `string` on every `UltimateError`, so no cast makes that unreachable. Fourth instance of the
117
+ * class in the framework, after i18n's catalog lookup, schema's `coerce` and mcp's `validate-args`.
118
+ *
119
+ * Exported so a test can drive it without building a `Response`; `OAUTH_ROUTE_STATUS` stays
120
+ * exported unchanged, because `scripts/oauth-route-status.test.ts` pins it against
121
+ * `@ultimat3/http`'s `statusFor`.
122
+ */
123
+ export function oauthRouteStatus(code: string): number {
124
+ // 502 is the default: an uncoded throw on this path came out of the provider conversation.
125
+ return Object.hasOwn(OAUTH_ROUTE_STATUS, code) ? (OAUTH_ROUTE_STATUS[code] ?? 502) : 502;
126
+ }
127
+
104
128
  /**
105
129
  * What an anonymous caller is allowed to read. `UltimateError.toJSON()` carries `meta` and `stack`
106
130
  * — a developer's fields — and BOTH legs of this flow are public by definition, so serialising it
@@ -122,26 +146,42 @@ const publicBody = (coded: UltimateError): Record<string, string> => ({
122
146
  * wants a rendered page wraps these two descriptors; the framework ships the debuggable answer.
123
147
  */
124
148
  function problem(error: unknown, extraCookies: readonly string[]): Response {
125
- const coded = isUltimateError(error)
126
- ? error
127
- : oauthExchangeFailed({
128
- provider: 'oauth',
129
- stage: 'token',
130
- // `renderThrowable`, never `error.message`: the throw came from an adapter or a `fetch`
131
- // this package does not own, and a getter on `message` — or a `Proxy` trapping
132
- // `getPrototypeOf` — would make the callback's last answer throw instead of send.
133
- detail: renderThrowable(error),
134
- fix: 'throw an UltimateError from the AuthAdapter or OAuthFetch that failed — the factories are in packages/auth/src/errors.ts',
135
- });
149
+ const coded = isUltimateError(error) ? error : uncoded(error);
136
150
  const headers = new Headers({ 'content-type': 'application/json; charset=utf-8' });
137
151
  for (const cookie of extraCookies) headers.append('set-cookie', cookie);
138
152
  return new Response(JSON.stringify(publicBody(coded)), {
139
- // 502 is the default: an uncoded throw on this path came out of the provider conversation.
140
- status: OAUTH_ROUTE_STATUS[coded.code] ?? 502,
153
+ status: oauthRouteStatus(coded.code),
141
154
  headers,
142
155
  });
143
156
  }
144
157
 
158
+ /**
159
+ * A throw with no code: a bug in an `AuthAdapter` or an `OAuthFetch` this package does not own.
160
+ *
161
+ * Its text goes to the LOG and never into the response. `publicBody` publishes `cause`, and the
162
+ * rendered value went straight into it — so a bare
163
+ * `Error('connect ECONNREFUSED 10.4.2.17:5432 (postgres://app:hunter2@db.internal/prod)')` from a
164
+ * pool inside a callback was served to whoever typed the URL, as a 502 with the connection string
165
+ * in the body. The comment above `publicBody` says a stack and `meta` must never reach that
166
+ * reader; the field carrying the message was the one exception nobody meant to make.
167
+ *
168
+ * `renderThrowable`, never `error.message`: the value came from code this package does not own,
169
+ * and a getter on `message` — or a `Proxy` trapping `getPrototypeOf` — would make the callback's
170
+ * last answer throw instead of send. Same shape `rate-limit.ts`'s `loginFailed()` uses: one fixed
171
+ * sentence outward, the discriminating detail kept where only an operator can read it.
172
+ */
173
+ function uncoded(error: unknown): UltimateError {
174
+ logger.error('auth.oauth.uncoded_failure', { detail: renderThrowable(error) });
175
+ return oauthExchangeFailed({
176
+ provider: 'oauth',
177
+ stage: 'token',
178
+ detail:
179
+ 'an adapter or fetch this package does not own threw a value with no error code; the ' +
180
+ 'detail is in this process log under auth.oauth.uncoded_failure',
181
+ fix: 'throw an UltimateError from the AuthAdapter or OAuthFetch that failed — the factories are in packages/auth/src/errors.ts, and the OAuth ones in packages/auth/src/oauth-errors.ts',
182
+ });
183
+ }
184
+
145
185
  /** `/auth/oauth/github` → `github`; `/auth/oauth/github/callback` → `github`. */
146
186
  function providerSegment(request: Request, leg: 'start' | 'callback'): string {
147
187
  const segments = new URL(request.url).pathname.split('/').filter((s) => s.length > 0);
@@ -173,6 +213,37 @@ function assertEnabled(auth: Auth, segment: string): OAuthProviderId {
173
213
  return provider;
174
214
  }
175
215
 
216
+ /**
217
+ * The credentials for a provider, or the SAME 404 an unknown provider gets.
218
+ *
219
+ * `assertEnabled` collapses "never heard of it" and "not enabled here" into one answer so an
220
+ * anonymous caller cannot enumerate this deployment's configuration. Past it, `oauthCredentials`
221
+ * threw `X_ENV_MISSING` and `problem()` answered 500 — publishing the app's own environment
222
+ * variable names in the `cause` and, worse, restoring the oracle: 500 meant "registered here",
223
+ * 404 meant "not". A provider with no credentials is not usable, which is the only thing this
224
+ * caller is entitled to learn.
225
+ *
226
+ * The real cause is not lost: `X_ENV_MISSING`'s `cause` and `fix` are the operator's, and they go
227
+ * to the process log where only an operator can read them.
228
+ */
229
+ function credentialsFor(
230
+ provider: OAuthProviderId,
231
+ options: OAuthLoginOptions,
232
+ ): OAuthClientCredentials {
233
+ if (options.credentials !== undefined) return options.credentials;
234
+ try {
235
+ return oauthCredentials(provider, options.env ?? Bun.env);
236
+ } catch (error) {
237
+ if (!isUltimateError(error) || error.code !== 'X_ENV_MISSING') throw error;
238
+ logger.error('auth.oauth.credentials_missing', {
239
+ provider,
240
+ cause: error.cause,
241
+ fix: error.fix,
242
+ });
243
+ throw oauthProviderUnknown(provider, BUILTIN_OAUTH_PROVIDER_IDS);
244
+ }
245
+ }
246
+
176
247
  function originFor(request: Request, options: OAuthLoginOptions): string {
177
248
  const env = options.env ?? Bun.env;
178
249
  const declared = options.baseUrl ?? env['APP_URL']?.trim() ?? '';
@@ -195,7 +266,7 @@ async function startHandler(
195
266
  ): Promise<Response> {
196
267
  try {
197
268
  const provider = assertEnabled(auth, providerSegment(request, 'start'));
198
- const credentials = options.credentials ?? oauthCredentials(provider, options.env ?? Bun.env);
269
+ const credentials = credentialsFor(provider, options);
199
270
  const handshake = beginOAuth({
200
271
  provider,
201
272
  clientId: credentials.clientId,
@@ -233,6 +304,10 @@ async function callbackHandler(
233
304
  const clear = hasOAuthProvider(segment) ? [clearHandshakeCookie(segment)] : [];
234
305
  try {
235
306
  const provider = assertEnabled(auth, segment);
307
+ // Asked here purely so a provider with no credentials answers 404 on THIS leg too: the
308
+ // exchange below resolves them again from the same two sources. One oracle, closed on both
309
+ // halves — a 404 on start and a 500 on callback is the same enumeration one request later.
310
+ credentialsFor(provider, options);
236
311
  const url = new URL(request.url);
237
312
  assertNoProviderError(url, provider);
238
313
  const result: LoginResult = await completeOAuthLogin(auth, {
package/src/oauth.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  // configs are pure data and live in `oauth-registry.ts`: importing this file performs no network
5
5
  // I/O and reads no env.
6
6
 
7
- import { oauthStateInvalid } from './errors';
7
+ import { oauthStateInvalid } from './oauth-errors';
8
8
  import { providerFor } from './oauth-registry';
9
9
  import { base64Url, randomToken, sha256Bytes, timingSafeEqual } from './tokens';
10
10
 
package/src/rate-limit.ts CHANGED
@@ -85,6 +85,13 @@ export interface AuthLimiter {
85
85
  recordSuccess(key: string): Promise<void>;
86
86
  lockedUntil(key: string): Promise<Date | null>;
87
87
  reset(): Promise<void>;
88
+ /**
89
+ * Drop every expired row this limiter is keeping, and answer how many went. Optional because a
90
+ * limiter that bounds itself has nothing to sweep — `createAuthLimiter` evicts on write, so it
91
+ * omits this and `purgeAuthLimits()` skips it. A limiter backed by a table declares it, and
92
+ * that is what makes the framework's purge job able to reach one without knowing it is Postgres.
93
+ */
94
+ purgeExpired?(): Promise<number>;
88
95
  }
89
96
 
90
97
  /** What `createAuthLimiter` returns: the interface, plus the bound it keeps, observable. */
package/src/tables.ts CHANGED
@@ -1,6 +1,29 @@
1
1
  // Single responsibility: the DDL `BuiltinAdapter` expects. Exported as plain strings so an app
2
- // can paste them into a migration and read exactly what auth stores — no column holds a
3
- // plaintext secret, and that is meant to be verifiable by reading, not by trusting.
2
+ // can paste them into a migration and read EXACTLY what auth stores — verifiable by reading,
3
+ // never by trusting.
4
+ //
5
+ // What is at rest, stated column by column rather than as a claim:
6
+ //
7
+ // | Column | Holds |
8
+ // |---|---|
9
+ // | `x_users.password_hash` | an argon2id digest, never the password |
10
+ // | `x_users.recovery_code_hashes` | SHA-256 digests, never the codes (`mfa.ts`) |
11
+ // | `x_users.mfa_secret` | **the base32 TOTP seed, in the clear** — see below |
12
+ // | `x_accounts.access_token` / `refresh_token` | **nothing.** The framework writes `null` |
13
+ // | `x_sessions.*`, `x_verifications.token_hash` | digests and metadata, never a token |
14
+ //
15
+ // `mfa_secret` is the one plaintext secret this schema still holds, and it is stated here rather
16
+ // than glossed: a TOTP seed is symmetric, so verifying a code requires the seed itself and a
17
+ // digest cannot replace it. Encrypting it needs a key-management seam this package does not have,
18
+ // which is a design change and not a patch — DEFERRED, deliberately, and written down so nobody
19
+ // reads the header above as covering it. `mfa.ts`'s "a database dump is not a permanent MFA
20
+ // bypass" is true of the recovery CODES and not of the seed.
21
+ //
22
+ // The two `x_accounts` token columns are kept in the DDL and written `null`: they held live
23
+ // provider credentials in the clear and nothing in this package ever read them back
24
+ // (`oauth-login.ts`'s `accountFor`). The columns stay so an app that deliberately stores tokens
25
+ // through its own `linkAccount` has somewhere to put them, and so an existing deployment needs
26
+ // no migration to stop.
4
27
 
5
28
  export const X_USERS_TABLE = `create table if not exists x_users (
6
29
  id uuid primary key,
@@ -12,6 +35,8 @@ export const X_USERS_TABLE = `create table if not exists x_users (
12
35
  permissions text[] not null default '{}',
13
36
  scopes text[] not null default '{}',
14
37
  external_id text unique,
38
+ -- The base32 TOTP seed, in the clear. A seed is symmetric: a digest cannot verify a code.
39
+ -- Encryption at rest is deferred and needs a key-management seam - see the header.
15
40
  mfa_secret text,
16
41
  recovery_code_hashes text[] not null default '{}',
17
42
  disabled_at timestamptz,
@@ -52,6 +77,8 @@ export const X_ACCOUNTS_TABLE = `create table if not exists x_accounts (
52
77
  user_id uuid not null references x_users (id) on delete cascade,
53
78
  provider text not null,
54
79
  provider_account_id text not null,
80
+ -- Written NULL by the framework. Nothing reads them back, and a live provider credential at
81
+ -- rest turns a database dump into third-party access. Kept for an app's own linkAccount().
55
82
  access_token text,
56
83
  refresh_token text,
57
84
  expires_at timestamptz,
package/src/verify.ts CHANGED
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Clock } from '@ultimat3/core';
7
7
  import type { AuthVerification, VerificationStore } from './adapter';
8
+ import { normaliseEmail } from './email';
8
9
  import { AuthError } from './errors';
9
10
  import { randomToken, sha256Hex, timingSafeEqual } from './tokens';
10
11
 
@@ -68,10 +69,17 @@ export async function issueVerification(
68
69
  const token = randomToken(32);
69
70
  const ttl = input.ttlMs ?? DEFAULT_VERIFICATION_TTL_MS[input.purpose];
70
71
  const expiresAt = new Date(now.getTime() + ttl);
72
+ // The FOURTH identity door, and the one that did not normalise: `register`, `login`,
73
+ // `profileEmail` and `accountKey` all do. `putVerification` upserts on `(purpose, identifier)`
74
+ // and `adapter.ts` promises that "issuing a new token invalidates the previous one" — a promise
75
+ // that was per SPELLING, so N live reset tokens for one address could be held at once by varying
76
+ // the case, and each one of them is a password. It is also the address the mail is sent to, so
77
+ // the link goes to the inbox the account is keyed by rather than to whatever a form posted.
78
+ const identifier = normaliseEmail(input.identifier);
71
79
  await runtime.store.putVerification({
72
80
  id: randomToken(12),
73
81
  purpose: input.purpose,
74
- identifier: input.identifier,
82
+ identifier,
75
83
  tokenHash: sha256Hex(token),
76
84
  expiresAt,
77
85
  consumedAt: null,
@@ -79,7 +87,7 @@ export async function issueVerification(
79
87
  });
80
88
  await runtime.mail.send(
81
89
  VERIFICATION_TEMPLATES[input.purpose],
82
- input.identifier,
90
+ identifier,
83
91
  {
84
92
  ...(input.data ?? {}),
85
93
  link: input.link?.(token) ?? token,
@@ -119,7 +127,13 @@ export async function consumeVerification(
119
127
  input: ConsumeVerificationInput,
120
128
  ): Promise<AuthVerification> {
121
129
  const tokenHash = sha256Hex(input.token);
122
- const record = await runtime.store.takeVerification(input.purpose, input.identifier, tokenHash);
130
+ // Normalised on the way OUT as well as in, or a link issued for `ada@x.test` is unredeemable by
131
+ // a form that posted `Ada@X.test` — one door, one key.
132
+ const record = await runtime.store.takeVerification(
133
+ input.purpose,
134
+ normaliseEmail(input.identifier),
135
+ tokenHash,
136
+ );
123
137
  if (record === null) throw verificationInvalid(input.purpose);
124
138
  // Kept for the seam, not for the blessed adapters: `VerificationStore` is implementable by an
125
139
  // app, and one that ignores the third argument would otherwise redeem any token. Constant-time