@ultimat3/auth 31.2.0 → 31.4.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
@@ -41,6 +41,11 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
41
41
  window, a one-statement take; a live lockout is never rewritten. †
42
42
  - **`installAuthLimiters` (`@ultimat3/auth/adapter`) is the HOST's install point and takes a
43
43
  FACTORY**: `config.limiter` → installed factory → `memoryAuthLimiter`. †
44
+ - **Every installed port is read where it is USED, never captured by `defineAuth`** (`auth-ports.ts`,
45
+ 31.3): `limiter`, `orgLimiter`, `orgRateLimit`, `totpReplay` are getters, rebuilt only when the
46
+ install changes. The boot installs after `runtime.ts` loads; a captured port was per-pod memory
47
+ for life. Installed at construction: judged then; not yet: judged at first use
48
+ (`X_AUTH_LIMITER_NOT_SHARED` there). `limiter-install.test.ts` "installed AFTER defineAuth".
44
49
  - **`normaliseEmail` is the ONE normalisation, ABOVE the `AuthAdapter` seam**: trim + lowercase,
45
50
  never a `+tag` or gmail dot; no adapter folds case. †
46
51
  - **`json.ts` owns `isRecord` and `decodeJwtSegment`; no second copy.** An array is not a record.
@@ -159,12 +164,13 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
159
164
  | `policy-bridge.ts` | the one funnel: identity → `Actor`, all four `ActorKind`s |
160
165
  | `session.ts` | two expiries, rotation, revocation, device list, the cookie |
161
166
  | `adapter.ts` | the seam; `builtin-adapter.ts` (Postgres) + `memory-adapter.ts` |
167
+ | `tables.ts` (`./schema`) | every auth table the boot applies — `AUTH_TABLES`, the limiter and TOTP DDL, and `authorization-server-schema.ts` re-exported. A LEAF: it imports nothing else (`schema-subpath.test.ts`), so `FRAMEWORK_SCHEMA` keeps the barrel off `ROLE=migrate` (`MIGRATE_CEILING`). The per-table constants stay module-private (removed from the API in 22.0.0). Also on `.` |
162
168
  | `adapter-subpath.ts` | `@ultimat3/auth/adapter`: the `authLimiter`/`totpReplay`/`authServerStore` port types, their installers and resets, and `installKdfGate` |
163
169
  | `authorization-server-installed.ts` | the `authServerStore` slot: `authorizationServer()` with no `store` reads it per CALL (never captured: `runtime.ts` may build the server first); empty, Postgres over the ambient pool |
164
170
  | `builtin-adapter-violation.ts` | a Postgres unique violation on an auth table → `authUniqueViolation` |
165
171
  | `rate-limit.ts` | per-ip, per-account and per-org buckets as reservations, lockout, scope check, `loginFailed()` |
166
172
  | `login-attempt.ts` | one attempt's reservations across the three buckets, taken before the check and settled after it |
167
- | `rate-limit-postgres.ts` | the SHARED limiter: one table, one row per key, a one-statement take, over a structural `PgExecutor` |
173
+ | `rate-limit-postgres.ts` | the SHARED limiter: one row per key, a one-statement take, over a structural `PgExecutor`. Its DDL is in `tables.ts` |
168
174
  | `limiter-install.ts` | the host's one install point for that limiter — the factory, what it built, and the purge over it, and the TOTP guard's |
169
175
  | `oauth.ts` | `OAuthProvider`, PKCE, `beginOAuth`, the callback gate. No I/O, no env |
170
176
  | `oauth-builtins.ts` | the two shipped IdPs (`github`, `google`), as data. Imports only the type, so no cycle |
@@ -175,7 +181,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
175
181
  | `jwt-bearer-resolver.ts` | an external bearer JWT → `{ actor, scopes } \| null` |
176
182
  | `revocation.ts` | per-user, per-org and before-an-instant sweeps; `disableUser` (sessions and api keys) |
177
183
  | `mfa-challenge.ts` | the sealed challenge `X_MFA_REQUIRED` carries, and `completeMfa` |
178
- | `mfa-replay-postgres.ts` | the shared replay guard: one table, the claim, the sweep |
184
+ | `mfa-replay-postgres.ts` | the shared replay guard: the claim and the sweep. Its DDL is in `tables.ts` |
179
185
  | `mfa-secret.ts` | the TOTP secret at rest: seal on write, open on read, the one-shot that seals older rows |
180
186
  | `directory.ts` | `describeUser` (allow-list projection), `listOrgUsers`, external-id lookup |
181
187
  | `privileges.ts` | `updatePrivileges` — the grant, the rotation it requires, and the sessions a changed password ends |
@@ -200,6 +206,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
200
206
  | `client-scope.ts` | `clientScopeOf(actor)`, the OPAQUE id for `<meta name="ultimate-scope">`: keyed SHA-256 (`SESSION_SECRET`, else a per-process key and one warning) over kind, id, impersonator; `''` anonymous |
201
207
  | `identity-provider*.ts` | SSO port, `signInWithIdentity`, OIDC adapter, route core, state cookie, status table |
202
208
  | `saml-*.ts` | SAML adapter: strict XML reader, exc-c14n, XML-DSig, response checks, metadata, AuthnRequest |
209
+ | `saml-test-idp.ts` / `saml-test-signer.ts` (`./saml-test-idp`) | the in-process test IdP and its RSA signer, SHIPPED (moved from `*-fixture.ts` in 31.3): this package's SAML suites, `@ultimat3/testing`'s `fakeSamlIdentityProvider` and an app's test sign with the one implementation. Never on `.` |
203
210
 
