@pithy-sh/auth 0.16.0 → 0.17.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.
Files changed (59) hide show
  1. package/dist/capability.d.ts +9 -6
  2. package/dist/capability.d.ts.map +1 -1
  3. package/dist/capability.js +4 -2
  4. package/dist/data/tables.d.ts +1 -0
  5. package/dist/data/tables.d.ts.map +1 -1
  6. package/dist/data/userLifecycle.d.ts +1 -0
  7. package/dist/data/userLifecycle.d.ts.map +1 -1
  8. package/dist/data/userLifecycle.js +3 -2
  9. package/dist/hooks/runtime.d.ts +32 -0
  10. package/dist/hooks/runtime.d.ts.map +1 -0
  11. package/dist/hooks/runtime.js +25 -0
  12. package/dist/http/adminRoutes.d.ts.map +1 -1
  13. package/dist/http/adminRoutes.js +4 -2
  14. package/dist/http/resolve.d.ts.map +1 -1
  15. package/dist/http/resolve.js +2 -1
  16. package/dist/http/responses.d.ts +3 -0
  17. package/dist/http/responses.d.ts.map +1 -1
  18. package/dist/http/responses.js +2 -1
  19. package/dist/lifecycle/erasure.d.ts.map +1 -1
  20. package/dist/lifecycle/erasure.js +2 -1
  21. package/dist/lifecycle/hooks.d.ts +18 -10
  22. package/dist/lifecycle/hooks.d.ts.map +1 -1
  23. package/dist/lifecycle/request.d.ts +2 -1
  24. package/dist/lifecycle/request.d.ts.map +1 -1
  25. package/dist/lifecycle/request.js +4 -1
  26. package/dist/lifecycle/transitions.d.ts +24 -16
  27. package/dist/lifecycle/transitions.d.ts.map +1 -1
  28. package/dist/lifecycle/transitions.js +27 -16
  29. package/dist/migrations/0011_retained_basis_key.d.ts +10 -0
  30. package/dist/migrations/0011_retained_basis_key.d.ts.map +1 -0
  31. package/dist/migrations/0011_retained_basis_key.js +18 -0
  32. package/dist/migrations/set.d.ts +1 -0
  33. package/dist/migrations/set.d.ts.map +1 -1
  34. package/dist/migrations/set.js +3 -1
  35. package/dist/purge/run.d.ts +11 -11
  36. package/dist/purge/run.d.ts.map +1 -1
  37. package/dist/purge/run.js +9 -8
  38. package/dist/purge/workflow.d.ts +7 -1
  39. package/dist/purge/workflow.d.ts.map +1 -1
  40. package/dist/purge/workflow.js +6 -2
  41. package/dist/version.generated.d.ts +1 -1
  42. package/dist/version.generated.js +1 -1
  43. package/docs/account-lifecycle.md +46 -10
  44. package/package.json +5 -5
  45. package/src/capability.ts +21 -8
  46. package/src/data/userLifecycle.ts +9 -2
  47. package/src/hooks/runtime.ts +41 -0
  48. package/src/http/adminRoutes.ts +14 -7
  49. package/src/http/resolve.ts +8 -4
  50. package/src/http/responses.ts +7 -1
  51. package/src/lifecycle/erasure.ts +2 -1
  52. package/src/lifecycle/hooks.ts +22 -10
  53. package/src/lifecycle/request.ts +4 -1
  54. package/src/lifecycle/transitions.ts +47 -28
  55. package/src/migrations/0011_retained_basis_key.ts +19 -0
  56. package/src/migrations/set.ts +2 -0
  57. package/src/purge/run.ts +29 -17
  58. package/src/purge/workflow.ts +7 -3
  59. package/src/version.generated.ts +1 -1
package/src/capability.ts CHANGED
@@ -23,6 +23,7 @@ import { type AttestationVerifiers, PLATFORM_VERIFIERS } from "./attestation/ver
23
23
  import { AuthAuditActions } from "./audit/actions";
24
24
  import type { AuthClientProjection } from "./client/projection";
25
25
  import { authTables } from "./data/tables";
26
+ import type { HookRuntime } from "./hooks/runtime";
26
27
  import { baseURLResolver } from "./http/baseUrl";
27
28
  import { publishSameOrigin } from "./http/csrf";
28
29
  import { registerDevLoginRoute } from "./http/devLoginRoute";
