@pithy-sh/auth 0.10.0 → 0.11.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 (116) hide show
  1. package/README.md +1 -1
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +19 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +20 -1
  6. package/dist/audit/emit.d.ts +2 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +1 -1
  9. package/dist/capability.d.ts +19 -0
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +20 -3
  12. package/dist/data/tables.d.ts +1 -0
  13. package/dist/data/tables.d.ts.map +1 -1
  14. package/dist/data/userLifecycle.d.ts +1 -0
  15. package/dist/data/userLifecycle.d.ts.map +1 -1
  16. package/dist/data/userLifecycle.js +2 -1
  17. package/dist/http/adminRoutes.d.ts.map +1 -1
  18. package/dist/http/adminRoutes.js +270 -5
  19. package/dist/http/guards.d.ts +8 -7
  20. package/dist/http/guards.d.ts.map +1 -1
  21. package/dist/http/guards.js +38 -7
  22. package/dist/http/middleware.d.ts +25 -1
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +44 -3
  25. package/dist/http/responses.d.ts +180 -0
  26. package/dist/http/responses.d.ts.map +1 -1
  27. package/dist/http/responses.js +142 -1
  28. package/dist/http/routes.d.ts +1 -0
  29. package/dist/http/routes.d.ts.map +1 -1
  30. package/dist/http/routes.js +45 -3
  31. package/dist/http/schemas.d.ts +57 -0
  32. package/dist/http/schemas.d.ts.map +1 -1
  33. package/dist/http/schemas.js +51 -1
  34. package/dist/http/views.d.ts +39 -2
  35. package/dist/http/views.d.ts.map +1 -1
  36. package/dist/http/views.js +105 -1
  37. package/dist/instance/auth.d.ts.map +1 -1
  38. package/dist/instance/auth.js +2 -2
  39. package/dist/lifecycle/audited.d.ts +48 -0
  40. package/dist/lifecycle/audited.d.ts.map +1 -0
  41. package/dist/lifecycle/audited.js +65 -0
  42. package/dist/lifecycle/enforce.d.ts +37 -2
  43. package/dist/lifecycle/enforce.d.ts.map +1 -1
  44. package/dist/lifecycle/enforce.js +46 -5
  45. package/dist/lifecycle/reason.d.ts +11 -0
  46. package/dist/lifecycle/reason.d.ts.map +1 -0
  47. package/dist/lifecycle/reason.js +13 -0
  48. package/dist/lifecycle/request.d.ts +5 -2
  49. package/dist/lifecycle/request.d.ts.map +1 -1
  50. package/dist/lifecycle/request.js +6 -2
  51. package/dist/lifecycle/transitions.d.ts +158 -18
  52. package/dist/lifecycle/transitions.d.ts.map +1 -1
  53. package/dist/lifecycle/transitions.js +344 -70
  54. package/dist/migrations/0005_purge_once.d.ts +22 -0
  55. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  56. package/dist/migrations/0005_purge_once.js +35 -0
  57. package/dist/migrations/pluginTables.d.ts +8 -0
  58. package/dist/migrations/pluginTables.d.ts.map +1 -1
  59. package/dist/migrations/pluginTables.js +8 -1
  60. package/dist/migrations/set.d.ts +2 -1
  61. package/dist/migrations/set.d.ts.map +1 -1
  62. package/dist/migrations/set.js +4 -2
  63. package/dist/purge/contribution.d.ts +47 -0
  64. package/dist/purge/contribution.d.ts.map +1 -0
  65. package/dist/purge/contribution.js +141 -0
  66. package/dist/purge/retryPolicy.d.ts +22 -0
  67. package/dist/purge/retryPolicy.d.ts.map +1 -0
  68. package/dist/purge/retryPolicy.js +26 -0
  69. package/dist/purge/run.d.ts +88 -0
  70. package/dist/purge/run.d.ts.map +1 -0
  71. package/dist/purge/run.js +102 -0
  72. package/dist/purge/specs.d.ts +71 -0
  73. package/dist/purge/specs.d.ts.map +1 -0
  74. package/dist/purge/specs.js +72 -0
  75. package/dist/purge/start.d.ts +42 -0
  76. package/dist/purge/start.d.ts.map +1 -0
  77. package/dist/purge/start.js +37 -0
  78. package/dist/purge/workflow.d.ts +58 -0
  79. package/dist/purge/workflow.d.ts.map +1 -0
  80. package/dist/purge/workflow.js +96 -0
  81. package/dist/test-utils/accountFootprint.d.ts +10 -0
  82. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  83. package/dist/test-utils/accountFootprint.js +44 -0
  84. package/dist/version.generated.d.ts +1 -1
  85. package/dist/version.generated.js +1 -1
  86. package/docs/account-lifecycle.md +123 -11
  87. package/package.json +5 -5
  88. package/pithy.manifest.json +1 -1
  89. package/src/audit/actions.ts +19 -0
  90. package/src/audit/emit.ts +3 -1
  91. package/src/capability.ts +48 -1
  92. package/src/data/userLifecycle.ts +4 -1
  93. package/src/http/adminRoutes.ts +398 -2
  94. package/src/http/guards.ts +39 -7
  95. package/src/http/middleware.ts +45 -2
  96. package/src/http/responses.ts +245 -0
  97. package/src/http/routes.ts +55 -3
  98. package/src/http/schemas.ts +110 -0
  99. package/src/http/views.ts +147 -2
  100. package/src/instance/auth.ts +7 -2
  101. package/src/lifecycle/audited.ts +104 -0
  102. package/src/lifecycle/enforce.ts +55 -5
  103. package/src/lifecycle/reason.ts +11 -0
  104. package/src/lifecycle/request.ts +10 -2
  105. package/src/lifecycle/transitions.ts +482 -93
  106. package/src/migrations/0005_purge_once.ts +42 -0
  107. package/src/migrations/pluginTables.ts +19 -1
  108. package/src/migrations/set.ts +3 -1
  109. package/src/purge/contribution.ts +191 -0
  110. package/src/purge/retryPolicy.ts +26 -0
  111. package/src/purge/run.ts +185 -0
  112. package/src/purge/specs.ts +95 -0
  113. package/src/purge/start.ts +79 -0
  114. package/src/purge/workflow.ts +144 -0
  115. package/src/test-utils/accountFootprint.ts +95 -0
  116. package/src/version.generated.ts +1 -1