204
211
  ```bash
205
212
  bun test ./packages/auth/
package/README.md CHANGED
@@ -740,6 +740,17 @@ brought up to date with no hand-run migration. There is nothing to paste: the pe
740
740
  constants and `X_USERS_MIGRATION_1_3` are gone, and a hand-written migration that pasted them
741
741
  should be deleted. They are still not `entity()` declarations, so `x db gen` does not see them.
742
742
 
743
+ **Read the DDL from `@ultimat3/auth/schema`, a leaf — `As of 2026-11-10`.** It exports
744
+ `AUTH_TABLES`, `AUTH_TABLE_NAMES`, `AUTH_SERVER_TABLES`, `SQL_AUTH_SERVER_TABLES`,
745
+ `SQL_AUTH_LIMIT_TABLES` and `SQL_TOTP_REPLAY_TABLE`, and imports no runtime: reading table names
746
+ costs 2 modules, not the barrel's 106. `FRAMEWORK_SCHEMA` reads it there, which took `ROLE=migrate`
747
+ from 977 modules to 873. The `.` barrel still exports the same six values, so a caller that also
748
+ needs `postgresAuthAdapter` or a store keeps one import.
749
+
750
+ ```ts
751
+ import { AUTH_TABLE_NAMES, AUTH_TABLES } from '@ultimat3/auth/schema';
752
+ ```
753
+
743
754
  ## Sessions are not a write path
744
755
 
745
756
  `verifySession` used to `UPDATE x_sessions … RETURNING *` on **every** authenticated request: one
@@ -1042,6 +1053,12 @@ is `X_SAML_METADATA_INVALID` at boot. An id the routes do not serve is `X_IDENTI
1042
1053
  An adapter of your own is held to the same contract by
1043
1054
  `identityProviderConformance` (`@ultimat3/testing/conformance`).
1044
1055
 
1056
+ Testing a SAML sign-in: `fakeSamlIdentityProvider({ audience, users })` from `@ultimat3/testing`
1057
+ answers the AuthnRequest an SP's redirect carries with a signed response, as a chosen user, and `tamper()`s
1058
+ it. It runs over `@ultimat3/auth/saml-test-idp` (`samlTestIdp()`, `readAuthnRequest()`,
1059
+ `encodeResponse()`), the in-process IdP this package's own SAML suites sign with — one signer,
1060
+ one path.
1061
+
1045
1062
  ## API keys — how an agent authenticates
1046
1063
 
1047
1064
  `ult_<env>_<id>_<secret>`. The plaintext is shown once; the row holds `sha256(secret)` and is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/auth",
3
- "version": "31.2.0",
3
+ "version": "31.4.0",
4
4
  "description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -30,6 +30,8 @@
30
30
  ".": "./src/index.ts",
31
31
  "./adapter": "./src/adapter-subpath.ts",
32
32
  "./client": "./src/client.ts",
33
+ "./saml-test-idp": "./src/saml-test-idp.ts",
34
+ "./schema": "./src/tables.ts",
33
35
  "./soft-authenticator": "./src/soft-authenticator.ts"
34
36
  },
35
37
  "files": [
@@ -48,8 +50,8 @@
48
50
  "test": "bun test"
49
51
  },
50
52
  "dependencies": {
51
- "@ultimat3/core": "31.2.0",
52
- "@ultimat3/db": "31.2.0",
53
- "@ultimat3/schema": "31.2.0"
53
+ "@ultimat3/core": "31.4.0",
54
+ "@ultimat3/db": "31.4.0",
55
+ "@ultimat3/schema": "31.4.0"
54
56
  }
55
57
  }
@@ -0,0 +1,104 @@
1
+ // Single responsibility: the credential ports an `Auth` reads — the two limiters and the TOTP
2
+ // replay guard — resolved where they are USED, never captured when `defineAuth` runs. What
3
+ // `defineAuth` was PASSED always wins.
4
+ //
5
+ // Why: the boot installs them after `runtime.ts` loads, and anything `runtime.ts` imports may call
6
+ // `defineAuth` first: captured, that app kept per-pod memory guards for life (lockouts × replicas,
7
+ // a TOTP code or SAML assertion replayable on every other pod).
8
+
9
+ import type { Clock } from '@ultimat3/core';
10
+ import { totpReplayGuardInvalid } from './errors';
11
+ import {
12
+ authLimiterInstall,
13
+ installedAuthLimiter,
14
+ installedTotpReplay,
15
+ totpReplayInstall,
16
+ } from './limiter-install';
17
+ import { memoryTotpReplayGuard, type TotpReplayGuard } from './mfa';
18
+ import {
19
+ type AuthLimiter,
20
+ type AuthRateLimitPolicy,
21
+ assertAuthLimiterPolicy,
22
+ memoryAuthLimiter,
23
+ } from './rate-limit';
24
+
25
+ /**
26
+ * The installed port, rebuilt only when the install changes; else `fallback`, built once. `check`
27
+ * runs on every port built, so a mismatch is refused where it first appears.
28
+ */
29
+ function resolving<F, P>(
30
+ installed: () => F | undefined,
31
+ build: () => P | undefined,
32
+ fallback: () => P,
33
+ ): () => P {
34
+ let from: F | undefined;
35
+ let port: P | undefined;
36
+ let local: P | undefined;
37
+ return () => {
38
+ const current = installed();
39
+ if (current === undefined) {
40
+ local ??= fallback();
41
+ return local;
42
+ }
43
+ if (current !== from || port === undefined) {
44
+ port = build() ?? fallback();
45
+ from = current;
46
+ }
47
+ return port;
48
+ };
49
+ }
50
+
51
+ /** A limiter for `policy`: passed, else installed, else this process' memory. `exempt`: the fallback is not compared. */
52
+ export function limiterPort(
53
+ passed: AuthLimiter | undefined,
54
+ policy: AuthRateLimitPolicy,
55
+ clock: Clock,
56
+ exempt: boolean,
57
+ ): () => AuthLimiter {
58
+ if (passed !== undefined) {
59
+ assertAuthLimiterPolicy(policy, passed);
60
+ return () => passed;
61
+ }
62
+ const checked = (limiter: AuthLimiter): AuthLimiter => {
63
+ assertAuthLimiterPolicy(policy, limiter);
64
+ return limiter;
65
+ };
66
+ const read = resolving(
67
+ authLimiterInstall,
68
+ () => {
69
+ const built = installedAuthLimiter(policy);
70
+ return built === undefined ? undefined : checked(built);
71
+ },
72
+ () => (exempt ? memoryAuthLimiter(clock, policy) : checked(memoryAuthLimiter(clock, policy))),
73
+ );
74
+ // Installed already: built and judged now, so a factory that ignores the policy is refused at
75
+ // `defineAuth` as before. Not installed: judged at first use, after the boot had its chance.
76
+ if (authLimiterInstall() !== undefined) read();
77
+ return read;
78
+ }
79
+
80
+ const validGuard = (guard: TotpReplayGuard): TotpReplayGuard => {
81
+ // Unreachable from TypeScript and reachable from a guard written before `claim`, which would
82
+ // otherwise be found at the first second factor, as a TypeError, on a production sign-in.
83
+ const declared: { readonly claim?: unknown } = guard;
84
+ if (typeof declared.claim !== 'function') throw totpReplayGuardInvalid();
85
+ return guard;
86
+ };
87
+
88
+ /** Where spent TOTP steps (and SAML assertions) are claimed: passed, else installed, else memory. */
89
+ export function totpReplayPort(passed: TotpReplayGuard | undefined): () => TotpReplayGuard {
90
+ if (passed !== undefined) {
91
+ const guard = validGuard(passed);
92
+ return () => guard;
93
+ }
94
+ const read = resolving(
95
+ totpReplayInstall,
96
+ () => {
97
+ const built = installedTotpReplay();
98
+ return built === undefined ? undefined : validGuard(built);
99
+ },
100
+ memoryTotpReplayGuard,
101
+ );
102
+ if (totpReplayInstall() !== undefined) read();
103
+ return read;
104
+ }
package/src/auth.ts CHANGED
@@ -6,12 +6,12 @@
6
6
  import { type Clock, systemClock, timingSafeEqual, uuidV7 } from '@ultimat3/core';