@@ -308,9 +309,15 @@ export type ScopeResolver = (
308
309
  * **Handed this request's D1 binding**, because the auth instance is built per request and the listener
309
310
  * almost certainly wants to write to the same database under a different capability's view of it. Taking
310
311
  * the binding rather than a typed database keeps this seam out of the business of knowing whose tables
311
- * the listener is about to touch.
312
+ * the listener is about to touch. **And handed the request's runtime**: its env, typed as `auth<Env>()` names
313
+ * it, and its `waitUntil`, so the listener can reach another binding or keep work running past the response.
314
+ * A listener that takes only `(session, d1)` is still one.
312
315
  */
313
- export type SessionRevokedListener = (session: { id: string; userId: string }, d1: D1Database) => Promise<void>;
316
+ export type SessionRevokedListener<Env = Record<string, unknown>> = (
317
+ session: { id: string; userId: string },
318
+ d1: D1Database,
319
+ runtime: HookRuntime<Env>,
320
+ ) => Promise<void>;
314
321
 
315
322
  /**
316
323
  * What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
@@ -320,8 +327,8 @@ export type SessionRevokedListener = (session: { id: string; userId: string }, d
320
327
  * `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
321
328
  * destructured off before the parse.
322
329
  */
323
- export type AuthOptions = AuthConfigInput &
324
- UserLifecycleHooks & {
330
+ export type AuthOptions<Env = Record<string, unknown>> = AuthConfigInput &
331
+ UserLifecycleHooks<Env> & {
325
332
  /**
326
333
  * Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
327
334
  *
@@ -352,7 +359,7 @@ export type AuthOptions = AuthConfigInput &
352
359
  *
353
360
  * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
354
361
  */
355
- onSessionRevoked?: SessionRevokedListener;
362
+ onSessionRevoked?: SessionRevokedListener<Env>;
356
363
  /**
357
364
  * Decide, per request, what this request's caller is — and so which scope gates it opens.
358
365
  *
@@ -468,7 +475,7 @@ export function attestationProjection(
468
475
  * `AuthContext` seam. Depends on `secrets` and `email`; auto-gates its send routes with `turnstile`
469
476
  * and emits `auth/*` through `audit` when those are composed.
470
477
  */
471
- export function auth(options: AuthOptions): AuthCapability {
478
+ export function auth<Env = Record<string, unknown>>(options: AuthOptions<Env>): AuthCapability {
472
479
  // **Destructured before the parse, and that ordering is the whole reason this is not a config field.**
473
480
  // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
474
481
  // would vanish with no error and the adopter's override would simply never run. `payments()` splits
@@ -480,18 +487,24 @@ export function auth(options: AuthOptions): AuthCapability {
480
487
  onUserSuspended,
481
488
  onUserReinstated,
482
489
  onUserDeleted,
490
+ onUserRestored,
483
491
  onUserPurged,
484
492
  ...config
485
493
  } = options;
486
494
  const resolved = AuthConfig.parse(config);
487
495
  // The lifecycle hooks, kept only where one was given, so an absent hook is an absent key rather than an
488
496
  // `undefined` every reader has to tell apart from a hook.
489
- const lifecycleHooks: UserLifecycleHooks = {
497
+ const typedHooks: UserLifecycleHooks<Env> = {
490
498
  ...(onUserSuspended ? { onUserSuspended } : {}),
491
499
  ...(onUserReinstated ? { onUserReinstated } : {}),
492
500
  ...(onUserDeleted ? { onUserDeleted } : {}),
501
+ ...(onUserRestored ? { onUserRestored } : {}),
493
502
  ...(onUserPurged ? { onUserPurged } : {}),
494
503
  };
504
+ // Every fire site hands these the Worker's own env, which is what `Env` names, so widening it here is the one
505
+ // place the adopter's type meets the env the kit holds untyped.
506
+ const lifecycleHooks = typedHooks as unknown as UserLifecycleHooks;
507
+ const sessionRevoked = onSessionRevoked as SessionRevokedListener | undefined;
495
508
  // What may be composed, before anything is built from the list. The four the kit composes are the
496
509
  // sign-in this product promises and what the control-plane seam verifies against, so a list naming one
497
510
  // of them is refused here by name rather than silently redefining a route at request time — and so is a
@@ -506,7 +519,7 @@ export function auth(options: AuthOptions): AuthCapability {
506
519
  resolveGithubUserInfo,
507
520
  enqueueEmail: undefined,
508
521
  turnstile: undefined,
509
- onSessionRevoked,
522
+ onSessionRevoked: sessionRevoked,
510
523
  resolveScopes,
511
524
  lifecycleHooks,
512
525
  purgeSteps: [],
@@ -33,7 +33,7 @@ export type UserLifecycleAction = z.output<typeof UserLifecycleAction>;
33
33
  export const UserLifecycleActorType = z
34
34
  .enum(["control-plane", "user", "system"])
35
35
  .describe(
36
- "Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (the account's own holder, deleting their own account), or `system` (the scheduled purge, with nobody calling).",
36
+ "Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (a signed-in person: the account's own holder deleting it, or an organization's owner whose deletion of that organization reached it through the sole-member cascade), or `system` (the scheduled purge, with nobody calling).",
37
37
  );
38
38
  export type UserLifecycleActorType = z.output<typeof UserLifecycleActorType>;
39
39
 
@@ -55,7 +55,7 @@ export const UserLifecycleEvent = z
55
55
  .string()
56
56
  .nullable()
57
57
  .describe(
58
- "The acting principal's id — the user's own id for a self-service deletion, the connection's for a management client. Null for `system`, and for a management client that named none.",
58
+ "The acting principal's id — the user's own id for a self-service deletion, the deleting owner's for an organization's cascade, the connection's for a management client. Null for `system`, and for a management client that named none.",
59
59
  ),
60
60
  reason: z
61
61
  .string()
@@ -87,6 +87,13 @@ export const UserLifecycleEvent = z
87
87
  .describe(
88
88
  "For a `deleted` row, when its purge comes due — kept here because the purge erases the account's own column. Null for every other row, and before `0007_erasure_record` (#823). Ms-epoch in SQLite.",
89
89
  ),
90
+ basisKey: z
91
+ .string()
92
+ .nullable()
93
+ .default(null)
94
+ .describe(
95
+ "For a `purge_retained` row, the catalog key its basis in `reason` translates through, under the retaining capability's own domain — `payments/purge.retained`. Null for every other row, for a retained step that names no key, and before `0011_retained_basis_key`.",
96
+ ),
90
97
  createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
91
98
  })
92
99
  .describe(
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * What a hook is handed beside its event and the D1 binding: the Worker it runs in.
6
+ *
7
+ * `env` is the Worker's environment, typed as the adopter's own through `auth<Env>()` or
8
+ * `organization.withEnv<Env>()(...)`, so a hook can read a secret, start a Workflow or send to a queue. `waitUntil` is the request's
9
+ * `ExecutionContext.waitUntil`, already bound, present when the hook fires inside a request and absent when it fires
10
+ * from a purge Workflow, which has no `ExecutionContext` — a Workflow step already runs to completion.
11
+ */
12
+ export interface HookRuntime<Env = Record<string, unknown>> {
13
+ /** The Worker's environment: every binding and secret. */
14
+ readonly env: Env;
15
+ /** Keep work running after the response, inside a request. Absent in a Workflow. */
16
+ readonly waitUntil?: (promise: Promise<unknown>) => void;
17
+ }
18
+
19
+ /** What {@link requestRuntime} reads off a Hono context. */
20
+ interface RuntimeSource {
21
+ readonly env: unknown;
22
+ readonly executionCtx?: { waitUntil(promise: Promise<unknown>): void } | undefined;
23
+ }
24
+
25
+ /**
26
+ * The runtime for a hook fired inside a request: the request's env, and its `waitUntil` bound to the context.
27
+ *
28
+ * Hono's `executionCtx` getter throws when the request carries none, as under `app.request()` with no context, so
29
+ * that case reads as absent rather than failing the hook's caller.
30
+ */
31
+ export function requestRuntime<Env = Record<string, unknown>>(c: RuntimeSource): HookRuntime<Env> {
32
+ const env = c.env as Env;
33
+ let ctx: RuntimeSource["executionCtx"];
34
+ try {
35
+ ctx = c.executionCtx;
36
+ } catch {
37
+ ctx = undefined;
38
+ }
39
+ if (!ctx) return { env };
40
+ return { env, waitUntil: ctx.waitUntil.bind(ctx) };
41
+ }
@@ -9,6 +9,7 @@ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
9
9
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
10
10
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
11
11
  import { validate } from "@pithy-sh/core/src/http/validation";
12
+ import { composedTranslator } from "@pithy-sh/core/src/i18n/composed";
12
13
  import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
13
14
  import type { Context, Hono } from "hono";
14
15
  import type { z } from "zod";
@@ -859,13 +860,19 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
859
860
  { action: AuthAuditActions.adminUserExported, ...call.audit },
860
861
  async () => {
861
862
  const database = db(c, wiring);
862
- await requirePresent(database, userId);
863
- return purgeExports(wiring.purgeSteps ?? [], {
864
- subject: { type: "user", id: userId },
865
- env: c.env as Record<string, unknown>,
866
- // A capability holding rows by address — a suppression, a tester's membership — reads it here.
867
- address: () => purgeAddress(database, userId),
868
- });
863
+ const { locale } = await requirePresent(database, userId);
864
+ // A retained basis is told to the person, so it is read in their stored locale, never the caller's.
865
+ const t = composedTranslator(wiring.composed ?? [], locale);
866
+ return purgeExports(
867
+ wiring.purgeSteps ?? [],
868
+ {
869
+ subject: { type: "user", id: userId },
870
+ env: c.env as Record<string, unknown>,
871
+ // A capability holding rows by address — a suppression, a tester's membership — reads it here.
872
+ address: () => purgeAddress(database, userId),
873
+ },
874
+ t ? (key) => t.maybe(key) : undefined,
875
+ );
869
876
  },
870
877
  () => false,
871
878
  );
@@ -12,6 +12,7 @@ import type { Context } from "hono";
12
12
  import type { AuthWiring } from "../capability";
13
13
  import { authDatabase } from "../data/tables";
14
14
  import { makeSendAuthEmail, type ResolveRecipientLocale } from "../email/send";
15
+ import { requestRuntime } from "../hooks/runtime";
15
16
  import { type AuthInstance, makeAuth } from "../instance/auth";
16
17
  import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption";
17
18
  import { resolveProvider } from "../instance/providers";
@@ -133,10 +134,13 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
133
134
  const baseURL = baseURLResolver(cfg.baseURL)(c.req.raw);
134
135
  return makeAuth({
135
136
  db: authDatabase(d1),
136
- // The adopter's listener, bound to *this* request's binding. The instance is built per request, so
137
- // there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and
138
- // has none.
139
- ...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
137
+ // The adopter's listener, bound to *this* request's binding and runtime. The instance is built per request, so
138
+ // there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and has none.
139
+ ...(listener
140
+ ? {
141
+ onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1, requestRuntime(c)),
142
+ }
143
+ : {}),
140
144
  secret,
141
145
  sessionSecrets,
142
146
  // Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
@@ -475,7 +475,13 @@ const exportEntry = {
475
475
  .string()
476
476
  .optional()
477
477
  .describe(
478
- "For a `retain` entry, why the rows are kept, in one sentence written for the person — `Kept for tax records.` Absent for `erase`.",
478
+ "For a `retain` entry, why the rows are kept, in one sentence written for the person and in their stored locale where a catalog translates it — `Kept for tax records.` Absent for `erase`.",
479
+ ),
480
+ basisKey: z
481
+ .string()
482
+ .optional()
483
+ .describe(
484
+ "For a `retain` entry, the catalog key `basis` was translated from, under the capability's own domain — `payments/purge.retained`. Absent when the capability names none, for `erase`, and from a Worker that predates it.",
479
485
  ),
480
486
  };
481
487
 
@@ -9,7 +9,7 @@ import { UserLifecycleEvent } from "../data/userLifecycle";
9
9
  import { resolveDb } from "../http/resolve";
10
10
 
11
11
  /**
12
- * **A user's erasure record, read back for the control plane's attestation (#823).**
12
+ * **A user's erasure record, read back for the control plane's attestation.**
13
13
  *
14
14
  * `pithy_auth_user_lifecycle` is the one `pithy_auth_*` table a purge leaves behind, and it names the account by id
15
15
  * and nothing else. This reads the rows an erasure is made of — the deletion, any restore, each step, a failure, the
@@ -45,6 +45,7 @@ export function userErasureReader(db: AuthDatabase): ErasureHistoryReader {
45
45
  actorType: row.actorType,
46
46
  reason: row.reason,
47
47
  step: row.step,
48
+ basisKey: row.basisKey,
48
49
  mode: row.mode,
49
50
  purgeAfter: row.purgeAfter,
50
51
  at: row.createdAt,
@@ -3,9 +3,10 @@
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
5
  import type { UserLifecycleActorType } from "../data/userLifecycle";
6
+ import type { HookRuntime } from "../hooks/runtime";
6
7
 
7
8
  /**
8
- * The four seams an adopter's own code follows the account lifecycle through, without polling (#620).
9
+ * The five seams an adopter's own code follows the account lifecycle through, without polling.
9
10
  *
10
11
  * **On the transition, not on a route.** An account is suspended from the management surface today and may be
11
12
  * from somewhere else tomorrow; a listener hung off one route would miss the others, which is the argument
@@ -36,19 +37,30 @@ export interface UserLifecycleHookEvent {
36
37
  }
37
38
 
38
39
  /**
39
- * One hook. Handed the request's D1 binding, for the reason `SessionRevokedListener` is: the listener almost
40
- * certainly writes to the same database under a different capability's view of it.
40
+ * One hook. Handed the run's D1 binding, for the reason `SessionRevokedListener` is: the listener almost certainly
41
+ * writes to the same database under a different capability's view of it. And handed the Worker it runs in, so it
42
+ * can reach a secret or another binding — start a Workflow, send to a queue, call out. `runtime.waitUntil` is there
43
+ * in a request and absent in the purge Workflow. A hook that takes only `(event, d1)` is still one.
41
44
  */
42
- export type UserLifecycleListener = (event: UserLifecycleHookEvent, d1: D1Database) => void | Promise<void>;
45
+ export type UserLifecycleListener<Env = Record<string, unknown>> = (
46
+ event: UserLifecycleHookEvent,
47
+ d1: D1Database,
48
+ runtime: HookRuntime<Env>,
49
+ ) => void | Promise<void>;
43
50
 
44
- /** The four hooks, each optional. Passed to `auth()` beside the config. */
45
- export interface UserLifecycleHooks {
51
+ /** The five hooks, each optional. Passed to `auth()` beside the config; `Env` is the adopter's Worker env. */
52
+ export interface UserLifecycleHooks<Env = Record<string, unknown>> {
46
53
  /** An account was suspended. */
47
- readonly onUserSuspended?: UserLifecycleListener;
54
+ readonly onUserSuspended?: UserLifecycleListener<Env>;
48
55
  /** A suspended account was reinstated. */
49
- readonly onUserReinstated?: UserLifecycleListener;
56
+ readonly onUserReinstated?: UserLifecycleListener<Env>;
50
57
  /** An account was deleted — by an operator or by its owner — and its purge window began. */
51
- readonly onUserDeleted?: UserLifecycleListener;
58
+ readonly onUserDeleted?: UserLifecycleListener<Env>;
59
+ /**
60
+ * A deleted account was restored inside its purge window. The undo for whatever `onUserDeleted` did: the account
61
+ * is back, and a suspension it was under is still in force.
62
+ */
63
+ readonly onUserRestored?: UserLifecycleListener<Env>;
52
64
  /** A deleted account's data was erased. The last thing that happens to it. */
53
- readonly onUserPurged?: UserLifecycleListener;
65
+ readonly onUserPurged?: UserLifecycleListener<Env>;
54
66
  }
@@ -6,6 +6,7 @@ import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
6
6
  import type { Context } from "hono";
7
7
  import type { AuthWiring } from "../capability";
8
8
  import { authDatabase } from "../data/tables";
9
+ import { requestRuntime } from "../hooks/runtime";
9
10
  import { resolveDb } from "../http/resolve";
10
11
  import type { LifecycleAuditContext, LifecycleDeps } from "./transitions";
11
12
 
@@ -14,7 +15,8 @@ import type { LifecycleAuditContext, LifecycleDeps } from "./transitions";
14
15
  *
15
16
  * One function so every route resolves them the same way: this request's database, its audit seam and logger,
16
17
  * the composed email capability's enqueue bound to this request's env, and the adopter's hooks as `auth()` was
17
- * handed them. A route that assembled its own would be the second place a hook could be forgotten.
18
+ * handed them, with this request's env and `waitUntil` to run in. A route that assembled its own would be the second
19
+ * place a hook could be forgotten.
18
20
  *
19
21
  * `context` is what the caller adds to each audit event: the request's correlation, and for a management call
20
22
  * the connection it came through. The caller passes it because only the caller knows who it is.
@@ -32,6 +34,7 @@ export function lifecycleDeps(
32
34
  emit: c.var.emit,
33
35
  config: wiring.config,
34
36
  hooks: wiring.lifecycleHooks ?? {},
37
+ runtime: requestRuntime(c),
35
38
  enqueueEmail: enqueue ? (input) => enqueue(c.env as unknown as EmailEnqueueEnv, input) : undefined,
36
39
  log: c.var.log?.child("auth"),
37
40
  ...(context ? { context } : {}),
@@ -16,14 +16,15 @@ import { type AuthAuditAction, AuthAuditActions } from "../audit/actions";
16
16
  import type { AuthConfig } from "../capability";
17
17
  import type { AuthDatabase } from "../data/tables";
18
18
  import type { UserLifecycleAction, UserLifecycleActorType } from "../data/userLifecycle";
19
+ import type { HookRuntime } from "../hooks/runtime";
19
20
  import type { UserLifecycleHookEvent, UserLifecycleHooks, UserLifecycleListener } from "./hooks";
20
21
  import { MAX_REASON } from "./reason";
21
22
  import { accountStanding, LifecycleColumns } from "./state";
22
23
 
23
24
  /**
24
- * The account-lifecycle transitions — the one place an account's state is ever changed (#620).
25
+ * The account-lifecycle transitions — the one place an account's state is ever changed.
25
26
  *
26
- * The admin routes (#621, #622), the self-service deletion, and the purge Workflow call these and write
27
+ * The admin routes, the self-service deletion, and the purge Workflow call these and write
27
28
  * nothing themselves, so each transition happens the same way whoever asked for it:
28
29
  *
29
30
  * 1. **The columns move, conditionally, and the history row is written with them.** The `update` names the
@@ -66,6 +67,8 @@ export interface LifecycleDeps {
66
67
  readonly config: Pick<AuthConfig, "retention" | "lifecycleEmails">;
67
68
  /** The adopter's hooks. */
68
69
  readonly hooks: UserLifecycleHooks;
70
+ /** The Worker the hooks run in: this run's env, and `waitUntil` inside a request. */
71
+ readonly runtime: HookRuntime;
69
72
  /** The email capability's enqueue, bound to this run's env. Absent, nothing is mailed. */
70
73
  readonly enqueueEmail?: ((input: EnqueueInput) => Promise<unknown>) | undefined;
71
74
  /** Where a swallowed failure is reported. Absent, it is swallowed silently. */
@@ -102,7 +105,7 @@ export interface LifecycleTransition {
102
105
  /** What a suspension did, and the suspension it left in force. */
103
106
  export interface SuspendTransition extends LifecycleTransition {
104
107
  /**
105
- * True when the account was already suspended and this call restated the reason and the end instead (#621).
108
+ * True when the account was already suspended and this call restated the reason and the end instead.
106
109
  * That is not a transition — `changed` is false and no hook fires — but it is written, audited and mailed.
107
110
  */
108
111
  readonly updated: boolean;
@@ -167,10 +170,12 @@ interface HistoryRow {
167
170
  readonly step?: string | null;
168
171
  /** A hard deletion's choice for the purge's last mail; see `UserLifecycleEvent.notify`. */
169
172
  readonly notify?: boolean | null;
170
- /** A deletion's mode, kept for the erasure attestation (#823). */
173
+ /** A deletion's mode, kept for the erasure attestation. */
171
174
  readonly mode?: DeletionMode | null;
172
- /** When a deletion's purge comes due, kept for the erasure attestation (#823). */
175
+ /** When a deletion's purge comes due, kept for the erasure attestation. */
173
176
  readonly purgeAfter?: Date | null;
177
+ /** A retained step's catalog key for the basis in `reason`. */
178
+ readonly basisKey?: string | null;
174
179
  }
175
180
 
176
181
  /** The history row's values, as the table stores them. */
@@ -186,6 +191,7 @@ function encoded(row: HistoryRow) {
186
191
  notify: row.notify === undefined || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
187
192
  mode: row.mode ?? null,
188
193
  purgeAfter: row.purgeAfter ? SQLiteDate.encode(row.purgeAfter) : null,
194
+ basisKey: row.basisKey ?? null,
189
195
  createdAt: SQLiteDate.encode(row.at),
190
196
  };
191
197
  }
@@ -304,7 +310,7 @@ async function fire(
304
310
  ): Promise<void> {
305
311
  if (!hook) return;
306
312
  try {
307
- await hook(event, deps.d1);
313
+ await hook(event, deps.d1, deps.runtime);
308
314
  } catch (error) {
309
315
  deps.log?.warn(`${name} threw; the transition stands`, { userId: event.userId, reason: messageOf(error) });
310
316
  }
@@ -338,7 +344,7 @@ function raced(userId: string): ConflictError {
338
344
  }
339
345
 
340
346
  /**
341
- * The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch (#622).
347
+ * The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch.
342
348
  *
343
349
  * A restore and a purge's `due` check race for one account, and each has to see the window the other saw. A
344
350
  * timestamp the restore took before its statement went out is stale by the time D1 runs it: the window can
@@ -369,7 +375,7 @@ function windowClosed(userId: string, closes: Date): ConflictError {
369
375
  * conflict rather than a no-op, and names `restoreRoute` when the caller gives one. A suspension whose end has
370
376
  * passed is not in force, and a new one replaces it.
371
377
  *
372
- * **An account already suspended has its terms restated (#621).** The reason and the end are replaced, a
378
+ * **An account already suspended has its terms restated.** The reason and the end are replaced, a
373
379
  * `suspended` row records the new reason — the newest one is what the person is shown — and the audit event
374
380
  * and the mail say so. The start is kept, and no hook fires: the account was suspended and still is, so
375
381
  * nothing transitioned. A fresh suspension that loses the race to another suspension finds the account
@@ -559,7 +565,7 @@ export interface DeleteTransition extends LifecycleTransition {
559
565
  * Restorable until then. The deletion-scheduled mail carries the purge date and, when the config names one,
560
566
  * the restore path. A deleted account deleted softly again is no transition.
561
567
  *
562
- * **Hard** (#622): `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
568
+ * **Hard**: `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
563
569
  * caller starts the purge. No deletion-scheduled mail, because nothing is scheduled; the purge sends the
564
570
  * deletion-complete one. An account already deleted softly has its purge brought forward to now, which is
565
571
  * written and audited but fires no hook: the account was deleted and still is. One already due is unchanged.
@@ -577,9 +583,9 @@ export async function deleteUser(
577
583
  const purgeAfter = hard ? at : new Date(at.getTime() + userPurgeWindowDays(deps.config) * 86_400_000);
578
584
  const subject = await subjectOf(deps.db, input.userId);
579
585
  // A hard deletion's `notify` is the purge's to read, so it is written on the row: the purge that sends the last
580
- // mail may be one the daily pass started, with no request to carry it (#622).
586
+ // mail may be one the daily pass started, with no request to carry it.
581
587
  // The mode and the due instant ride on the row too, because the purge erases the account's own column and the
582
- // erasure attestation still has to say both (#823).
588
+ // erasure attestation still has to say both.
583
589
  const row: HistoryRow = {
584
590
  userId: input.userId,
585
591
  action: "deleted",
@@ -678,7 +684,8 @@ export interface RestoreTransition extends LifecycleTransition {
678
684
  * 404 whose action says the data is gone — read off the history row the purge leaves behind, so it is told
679
685
  * apart from an id that never existed.
680
686
  *
681
- * An account that is not deleted is no transition. A suspension it was under is still in force after.
687
+ * An account that is not deleted is no transition, and fires nothing. A suspension it was under is still in force
688
+ * after. `onUserRestored` fires once the restore is written, so an adopter can undo what it did on `onUserDeleted`.
682
689
  */
683
690
  export async function restoreUser(
684
691
  deps: LifecycleDeps,
@@ -723,6 +730,12 @@ export async function restoreUser(
723
730
  }
724
731
 
725
732
  await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
733
+ await fire(deps, "onUserRestored", deps.hooks.onUserRestored, {
734
+ userId: input.userId,
735
+ actor: input.actor,
736
+ reason,
737
+ at,
738
+ });
726
739
  return { changed: true, mailed: false, state };
727
740
  }
728
741
 
@@ -748,13 +761,17 @@ async function purgedRefusal(db: AuthDatabase, userId: string): Promise<NotFound
748
761
  }
749
762
 
750
763
  /**
751
- * The account's row, or the refusal for one that is not there — the 404 that says the data is gone when the
752
- * purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
753
- * export.
764
+ * The account's stored locale, or the refusal for an account that is not there — the 404 that says the data is gone
765
+ * when the purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
766
+ * export, which answers in the person's own language.
754
767
  */
755
- export async function requirePresent(db: AuthDatabase, userId: string): Promise<void> {
756
- const row = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", userId).executeTakeFirst();
757
- if (row) return;
768
+ export async function requirePresent(db: AuthDatabase, userId: string): Promise<{ locale: string | null }> {
769
+ const row = await db
770
+ .selectFrom("pithyAuthUsers")
771
+ .select(["id", "locale"])
772
+ .where("id", "=", userId)
773
+ .executeTakeFirst();
774
+ if (row) return { locale: row.locale ?? null };
758
775
  throw (
759
776
  (await purgedRefusal(db, userId)) ??
760
777
  new NotFoundError({ message: "No such user.", detail: `no pithy_auth_users row for ${userId}` })
@@ -772,7 +789,7 @@ export interface PurgeRecipient {
772
789
  }
773
790
 
774
791
  /**
775
- * Whether one account is due for its purge, who its last mail goes to, and whether it goes (#622).
792
+ * Whether one account is due for its purge, who its last mail goes to, and whether it goes.
776
793
  *
777
794
  * `due` only for an account that is deleted and whose `purgeAfter` has passed — the cron and a hard deletion
778
795
  * both start a purge, and this is the one check either passes through, so an account restored in between is
@@ -790,7 +807,7 @@ export async function purgeSubject(
790
807
  { state: "due"; recipient: PurgeRecipient; notify: boolean | null } | { state: "not_due" } | { state: "gone" }
791
808
  > {
792
809
  // The instant is the database's, read in the same statement as the row — the clock `restoreUser` guards on, so
793
- // a restore and this check agree on whether the window has closed, whichever runs first (#622).
810
+ // a restore and this check agree on whether the window has closed, whichever runs first.
794
811
  const row = await deps.db
795
812
  .selectFrom("pithyAuthUsers")
796
813
  .select(["email", "name", "locale", "suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
@@ -816,7 +833,7 @@ export async function purgeSubject(
816
833
  }
817
834
 
818
835
  /**
819
- * The account's address, as a purge step reads it (#814) — `null` when there is no account, or no address. Read
836
+ * The account's address, as a purge step reads it — `null` when there is no account, or no address. Read
820
837
  * inside the step that asks, so it is never carried in a Workflow's journal.
821
838
  */
822
839
  export async function purgeAddress(db: AuthDatabase, userId: string): Promise<string | null> {
@@ -831,7 +848,7 @@ export interface DuePurge {
831
848
  }
832
849
 
833
850
  /**
834
- * The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
851
+ * The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit`.
835
852
  * What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
836
853
  * that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
837
854
  */
@@ -853,23 +870,25 @@ export async function duePurges(deps: LifecycleDeps, limit: number): Promise<Due
853
870
  /**
854
871
  * Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
855
872
  * the row's reason, so the history says what the step erased and not only that it ran. With `retained`, the step
856
- * kept its rows instead (#814): the row is `purge_retained`, and its reason is the basis the capability gave.
873
+ * kept its rows instead: the row is `purge_retained`, its reason is the basis the capability gave, and its
874
+ * `basisKey` the catalog key that translates it, when the capability names one.
857
875
  */
858
876
  export async function recordPurgeStep(
859
877
  deps: LifecycleDeps,
860
- input: { userId: string; step: string; summary?: string | null; retained?: boolean },
878
+ input: { userId: string; step: string; summary?: string | null; retained?: boolean; basisKey?: string },
861
879
  ): Promise<void> {
862
880
  const at = (deps.now ?? (() => new Date()))();
863
881
  await record(deps, {
864
882
  userId: input.userId,
865
- // A retained step kept its rows (#814): its own action, so the trail never reads a kept step as an erased one.
883
+ // A retained step kept its rows: its own action, so the trail never reads a kept step as an erased one.
866
884
  action: input.retained ? "purge_retained" : "purge_step",
867
885
  actor: PURGE,
868
886
  reason: input.summary?.trim() ? input.summary.trim().slice(0, MAX_REASON) : null,
869
887
  at,
870
888
  step: input.step,
889
+ basisKey: input.retained ? (input.basisKey ?? null) : null,
871
890
  });
872
- // The trail's record of the step, which the erasure attestation cites by id and chain position (#823). The step's
891
+ // The trail's record of the step, which the erasure attestation cites by id and chain position. The step's
873
892
  // name and disposition only: the summary is the row's, and the trail never holds anything about the person.
874
893
  await audit(deps, AuthAuditActions.adminUserPurgeStep, input.userId, PURGE, {
875
894
  step: input.step,
@@ -878,7 +897,7 @@ export async function recordPurgeStep(
878
897
  }
879
898
 
880
899
  /**
881
- * Record that a purge gave up (#823): the step it stopped at, in the history and in the trail. The daily pass starts
900
+ * Record that a purge gave up: the step it stopped at, in the history and in the trail. The daily pass starts
882
901
  * the purge again tomorrow, so this is where it stands until then, not an end. The failure's message is never
883
902
  * written: it is code the kit did not write, and it may name the person.
884
903
  */
@@ -896,7 +915,7 @@ export async function recordPurgeFailure(deps: LifecycleDeps, input: { userId: s
896
915
  }
897
916
 
898
917
  /**
899
- * The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
918
+ * The deletion-complete mail, sent **before the address is erased**. The purge calls this after every
900
919
  * other capability's rows are gone and before auth's own, which holds the address, so the last mail is
901
920
  * enqueued while there is still an account to have sent it to. The address is handed in, captured before the
902
921
  * first step. `notify: false` sends nothing, whatever the config says.
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /**
8
+ * `basis_key` on `pithy_auth_user_lifecycle`: the catalog key a retained step's basis translates through, beside the
9
+ * English basis in `reason`. Null on every other row, on a retained step that names no key, and on one recorded
10
+ * before this ran. Appended: the chain is released history.
11
+ */
12
+ export const auth_0011_retained_basis_key: Migration = {
13
+ async up(db: Kysely<unknown>): Promise<void> {
14
+ await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("basisKey", "text").execute();
15
+ },
16
+ async down(db: Kysely<unknown>): Promise<void> {
17
+ await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("basisKey").execute();
18
+ },
19
+ };
@@ -11,6 +11,7 @@ import { auth_0007_erasure_record } from "./0007_erasure_record";
11
11
  import { auth_0008_last_active } from "./0008_last_active";
12
12
  import { auth_0009_attestation_challenges } from "./0009_attestation_challenges";
13
13
  import { auth_0010_app_attest_keys } from "./0010_app_attest_keys";
14
+ import { auth_0011_retained_basis_key } from "./0011_retained_basis_key";
14
15
 
15
16
  /**
16
17
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -36,4 +37,5 @@ export const AUTH_MIGRATIONS = {
36
37
  "0008_last_active": auth_0008_last_active,
37
38
  "0009_attestation_challenges": auth_0009_attestation_challenges,
38
39
  "0010_app_attest_keys": auth_0010_app_attest_keys,
40
+ "0011_retained_basis_key": auth_0011_retained_basis_key,
39
41
  } as const;