@@ -0,0 +1,79 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { WorkflowBinding } from "@pithy-sh/core/src/workflow/spec";
5
+ import { AuthPurgeParams } from "./specs";
6
+
7
+ /**
8
+ * Starting one account's purge, from either door (#622) — a hard deletion's route and the daily pass.
9
+ *
10
+ * **Under an id the deletion names, so two starts of one purge are one instance.** A hard deletion repeated, a
11
+ * hard deletion the daily pass also finds due, a `start` step the pass retries: each asks for the same
12
+ * instance, and Cloudflare holds one instance per id, so the second `create` is refused and nothing runs
13
+ * twice. Two purges of one account running at once would both pass `due` and both reach the mail.
14
+ *
15
+ * **The id is the account, the deletion's start, and the UTC day of the start.** The account and the deletion,
16
+ * so a restored and re-deleted account is a different purge. The day, because the daily pass is the outer
17
+ * retry (`./retryPolicy.ts`): an instance that failed keeps its id, and a purge started under the same id
18
+ * forever could never be started again. So tomorrow's pass gets a fresh instance for an account still due,
19
+ * and every start within one day is the same one. Two instances of one purge can overlap only across a day
20
+ * boundary, while the first is still retrying; `complete` then records, audits and fires once whatever
21
+ * overlaps (`../lifecycle/transitions.ts`).
22
+ *
23
+ * **Hashed.** An instance id is at most 100 characters of `[A-Za-z0-9_-]`, and a user id is up to 255 of
24
+ * anything. A SHA-256 of the pair keeps the id inside the rule and says nothing about the account.
25
+ */
26
+
27
+ /** What starting a purge needs to know. */
28
+ export interface PurgeStart {
29
+ /** The account. */
30
+ readonly userId: string;
31
+ /** The deletion it is purged under — its start, ms-epoch. */
32
+ readonly deletedAt: number;
33
+ /** A hard deletion's `notify`, when it named one. The deletion's row carries it too. */
34
+ readonly notify?: boolean;
35
+ /** Now, for the day the id is named for. */
36
+ readonly at: Date;
37
+ }
38
+
39
+ /** The instance id of one purge, on one day. Deterministic: the same start always names the same instance. */
40
+ export async function purgeInstanceId(start: Pick<PurgeStart, "userId" | "deletedAt" | "at">): Promise<string> {
41
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${start.userId}\n${start.deletedAt}`));
42
+ const hex = Array.from(new Uint8Array(digest).slice(0, 20), (byte) => byte.toString(16).padStart(2, "0")).join("");
43
+ const day = start.at.toISOString().slice(0, 10).replaceAll("-", "");
44
+ return `auth-purge-${hex}-${day}`;
45
+ }
46
+
47
+ /** The half of a Workflow binding that looks an instance up — present on the real one, resolving when it exists. */
48
+ interface InstanceLookup {
49
+ get(id: string): Promise<unknown>;
50
+ }
51
+
52
+ function canLookUp(binding: WorkflowBinding): binding is WorkflowBinding & InstanceLookup {
53
+ return typeof (binding as Partial<InstanceLookup>).get === "function";
54
+ }
55
+
56
+ /**
57
+ * Start one purge, or find it started. A `create` refused because the id is taken is a purge already started,
58
+ * so this asks the binding for the instance and succeeds when it is there. Any other failure is thrown, for the
59
+ * caller to report as `pending`. The parameters are the job's own schema, parsed.
60
+ */
61
+ export async function startPurgeInstance(binding: WorkflowBinding, start: PurgeStart): Promise<void> {
62
+ const id = await purgeInstanceId(start);
63
+ const params = AuthPurgeParams.parse({
64
+ userId: start.userId,
65
+ ...(start.notify === undefined ? {} : { notify: start.notify }),
66
+ });
67
+ try {
68
+ await binding.create({ id, params });
69
+ } catch (error) {
70
+ if (canLookUp(binding)) {
71
+ const found = await binding.get(id).then(
72
+ () => true,
73
+ () => false,
74
+ );
75
+ if (found) return;
76
+ }
77
+ throw error;
78
+ }
79
+ }
@@ -0,0 +1,144 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { composedCapability } from "@pithy-sh/core/src/capability/composition";
5
+ import { messageOf } from "@pithy-sh/core/src/error/pithyError";
6
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
7
+ import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
8
+ import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
9
+ import type { TerminalErrorConstructor, WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
10
+ import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
11
+ import { enqueueFromEnv } from "@pithy-sh/email/src/send/fromComposition";
12
+ import { type AuthCapability, isAuthCapability } from "../capability";
13
+ import { authDatabase } from "../data/tables";
14
+ import { resolveDb } from "../http/resolve";
15
+ import type { LifecycleDeps } from "../lifecycle/transitions";
16
+ import { duePurgesOf, type PurgeDueRun, type PurgeOutcome, purgeOps, purgeUser, startDuePurges } from "./run";
17
+ import { AUTH_PURGE_BINDING, AUTH_PURGE_KEY, AuthPurgeDueParams, AuthPurgeParams } from "./specs";
18
+ import { startPurgeInstance } from "./start";
19
+
20
+ /**
21
+ * The purge's two Workflow bodies (#622) — run by classes **the adopter's own Worker** exports, beside the
22
+ * `createEntrypoint` it already exports, because a purge runs every composed capability's contribution and
23
+ * those exist nowhere else:
24
+ *
25
+ * // apps/api/src/index.ts
26
+ * import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
27
+ * import { NonRetryableError } from "cloudflare:workflows";
28
+ * import { runAuthPurge, runAuthPurgeDue } from "@pithy-sh/auth/src/purge/workflow";
29
+ *
30
+ * export class AuthPurgeWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
31
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
32
+ * return runAuthPurge(this.env, event, step, NonRetryableError);
33
+ * }
34
+ * }
35
+ * export class AuthPurgeDueWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
36
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
37
+ * return runAuthPurgeDue(this.env, event, step, NonRetryableError);
38
+ * }
39
+ * }
40
+ *
41
+ * plus a `workflows` entry binding `AUTH_PURGE` and `AUTH_PURGE_DUE` to them and the daily cron —
42
+ * `docs/account-lifecycle.md` has the stanza. **The class is the adopter's, the body is the kit's**, the split
43
+ * `@pithy-sh/payments`' usage pass has, for the same reason.
44
+ *
45
+ * Each body finds the composed auth capability the way a Workflow that sends mail finds email: the class is
46
+ * exported from the entry that calls `createEntrypoint`, so the composition has happened in this isolate. The
47
+ * steps, the hooks, the config and the audit recorder are on the capability; the mail is email's own enqueue.
48
+ */
49
+
50
+ /** What a Workflow event hands a body. */
51
+ interface PurgeEvent {
52
+ readonly payload?: unknown;
53
+ readonly workflowName?: string;
54
+ readonly instanceId?: string;
55
+ }
56
+
57
+ /** The lifecycle transitions' dependencies, for a run with no request: this env, and the composition's seams. */
58
+ function lifecycleFor(auth: AuthCapability, env: Record<string, unknown>, log: Logger): LifecycleDeps {
59
+ const d1 = resolveDb(env, auth.authConfig.database);
60
+ return {
61
+ db: authDatabase(d1),
62
+ d1,
63
+ emit: auth.auditFor(env),
64
+ config: auth.authConfig,
65
+ hooks: auth.lifecycleHooks,
66
+ enqueueEmail: (input) => enqueueFromEnv(env as unknown as EmailEnqueueEnv, input),
67
+ log,
68
+ };
69
+ }
70
+
71
+ /** This run's logger, bound to the instance an operator reads it under. */
72
+ function runLog(env: Record<string, unknown>, event: PurgeEvent, name: string): Logger {
73
+ return bindWorkflowContext(createWorkerLogger({ name }), {
74
+ workflow: event.workflowName ?? name,
75
+ instance: event.instanceId ?? "unknown",
76
+ env: typeof env.ENVIRONMENT === "string" ? env.ENVIRONMENT : "unknown",
77
+ });
78
+ }
79
+
80
+ /** Purge one account: every composed contribution, one step each, auth's last. See `./run.ts`. */
81
+ export async function runAuthPurge(
82
+ env: Record<string, unknown>,
83
+ event: PurgeEvent,
84
+ step: WorkflowStepLike,
85
+ terminalError: TerminalErrorConstructor,
86
+ ): Promise<PurgeOutcome> {
87
+ // Parsed rather than trusted: an instance can be started by the daily pass, by a hard deletion, or by hand.
88
+ const params = AuthPurgeParams.parse(event.payload ?? {});
89
+ const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
90
+ const lifecycle = lifecycleFor(auth, env, runLog(env, event, "auth:purge"));
91
+ return purgeUser({ steps: auth.purgeSteps, env, ops: purgeOps(lifecycle) }, step, terminalError, params);
92
+ }
93
+
94
+ /** The daily pass: start a purge for every account past its window. See `./run.ts`. */
95
+ export async function runAuthPurgeDue(
96
+ env: Record<string, unknown>,
97
+ event: PurgeEvent,
98
+ step: WorkflowStepLike,
99
+ terminalError: TerminalErrorConstructor,
100
+ ): Promise<{ started: number }> {
101
+ const params = AuthPurgeDueParams.parse(event.payload ?? {});
102
+ const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
103
+ const log = runLog(env, event, "auth:purge-due");
104
+ const lifecycle = lifecycleFor(auth, env, log);
105
+ return startDuePurges({ due: duePurgesOf(lifecycle), start: purgeStarter(env, log) }, step, terminalError, params);
106
+ }
107
+
108
+ /**
109
+ * How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
110
+ * deletion already started today is the same instance, not a second one. No `notify`: the deletion's own row
111
+ * carries it, and the purge reads it there.
112
+ *
113
+ * **It answers whether the purge is running**, and the pass counts that. A Worker that has not bound the purge,
114
+ * and a start that failed, each log the skip rather than throwing inside a cron nobody watches — tomorrow's pass
115
+ * starts it again — and answer `false`, so the pass does not report a purge it never started.
116
+ */
117
+ export function purgeStarter(
118
+ env: Record<string, unknown>,
119
+ log: Logger,
120
+ now: () => Date = () => new Date(),
121
+ ): PurgeDueRun["start"] {
122
+ return async (due) => {
123
+ const binding = workflowBindingFor(env, AUTH_PURGE_BINDING);
124
+ if (!binding) {
125
+ log.warn("workflow skipped", {
126
+ workflow: AUTH_PURGE_KEY,
127
+ binding: AUTH_PURGE_BINDING,
128
+ reason: "binding absent — the purge Workflow is not bound",
129
+ });
130
+ return false;
131
+ }
132
+ try {
133
+ await startPurgeInstance(binding, { userId: due.userId, deletedAt: due.deletedAt, at: now() });
134
+ return true;
135
+ } catch (error) {
136
+ log.warn("workflow skipped", {
137
+ workflow: AUTH_PURGE_KEY,
138
+ binding: AUTH_PURGE_BINDING,
139
+ reason: messageOf(error),
140
+ });
141
+ return false;
142
+ }
143
+ };
144
+ }
@@ -0,0 +1,95 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+
6
+ /**
7
+ * One account's rows across every `pithy_auth_*` table that keys a row to a person — what a purge must erase
8
+ * and an export must read (#622). For the workers suites; the tables are the real ones, written by raw SQL in
9
+ * the shapes the kit's own writers produce, so a test reads back exactly what production would hold.
10
+ */
11
+
12
+ const AT = "2026-10-01T00:00:00.000Z";
13
+ const AT_MS = Date.parse(AT);
14
+
15
+ /** Every table a footprint writes to, with the column that names the person in it. */
16
+ export const FOOTPRINT_TABLES = [
17
+ ["pithy_auth_users", "id"],
18
+ ["pithy_auth_sessions", "user_id"],
19
+ ["pithy_auth_accounts", "user_id"],
20
+ ["pithy_auth_devices", "user_id"],
21
+ ["pithy_auth_rotated_tokens", "user_id"],
22
+ ] as const;
23
+
24
+ /** Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending codes. */
25
+ export async function seedAccountFootprint(
26
+ d1: D1Database,
27
+ userId: string,
28
+ email = `${userId}@test.com`,
29
+ ): Promise<void> {
30
+ await d1.batch([
31
+ d1
32
+ .prepare(
33
+ "insert into pithy_auth_users (id, name, email, email_verified, locale, created_at, updated_at) values (?, 'Sam', ?, 1, null, ?, ?)",
34
+ )
35
+ .bind(userId, email, AT, AT),
36
+ d1
37
+ .prepare(
38
+ "insert into pithy_auth_sessions (id, expires_at, token, created_at, updated_at, ip_address, user_agent, user_id, device_id) values (?, ?, ?, ?, ?, '203.0.113.9', 'Pithy/1.0', ?, ?)",
39
+ )
40
+ .bind(`s-${userId}`, "2099-01-01T00:00:00.000Z", `token-${userId}`, AT, AT, userId, `d-${userId}`),
41
+ d1
42
+ .prepare(
43
+ "insert into pithy_auth_accounts (id, account_id, provider_id, user_id, access_token, refresh_token, created_at, updated_at) values (?, ?, 'google', ?, ?, ?, ?, ?)",
44
+ )
45
+ .bind(`a-${userId}`, `g-${userId}`, userId, `access-${userId}`, `refresh-${userId}`, AT, AT),
46
+ d1
47
+ .prepare(
48
+ "insert into pithy_auth_devices (id, user_id, platform, push_token, last_ip, last_seen_at, created_at) values (?, ?, 'ios', ?, '203.0.113.9', ?, ?)",
49
+ )
50
+ .bind(`d-${userId}`, userId, `push-${userId}`, AT_MS, AT_MS),
51
+ d1
52
+ .prepare("insert into pithy_auth_rotated_tokens (token, family_id, user_id, rotated_at) values (?, ?, ?, ?)")
53
+ .bind(`spent-${userId}`, `f-${userId}`, userId, AT_MS),
54
+ d1
55
+ .prepare(
56
+ "insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, '123456:0', ?, ?, ?)",
57
+ )
58
+ .bind(`otp-${userId}`, `sign-in-otp-${email}`, "2099-01-01T00:00:00.000Z", AT, AT),
59
+ d1
60
+ .prepare(
61
+ "insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, ?, ?, ?, ?)",
62
+ )
63
+ .bind(
64
+ `link-${userId}`,
65
+ `magic-link-${userId}`,
66
+ JSON.stringify({ email, name: "", attempt: 0 }),
67
+ "2099-01-01T00:00:00.000Z",
68
+ AT,
69
+ AT,
70
+ ),
71
+ ]);
72
+ }
73
+
74
+ /** How many rows one account still holds in each footprint table, and in the pending codes for its address. */
75
+ export async function footprintCounts(d1: D1Database, userId: string, email = `${userId}@test.com`) {
76
+ const counts: Record<string, number> = {};
77
+ for (const [table, column] of FOOTPRINT_TABLES) {
78
+ const row = await d1
79
+ .prepare(`select count(*) as n from ${table} where ${column} = ?`)
80
+ .bind(userId)
81
+ .first<{ n: number }>();
82
+ counts[table] = row?.n ?? 0;
83
+ }
84
+ const codes = await d1
85
+ .prepare("select count(*) as n from pithy_auth_verifications where identifier = ? or instr(value, ?) > 0")
86
+ .bind(`sign-in-otp-${email}`, JSON.stringify(email))
87
+ .first<{ n: number }>();
88
+ counts.pithy_auth_verifications = codes?.n ?? 0;
89
+ const history = await d1
90
+ .prepare("select count(*) as n from pithy_auth_user_lifecycle where user_id = ?")
91
+ .bind(userId)
92
+ .first<{ n: number }>();
93
+ counts.pithy_auth_user_lifecycle = history?.n ?? 0;
94
+ return counts;
95
+ }
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/auth";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.10.0";
16
+ export const PACKAGE_VERSION = "0.11.0";