7
7
  import { t } from '@ultimat3/schema';
8
8
  import type { AuthAdapter, AuthSession, AuthUser } from './adapter';
9
+ import { limiterPort, totpReplayPort } from './auth-ports';
9
10
  import { normaliseEmail } from './email';
10
- import { mfaRequiredUnenforceable, sessionUnknown, totpReplayGuardInvalid } from './errors';
11
- import { installedAuthLimiter, installedTotpReplay } from './limiter-install';
11
+ import { mfaRequiredUnenforceable, sessionUnknown } from './errors';
12
12
  import { openLoginAttempt } from './login-attempt';
13
13
  import { type HandleDirectory, loginIdentity } from './login-identity';
14
- import { memoryTotpReplayGuard, type TotpReplayGuard } from './mfa';
14
+ import type { TotpReplayGuard } from './mfa';
15
15
  import { mfaChallengeRequired } from './mfa-challenge';
16
16
  import type { OAuthProviderId } from './oauth';
17
17
  import {
@@ -31,10 +31,8 @@ import { assertPasswordPolicy, assertRateLimitPolicy, assertSessionPolicy } from
31
31
  import {
32
32
  type AuthLimiter,
33
33
  type AuthRateLimitPolicy,
34
- assertAuthLimiterPolicy,
35
34
  DEFAULT_AUTH_RATE_LIMIT,
36
35
  loginFailed,
37
- memoryAuthLimiter,
38
36
  orgRateLimit,
39
37
  } from './rate-limit';
40
38
  import {
@@ -218,23 +216,9 @@ export function defineAuth(config: AuthConfigInput): Auth {
218
216
  // the database connection), then one process' worth of state. Without the middle arm a
219
217
  // scaffolded app had to remember to build a shared limiter itself, which is the opposite of
220
218
  // what this framework promises — and `x new` scaffolds two replicas.
221
- const limiter =
222
- config.limiter ?? installedAuthLimiter(rateLimit) ?? memoryAuthLimiter(clock, rateLimit);
223
- assertAuthLimiterPolicy(rateLimit, limiter);
224
- // The tenant bucket is a noisy-neighbour cap, not a credential-guessing allowance, so an app
225
- // that declares `scope: 'shared'` for its LOCKOUT is not also required to ship a shared limiter
226
- // for this one — per replica it approximates to `orgMaxAttempts × replicas`, which is a
227
- // throughput ceiling and discloses nothing. Only the LOCAL fallback is exempt, and exempting it
228
- // is what buys that: `memoryAuthLimiter` always reports `'process'`, which is the one arm the
229
- // scope check would refuse. A limiter somebody else supplied — injected by the app or built by
230
- // the host's factory — is compared exactly as the general bucket's is, because a factory that
231
- // ignores the policy it was handed otherwise enforces numbers the app never declared while
232
- // `Auth.orgRateLimit` reports the app's. That asymmetry was the whole defect: the same factory
233
- // is refused for one bucket and trusted for the other.
219
+ const limiter = limiterPort(config.limiter, rateLimit, clock, false);
234
220
  const orgLimits = orgRateLimit(rateLimit);
235
- const suppliedOrgLimiter = config.orgLimiter ?? installedAuthLimiter(orgLimits);
236
- const orgLimiter = suppliedOrgLimiter ?? memoryAuthLimiter(clock, orgLimits);
237
- if (suppliedOrgLimiter !== undefined) assertAuthLimiterPolicy(orgLimits, suppliedOrgLimiter);
221
+ const orgLimiter = limiterPort(config.orgLimiter, orgLimits, clock, true);
238
222
  // Read through a widened local on purpose: the field's type is the literal `false`, so this
239
223
  // branch is unreachable from TypeScript and reachable from every JS caller and every config
240
224
  // parsed out of JSON — the same split `invariantColumns()` keeps its Proxy behind a compile
@@ -242,11 +226,9 @@ export function defineAuth(config: AuthConfigInput): Auth {
242
226
  const declaredMfa: { readonly required?: unknown } = config.mfa ?? {};
243
227
  if (declaredMfa.required === true) throw mfaRequiredUnenforceable();
244
228
  const mfa: AuthMfaPolicy = { issuer: config.mfa?.issuer ?? DEFAULT_MFA_ISSUER, required: false };
245
- const totpReplay = config.totpReplay ?? installedTotpReplay() ?? memoryTotpReplayGuard();
246
- // Unreachable from TypeScript and reachable from a guard written before `claim`, which would
247
- // otherwise be found at the first second factor, as a TypeError, on a production sign-in.
248
- const declaredReplay: { readonly claim?: unknown } = totpReplay;
249
- if (typeof declaredReplay.claim !== 'function') throw totpReplayGuardInvalid();
229
+ // Each port is read where it is used (`auth-ports.ts`): the boot installs them after `runtime.ts`
230
+ // loads, so one captured here would be the per-process default for the app's whole life.
231
+ const totpReplay = totpReplayPort(config.totpReplay);
250
232
  const passkeys =
251
233
  config.passkeys === undefined ? undefined : resolvePasskeyPolicy(config.passkeys);
252
234
  return Object.freeze({
@@ -255,13 +237,21 @@ export function defineAuth(config: AuthConfigInput): Auth {
255
237
  sessions: { store: config.adapter, policy: session, clock },
256
238
  password,
257
239
  rateLimit,
258
- limiter,
240
+ get limiter(): AuthLimiter {
241
+ return limiter();
242
+ },
259
243
  // What the limiter in use actually enforces, not the derivation — the two differ in `scope`
260
244
  // exactly when the app declared 'shared' and left this limiter to the default.
261
- orgRateLimit: orgLimiter.policy,
262
- orgLimiter,
245
+ get orgRateLimit(): AuthRateLimitPolicy {
246
+ return orgLimiter().policy;
247
+ },
248
+ get orgLimiter(): AuthLimiter {
249
+ return orgLimiter();
250
+ },
263
251
  mfa,
264
- totpReplay,
252
+ get totpReplay(): TotpReplayGuard {
253
+ return totpReplay();
254
+ },
265
255
  // BREAKING (majors only): the default is `[]`, never the live registry.
266
256
  //
267
257
  // It was `oauthProviderIds()`, so `defineAuth({ providers })`'s own documented purpose — the
package/src/index.ts CHANGED
@@ -75,7 +75,6 @@ export type {
75
75
  export type { PostgresAuthServerStoreOptions } from './authorization-server-postgres';
76
76
  export { postgresAuthServerStore } from './authorization-server-postgres';
77
77
  export type { ReadRequestResult } from './authorization-server-request';
78
- export { AUTH_SERVER_TABLES, SQL_AUTH_SERVER_TABLES } from './authorization-server-schema';
79
78
  export type { AuthServerStore } from './authorization-server-store';
80
79
  export { memoryAuthServerStore } from './authorization-server-store';
81
80
  export type {
@@ -212,7 +211,7 @@ export type {
212
211
  PostgresTotpReplayGuard,
213
212
  PostgresTotpReplayGuardOptions,
214
213
  } from './mfa-replay-postgres';
215
- export { postgresTotpReplayGuard, SQL_TOTP_REPLAY_TABLE } from './mfa-replay-postgres';
214
+ export { postgresTotpReplayGuard } from './mfa-replay-postgres';
216
215
  export type { MfaSecretStore, SealMfaSecretsReport } from './mfa-secret';
217
216
  export {
218
217
  countUnsealedMfaSecrets,
@@ -369,10 +368,7 @@ export {
369
368
  orgRateLimit,
370
369
  } from './rate-limit';
371
370
  export type { PostgresAuthLimiter, PostgresAuthLimiterOptions } from './rate-limit-postgres';
372
- export {
373
- postgresAuthLimiter,
374
- SQL_AUTH_LIMIT_TABLES,
375
- } from './rate-limit-postgres';
371
+ export { postgresAuthLimiter } from './rate-limit-postgres';
376
372
  export type { DisabledUser } from './revocation';
377
373
  export {
378
374
  disableUser,
@@ -419,9 +415,14 @@ export type {
419
415
  } from './subject-target';
420
416
  export { authSubjectTarget } from './subject-target';
421
417
 
418
+ /** Also `@ultimat3/auth/schema`, the leaf a schema reader imports instead of this barrel. */
422
419
  export {
420
+ AUTH_SERVER_TABLES,
423
421
  AUTH_TABLE_NAMES,
424
422
  AUTH_TABLES,
423
+ SQL_AUTH_LIMIT_TABLES,
424
+ SQL_AUTH_SERVER_TABLES,
425
+ SQL_TOTP_REPLAY_TABLE,
425
426
  } from './tables';
426
427
  export {
427
428
  randomToken,
@@ -149,3 +149,16 @@ export function resetTotpReplay(): void {
149
149
  export function installedTotpReplay(): TotpReplayGuard | undefined {
150
150
  return replayFactory.current()?.();
151
151
  }
152
+
153
+ /**
154
+ * The installed limiter FACTORY itself, so a reader can tell one install from the next and rebuild
155
+ * only then (`auth-ports.ts`). Not exported from `src/index.ts`, for `installedAuthLimiter`'s reason.
156
+ */
157
+ export function authLimiterInstall(): AuthLimiterFactory | undefined {
158
+ return factory.current();
159
+ }
160
+
161
+ /** The installed TOTP replay factory, for `authLimiterInstall`'s reason. */
162
+ export function totpReplayInstall(): TotpReplayFactory | undefined {
163
+ return replayFactory.current();
164
+ }
@@ -4,18 +4,6 @@
4
4
  import type { PgExecutor } from '@ultimat3/core';
5
5
  import { TOTP_DRIFT_STEPS, type TotpReplayGuard, totpStep } from './mfa';
6
6
 
7
- /** Applied by the boot, never by an app migration: `SQL_AUTH_LIMIT_TABLES`' rule. */
8
- export const SQL_TOTP_REPLAY_TABLE = `
9
- create table if not exists x_totp_steps (
10
- subject text not null,
11
- step bigint not null,
12
- used_at timestamptz not null,
13
- primary key (subject, step)
14
- );
15
-
16
- create index if not exists x_totp_steps_step_idx on x_totp_steps (step);
17
- `;
18
-
19
7
  /** `$1` subject, `$2` step, `$3` the caller's clock. A row back is the first use; none, a replay. */
20
8
  export const SQL_TOTP_CLAIM = `
21
9
  insert into x_totp_steps (subject, step, used_at)
@@ -6,35 +6,6 @@ import type { Clock, PgExecutor } from '@ultimat3/core';
6
6
  import { accountLocked, authWriteFailed } from './errors';
7
7
  import type { AuthLimiter, AuthRateLimitPolicy, AuthReservation } from './rate-limit';
8
8
 
9
- /**
10
- * Applied by the boot, never by an app migration — the rule `SQL_IDEMPOTENCY_TABLE` follows, so
11
- * `x dev`, the container's `web` role and `ROLE=migrate` all install it.
12
- *
13
- * ONE row per key, holding every attempt still inside the window. The window this package enforces
14
- * is a SLIDING one, so the instants are kept (a counter plus a window end is a fixed window, which
15
- * admits `maxAttempts` at the end of one and `maxAttempts` again at the start of the next). They
16
- * are kept IN the row because the row is what a concurrent take waits on: a count over a second
17
- * table reads its statement's snapshot, and that snapshot predates the wait.
18
- *
19
- * The two `add column` lines are the upgrade of a table made before the reservation, on the rule
20
- * `x_users` follows: additive, defaulted, idempotent, applied at every boot. The name and the
21
- * first two columns are unchanged on purpose — a replica still running the previous release reads
22
- * and writes this table as it always did, so a lockout holds on both sides of a rolling deploy.
23
- */
24
- export const SQL_AUTH_LIMIT_TABLES = `
25
- create table if not exists x_auth_lockouts (
26
- key text primary key,
27
- locked_until_ms bigint not null,
28
- attempts_ms bigint[] not null default '{}',
29
- admitted boolean not null default true
30
- );
31
-
32
- alter table x_auth_lockouts add column if not exists attempts_ms bigint[] not null default '{}';
33
- alter table x_auth_lockouts add column if not exists admitted boolean not null default true;
34
-
35
- create index if not exists x_auth_lockouts_until_idx on x_auth_lockouts (locked_until_ms);
36
- `;
37
-
38
9
  /**
39
10
  * The attempts still inside the window, read off the row as it is AFTER its lock is taken. It is
40
11
  * repeated in the statement below rather than computed once in a CTE, and the repetition is
@@ -0,0 +1,189 @@
1
+ // TEST TOOL, shipped as `@ultimat3/auth/saml-test-idp`. A SAML IdP in-process: metadata, and signed
2
+ // responses written DIRECTLY in canonical form — every namespace declared where exc-c14n renders it,
3
+ // attributes pre-sorted, no empty-tag shorthand — so the digest is SHA-256 of the literal string and
4
+ // the signer never calls the `saml-c14n.ts` it is testing.
5
+ //
6
+ // This package's suites, `@ultimat3/testing`'s `fakeSamlIdentityProvider` and an app's sign-in test
7
+ // share it: one signer, one path.
8
+
9
+ import { finiteOption } from '@ultimat3/core';
10
+ import { c14nAttribute, c14nText } from './saml-c14n';
11
+ import {
12
+ BEARER,
13
+ DSIG_NS,
14
+ ENVELOPED,
15
+ EXC_C14N,
16
+ MD_NS,
17
+ NAMEID_PERSISTENT,
18
+ RSA_SHA256,
19
+ SAML_NS,
20
+ SAMLP_NS,
21
+ SHA256,
22
+ STATUS_SUCCESS,
23
+ } from './saml-dom';
24
+ import { parseSamlMetadata, type SamlIdpMetadata } from './saml-metadata';
25
+ import { type TestRsaSigner, testRsaSigner } from './saml-test-signer';
26
+
27
+ export type { TestRsaSigner } from './saml-test-signer';
28
+ export { testRsaSigner } from './saml-test-signer';
29
+
30
+ export const TEST_IDP_ENTITY_ID = 'https://idp.example.test/metadata';
31
+ export const TEST_IDP_SSO_URL = 'https://idp.example.test/sso';
32
+
33
+ export interface TestResponseSpec {
34
+ readonly requestId: string;
35
+ readonly acsUrl: string;
36
+ readonly audience: string;
37
+ readonly now: Date;
38
+ readonly nameId?: string;
39
+ readonly nameIdFormat?: string;
40
+ /** `null` omits the email attribute. */
41
+ readonly email?: string | null;
42
+ /** The `displayName` attribute; default `Ada Lovelace`, `null` omits it. */
43
+ readonly name?: string | null;
44
+ /** The confirmation's Recipient alone; default `acsUrl`. */
45
+ readonly recipient?: string;
46
+ readonly issuer?: string;
47
+ readonly assertionId?: string;
48
+ readonly lifetimeMs?: number;
49
+ readonly notBefore?: Date;
50
+ readonly status?: string;
51
+ readonly signAssertion?: boolean;
52
+ readonly signResponse?: boolean;
53
+ readonly signer?: TestRsaSigner;
54
+ readonly digestAlgorithm?: string;
55
+ }
56
+
57
+ export interface TestIdp {
58
+ readonly signer: TestRsaSigner;
59
+ readonly metadataXml: string;
60
+ readonly idp: SamlIdpMetadata;
61
+ /** The response document, in canonical form. Tamper with it, then `encode` it. */
62
+ responseXml(spec: TestResponseSpec): Promise<string>;
63
+ respond(spec: TestResponseSpec): Promise<string>;
64
+ }
65
+
66
+ export const encodeResponse = (xml: string): string =>
67
+ btoa(String.fromCharCode(...new TextEncoder().encode(xml)));
68
+
69
+ /** Text and attribute values in canonical form: the spec's tables, shared with the verifier. */
70
+ const esc = c14nText;
71
+ const escAttr = c14nAttribute;
72
+ const at = (date: Date): string => `${date.toISOString().slice(0, 19)}Z`;
73
+ const randomId = (): string => `_${crypto.randomUUID().replaceAll('-', '')}`;
74
+
75
+ async function sha256Base64(value: string): Promise<string> {
76
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
77
+ return btoa(String.fromCharCode(...new Uint8Array(digest)));
78
+ }
79
+
80
+ /** `<ds:Signature>` for the canonical `signed` (which carries ID `id`), in canonical form. */
81
+ async function signatureFor(signed: string, id: string, signer: TestRsaSigner, digestAlg: string) {
82
+ const body =
83
+ `<ds:CanonicalizationMethod Algorithm="${EXC_C14N}"></ds:CanonicalizationMethod>` +
84
+ `<ds:SignatureMethod Algorithm="${RSA_SHA256}"></ds:SignatureMethod>` +
85
+ `<ds:Reference URI="#${id}"><ds:Transforms>` +
86
+ `<ds:Transform Algorithm="${ENVELOPED}"></ds:Transform>` +
87
+ `<ds:Transform Algorithm="${EXC_C14N}"></ds:Transform></ds:Transforms>` +
88
+ `<ds:DigestMethod Algorithm="${digestAlg}"></ds:DigestMethod>` +
89
+ `<ds:DigestValue>${await sha256Base64(signed)}</ds:DigestValue></ds:Reference>`;
90
+ const value = await signer.sign(`<ds:SignedInfo xmlns:ds="${DSIG_NS}">${body}</ds:SignedInfo>`);
91
+ return (
92
+ `<ds:Signature xmlns:ds="${DSIG_NS}"><ds:SignedInfo>${body}</ds:SignedInfo>` +
93
+ `<ds:SignatureValue>${value}</ds:SignatureValue><ds:KeyInfo><ds:X509Data>` +
94
+ `<ds:X509Certificate>${signer.certificate}</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature>`
95
+ );
96
+ }
97
+
98
+ /** Splice the signature in right after the element's first `</saml:Issuer>`. */
99
+ const envelop = (canonical: string, signature: string): string =>
100
+ canonical.replace('</saml:Issuer>', `</saml:Issuer>${signature}`);
101
+
102
+ function assertionXml(spec: TestResponseSpec, id: string): string {
103
+ // Negative is legal — an already-expired assertion is a case a test signs — so finite, not a count.
104
+ const lifetimeMs = finiteOption('samlTestIdp', 'lifetimeMs', spec.lifetimeMs ?? 300_000);
105
+ const notOnOrAfter = at(new Date(spec.now.getTime() + lifetimeMs));
106
+ const notBefore = at(spec.notBefore ?? new Date(spec.now.getTime() - 30_000));
107
+ const email = spec.email === undefined ? 'ada@corp.example' : spec.email;
108
+ const emailAttribute =
109
+ email === null
110
+ ? ''
111
+ : `<saml:Attribute Name="email"><saml:AttributeValue>${esc(email)}</saml:AttributeValue></saml:Attribute>`;
112
+ const name = spec.name === undefined ? 'Ada Lovelace' : spec.name;
113
+ const nameAttribute =
114
+ name === null
115
+ ? ''
116
+ : `<saml:Attribute Name="displayName"><saml:AttributeValue>${esc(name)}</saml:AttributeValue></saml:Attribute>`;
117
+ return (
118
+ `<saml:Assertion xmlns:saml="${SAML_NS}" ID="${id}" IssueInstant="${at(spec.now)}" Version="2.0">` +
119
+ `<saml:Issuer>${esc(spec.issuer ?? TEST_IDP_ENTITY_ID)}</saml:Issuer><saml:Subject>` +
120
+ `<saml:NameID Format="${spec.nameIdFormat ?? NAMEID_PERSISTENT}">${esc(spec.nameId ?? 'u-1001')}</saml:NameID>` +
121
+ `<saml:SubjectConfirmation Method="${BEARER}"><saml:SubjectConfirmationData InResponseTo="${escAttr(spec.requestId)}"` +
122
+ ` NotOnOrAfter="${notOnOrAfter}" Recipient="${escAttr(spec.recipient ?? spec.acsUrl)}"></saml:SubjectConfirmationData>` +
123
+ `</saml:SubjectConfirmation></saml:Subject><saml:Conditions NotBefore="${notBefore}" NotOnOrAfter="${notOnOrAfter}">` +
124
+ `<saml:AudienceRestriction><saml:Audience>${esc(spec.audience)}</saml:Audience></saml:AudienceRestriction>` +
125
+ `</saml:Conditions><saml:AuthnStatement AuthnInstant="${at(spec.now)}" SessionIndex="s-1">` +
126
+ '<saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password' +
127
+ '</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement><saml:AttributeStatement>' +
128
+ emailAttribute +
129
+ nameAttribute +
130
+ '</saml:AttributeStatement></saml:Assertion>'
131
+ );
132
+ }
133
+
134
+ export async function samlTestIdp(signer?: TestRsaSigner): Promise<TestIdp> {
135
+ const own = signer ?? (await testRsaSigner());
136
+ const metadataXml =
137
+ `<md:EntityDescriptor xmlns:md="${MD_NS}" xmlns:ds="${DSIG_NS}" entityID="${TEST_IDP_ENTITY_ID}">` +
138
+ '<md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">' +
139
+ `<md:KeyDescriptor use="signing"><ds:KeyInfo><ds:X509Data><ds:X509Certificate>\n${own.certificate}\n` +
140
+ '</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor>' +
141
+ '<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://idp.example.test/post"/>' +
142
+ `<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="${TEST_IDP_SSO_URL}"/>` +
143
+ '</md:IDPSSODescriptor></md:EntityDescriptor>';
144
+
145
+ const responseXml = async (spec: TestResponseSpec): Promise<string> => {
146
+ const key = spec.signer ?? own;
147
+ const digestAlg = spec.digestAlgorithm ?? SHA256;
148
+ const assertionId = spec.assertionId ?? randomId();
149
+ let assertion = assertionXml(spec, assertionId);
150
+ if (spec.signAssertion ?? true) {
151
+ assertion = envelop(assertion, await signatureFor(assertion, assertionId, key, digestAlg));
152
+ }
153
+ // Inside the response, the saml prefix is already rendered by... nobody: Response does not
154
+ // use it, so exc-c14n renders it on the Issuer and the Assertion — exactly as written here.
155
+ const id = randomId();
156
+ const response =
157
+ `<samlp:Response xmlns:samlp="${SAMLP_NS}" Destination="${escAttr(spec.acsUrl)}" ID="${id}"` +
158
+ ` InResponseTo="${escAttr(spec.requestId)}" IssueInstant="${at(spec.now)}" Version="2.0">` +
159
+ `<saml:Issuer xmlns:saml="${SAML_NS}">${esc(spec.issuer ?? TEST_IDP_ENTITY_ID)}</saml:Issuer>` +
160
+ `<samlp:Status><samlp:StatusCode Value="${spec.status ?? STATUS_SUCCESS}"></samlp:StatusCode></samlp:Status>` +
161
+ `${assertion}</samlp:Response>`;
162
+ return spec.signResponse === true
163
+ ? envelop(response, await signatureFor(response, id, key, digestAlg))
164
+ : response;
165
+ };
166
+
167
+ return {
168
+ signer: own,
169
+ metadataXml,
170
+ idp: parseSamlMetadata(metadataXml),
171
+ responseXml,
172
+ respond: async (spec) => encodeResponse(await responseXml(spec)),
173
+ };
174
+ }
175
+
176
+ /** What `samlAuthnRequest` put on the redirect: inflated, so a test can answer it. */
177
+ export function readAuthnRequest(location: string): {
178
+ id: string;
179
+ relayState: string;
180
+ xml: string;
181
+ } {
182
+ const url = new URL(location);
183
+ const deflated = Uint8Array.from(atob(url.searchParams.get('SAMLRequest') ?? ''), (c) =>
184
+ c.charCodeAt(0),
185
+ );
186
+ const xml = new TextDecoder().decode(Bun.inflateSync(deflated));
187
+ const id = /\bID="([^"]+)"/.exec(xml)?.[1] ?? '';
188
+ return { id, relayState: url.searchParams.get('RelayState') ?? '', xml };
189
+ }
@@ -0,0 +1,67 @@
1
+ // TEST TOOL, `saml-test-idp.ts`'s signer. An RSA-2048 key pair and a self-signed X.509 certificate
2
+ // for it, minted in-process with Web Crypto and hand-written DER: what a SAML IdP's metadata
3
+ // publishes and signs with.
4
+
5
+ export interface TestRsaSigner {
6
+ /** Base64 DER, as `<ds:X509Certificate>` carries it. */
7
+ readonly certificate: string;
8
+ sign(data: string): Promise<string>;
9
+ }
10
+
11
+ const concat = (parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {
12
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
13
+ let at = 0;
14
+ for (const part of parts) {
15
+ out.set(part, at);
16
+ at += part.length;
17
+ }
18
+ return out;
19
+ };
20
+
21
+ const lengthOf = (n: number): Uint8Array =>
22
+ n < 0x80 ? Uint8Array.of(n) : n < 0x100 ? Uint8Array.of(0x81, n) : Uint8Array.of(0x82, n >> 8, n);
23
+ const tlv = (tag: number, ...parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {
24
+ const body = concat(parts);
25
+ return concat([Uint8Array.of(tag), lengthOf(body.length), body]);
26
+ };
27
+ const seq = (...parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => tlv(0x30, ...parts);
28
+ const text = (value: string): Uint8Array => new TextEncoder().encode(value);
29
+
30
+ /** sha256WithRSAEncryption, NULL parameters. */
31
+ const SHA256_RSA = seq(
32
+ Uint8Array.of(0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b),
33
+ Uint8Array.of(0x05, 0x00),
34
+ );
35
+ const COMMON_NAME = Uint8Array.of(0x06, 0x03, 0x55, 0x04, 0x03);
36
+ const NAME = seq(tlv(0x31, seq(COMMON_NAME, tlv(0x0c, text('test-idp')))));
37
+ const VALIDITY = seq(tlv(0x17, text('000101000000Z')), tlv(0x18, text('20991231235959Z')));
38
+
39
+ const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
40
+
41
+ export async function testRsaSigner(): Promise<TestRsaSigner> {
42
+ const algorithm = {
43
+ name: 'RSASSA-PKCS1-v1_5',
44
+ modulusLength: 2048,
45
+ publicExponent: Uint8Array.of(1, 0, 1),
46
+ hash: 'SHA-256',
47
+ };
48
+ const pair = await crypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
49
+ const spki = new Uint8Array(await crypto.subtle.exportKey('spki', pair.publicKey));
50
+ const tbs = seq(
51
+ tlv(0xa0, tlv(0x02, Uint8Array.of(2))),
52
+ tlv(0x02, Uint8Array.of(1)),
53
+ SHA256_RSA,
54
+ NAME,
55
+ VALIDITY,
56
+ NAME,
57
+ spki,
58
+ );
59
+ const signRaw = async (data: Uint8Array<ArrayBuffer>): Promise<Uint8Array> =>
60
+ new Uint8Array(await crypto.subtle.sign('RSASSA-PKCS1-v1_5', pair.privateKey, data));
61
+ const signature = await signRaw(tbs);
62
+ const certificate = seq(tbs, SHA256_RSA, tlv(0x03, Uint8Array.of(0), signature));
63
+ return {
64
+ certificate: base64(certificate),
65
+ sign: async (data) => base64(await signRaw(new TextEncoder().encode(data))),
66
+ };
67
+ }
package/src/tables.ts CHANGED
@@ -1,7 +1,11 @@
1
- // Single responsibility: the DDL `PostgresAuthAdapter` expects, as `AUTH_TABLES` — applied at every boot
2
- // by `@ultimat3/cli`'s `FRAMEWORK_SCHEMA`, upgrades of an older table included. Plain strings, so
3
- // what auth stores is verifiable by reading, never by trusting. There is nothing to paste into a
4
- // migration any more: the per-table exports and `X_USERS_MIGRATION_1_3` are gone (22.0.0).
1
+ // Single responsibility: every auth table the boot applies, and nothing else — shipped as the LEAF
2
+ // `@ultimat3/auth/schema`, so `@ultimat3/cli`'s `FRAMEWORK_SCHEMA` reads the DDL in every role
3
+ // (`ROLE=migrate` first) without the barrel. Imports only its sibling leaf; `schema-subpath.test.ts`
4
+ // refuses anything more. Plain strings: what auth stores is verifiable by reading, never by trusting.
5
+ //
6
+ // `AUTH_TABLES` is the DDL `PostgresAuthAdapter` expects, upgrades of an older table included.
7
+ // There is nothing to paste into a migration: the per-table exports and `X_USERS_MIGRATION_1_3`
8
+ // are gone (22.0.0), and the per-table constants below stay module-private for that reason.
5
9
  //
6
10
  // What is at rest, stated column by column rather than as a claim:
7
11
  //
@@ -25,7 +29,7 @@
25
29
  // through its own `linkAccount` has somewhere to put them, and so an existing deployment needs
26
30
  // no migration to stop.
27
31
 
28
- export const X_USERS_TABLE = `create table if not exists x_users (
32
+ const X_USERS_TABLE = `create table if not exists x_users (
29
33
  id uuid primary key,
30
34
  email text not null unique,
31
35
  email_verified_at timestamptz,
@@ -58,7 +62,7 @@ const X_USERS_UPGRADE = [
58
62
  ].join(';\n');
59
63
 
60
64
  // `id` is the public half of the cookie; `token_hash` is sha256 of the secret half.
61
- export const X_SESSIONS_TABLE = `create table if not exists x_sessions (
65
+ const X_SESSIONS_TABLE = `create table if not exists x_sessions (
62
66
  id text primary key,
63
67
  user_id uuid not null references x_users (id) on delete cascade,
64
68
  token_hash text not null,
@@ -73,7 +77,7 @@ create index if not exists x_sessions_user_id_idx on x_sessions (user_id);
73
77
  create index if not exists x_sessions_absolute_expires_at_idx on x_sessions (absolute_expires_at);
74
78
  create index if not exists x_sessions_created_at_idx on x_sessions (created_at)`;
75
79
 
76
- export const X_ACCOUNTS_TABLE = `create table if not exists x_accounts (
80
+ const X_ACCOUNTS_TABLE = `create table if not exists x_accounts (
77
81
  id uuid primary key,
78
82
  user_id uuid not null references x_users (id) on delete cascade,
79
83
  provider text not null,
@@ -88,7 +92,7 @@ export const X_ACCOUNTS_TABLE = `create table if not exists x_accounts (
88
92
  )`;
89
93
 
90
94
  // One live token per (purpose, identifier): issuing a new one overwrites the old.
91
- export const X_VERIFICATIONS_TABLE = `create table if not exists x_verifications (
95
+ const X_VERIFICATIONS_TABLE = `create table if not exists x_verifications (
92
96
  id text primary key,
93
97
  purpose text not null,
94
98
  identifier text not null,
@@ -99,7 +103,7 @@ export const X_VERIFICATIONS_TABLE = `create table if not exists x_verifications
99
103
  unique (purpose, identifier)
100
104
  )`;
101
105
 
102
- export const X_API_KEYS_TABLE = `create table if not exists x_api_keys (
106
+ const X_API_KEYS_TABLE = `create table if not exists x_api_keys (
103
107
  id text primary key,
104
108
  prefix text not null unique,
105
109
  key_hash text not null,
@@ -114,7 +118,7 @@ export const X_API_KEYS_TABLE = `create table if not exists x_api_keys (
114
118
 
115
119
  // Passkeys (`passkey-*.ts`). Byte fields are base64url text; the challenge row holds the
116
120
  // challenge's sha256, never the challenge; evidence carries its own key so it verifies alone.
117
- export const X_PASSKEYS_TABLE = `create table if not exists x_passkeys (
121
+ const X_PASSKEYS_TABLE = `create table if not exists x_passkeys (
118
122
  id text primary key,
119
123
  user_id uuid not null references x_users (id) on delete cascade,
120
124
  public_key text not null,
@@ -126,7 +130,7 @@ export const X_PASSKEYS_TABLE = `create table if not exists x_passkeys (
126
130
  );
127
131
  create index if not exists x_passkeys_user_id_idx on x_passkeys (user_id)`;
128
132
 
129
- export const X_PASSKEY_CHALLENGES_TABLE = `create table if not exists x_passkey_challenges (
133
+ const X_PASSKEY_CHALLENGES_TABLE = `create table if not exists x_passkey_challenges (
130
134
  id text primary key,
131
135
  ceremony text not null,
132
136
  user_id uuid references x_users (id) on delete cascade,
@@ -137,7 +141,7 @@ export const X_PASSKEY_CHALLENGES_TABLE = `create table if not exists x_passkey_
137
141
  );
138
142
  create index if not exists x_passkey_challenges_expires_at_idx on x_passkey_challenges (expires_at)`;
139
143
 
140
- export const X_PASSKEY_EVIDENCE_TABLE = `create table if not exists x_passkey_evidence (
144
+ const X_PASSKEY_EVIDENCE_TABLE = `create table if not exists x_passkey_evidence (
141
145
  id text primary key,
142
146
  user_id uuid not null references x_users (id) on delete cascade,
143
147
  credential_id text not null,
@@ -175,3 +179,49 @@ export const AUTH_TABLE_NAMES: readonly string[] = Object.freeze([
175
179
  'x_passkey_challenges',
176
180
  'x_passkey_evidence',
177
181
  ]);
182
+
183
+ /**
184
+ * `postgresAuthLimiter`'s table (`rate-limit-postgres.ts`).
185
+ *
186
+ * Applied by the boot, never by an app migration — the rule `SQL_IDEMPOTENCY_TABLE` follows, so
187
+ * `x dev`, the container's `web` role and `ROLE=migrate` all install it.
188
+ *
189
+ * ONE row per key, holding every attempt still inside the window. The window this package enforces
190
+ * is a SLIDING one, so the instants are kept (a counter plus a window end is a fixed window, which
191
+ * admits `maxAttempts` at the end of one and `maxAttempts` again at the start of the next). They
192
+ * are kept IN the row because the row is what a concurrent take waits on: a count over a second
193
+ * table reads its statement's snapshot, and that snapshot predates the wait.
194
+ *
195
+ * The two `add column` lines are the upgrade of a table made before the reservation, on the rule
196
+ * `x_users` follows: additive, defaulted, idempotent, applied at every boot. The name and the
197
+ * first two columns are unchanged on purpose — a replica still running the previous release reads
198
+ * and writes this table as it always did, so a lockout holds on both sides of a rolling deploy.
199
+ */
200
+ export const SQL_AUTH_LIMIT_TABLES = `
201
+ create table if not exists x_auth_lockouts (
202
+ key text primary key,
203
+ locked_until_ms bigint not null,
204
+ attempts_ms bigint[] not null default '{}',
205
+ admitted boolean not null default true
206
+ );
207
+
208
+ alter table x_auth_lockouts add column if not exists attempts_ms bigint[] not null default '{}';
209
+ alter table x_auth_lockouts add column if not exists admitted boolean not null default true;
210
+
211
+ create index if not exists x_auth_lockouts_until_idx on x_auth_lockouts (locked_until_ms);
212
+ `;
213
+
214
+ /** `postgresTotpReplayGuard`'s spent steps (`mfa-replay-postgres.ts`). Applied by the boot, likewise. */
215
+ export const SQL_TOTP_REPLAY_TABLE = `
216
+ create table if not exists x_totp_steps (
217
+ subject text not null,
218
+ step bigint not null,
219
+ used_at timestamptz not null,
220
+ primary key (subject, step)
221
+ );
222
+
223
+ create index if not exists x_totp_steps_step_idx on x_totp_steps (step);
224
+ `;
225
+
226
+ /** The authorization server's five tables: their own leaf, re-exported so `./schema` is one import. */
227
+ export { AUTH_SERVER_TABLES, SQL_AUTH_SERVER_TABLES } from './authorization-server-schema';