@pithy-sh/auth 0.9.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.
- package/README.md +8 -2
- package/dist/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +40 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +41 -1
- package/dist/audit/emit.d.ts +2 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +2 -2
- package/dist/capability.d.ts +45 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +40 -5
- package/dist/client/lifecycle.d.ts +19 -0
- package/dist/client/lifecycle.d.ts.map +1 -0
- package/dist/client/lifecycle.js +25 -0
- package/dist/client/projection.d.ts +4 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +4 -0
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +6 -2
- package/dist/data/kitFields.d.ts +20 -25
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +28 -32
- package/dist/data/tables.d.ts +29 -2
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +62 -0
- package/dist/data/userLifecycle.d.ts.map +1 -0
- package/dist/data/userLifecycle.js +51 -0
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +270 -5
- package/dist/http/guards.d.ts +24 -1
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +59 -3
- package/dist/http/lifecycleGate.d.ts +18 -0
- package/dist/http/lifecycleGate.d.ts.map +1 -0
- package/dist/http/lifecycleGate.js +75 -0
- package/dist/http/middleware.d.ts +30 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +89 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +8 -0
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +7 -4
- package/dist/http/responses.d.ts +180 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +142 -1
- package/dist/http/routes.d.ts +1 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +65 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +51 -1
- package/dist/http/views.d.ts +39 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +105 -1
- package/dist/instance/auth.d.ts +55 -3
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +53 -2
- package/dist/instance/microsoftEmail.d.ts +70 -0
- package/dist/instance/microsoftEmail.d.ts.map +1 -0
- package/dist/instance/microsoftEmail.js +96 -0
- package/dist/instance/providerSignInGate.d.ts +7 -6
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +7 -6
- package/dist/instance/providers.d.ts +7 -5
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +5 -3
- package/dist/instance/secrets.d.ts +64 -3
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +44 -5
- package/dist/lifecycle/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +75 -0
- package/dist/lifecycle/enforce.d.ts.map +1 -0
- package/dist/lifecycle/enforce.js +111 -0
- package/dist/lifecycle/hooks.d.ts +53 -0
- package/dist/lifecycle/hooks.d.ts.map +1 -0
- package/dist/lifecycle/hooks.js +2 -0
- package/dist/lifecycle/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +18 -0
- package/dist/lifecycle/request.d.ts.map +1 -0
- package/dist/lifecycle/request.js +31 -0
- package/dist/lifecycle/state.d.ts +64 -0
- package/dist/lifecycle/state.d.ts.map +1 -0
- package/dist/lifecycle/state.js +90 -0
- package/dist/lifecycle/transitions.d.ts +272 -0
- package/dist/lifecycle/transitions.d.ts.map +1 -0
- package/dist/lifecycle/transitions.js +623 -0
- package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
- package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
- package/dist/migrations/0004_user_lifecycle.js +47 -0
- package/dist/migrations/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -0
- package/dist/migrations/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +3 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +6 -2
- package/dist/peer.d.ts +4 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/purge/contribution.d.ts +47 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +141 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +88 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +102 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +58 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +96 -0
- package/dist/test-utils/accountFootprint.d.ts +10 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +44 -0
- package/dist/test-utils/liveApp.d.ts +21 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +1 -0
- package/dist/test-utils/scopedBackend.d.ts +21 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -1
- package/dist/test-utils/scopedBackend.js +7 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +217 -0
- package/docs/apple-signin.md +7 -1
- package/docs/facebook-oauth.md +7 -1
- package/docs/github-oauth.md +7 -1
- package/docs/google-oauth.md +7 -1
- package/docs/microsoft-oauth.md +177 -0
- package/package.json +5 -5
- package/pithy.manifest.json +17 -3
- package/src/audit/actions.ts +42 -0
- package/src/audit/emit.ts +4 -2
- package/src/capability.ts +170 -52
- package/src/client/lifecycle.ts +27 -0
- package/src/client/projection.ts +4 -0
- package/src/data/betterAuth.ts +21 -1
- package/src/data/kitFields.ts +27 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +83 -0
- package/src/http/adminRoutes.ts +398 -2
- package/src/http/guards.ts +61 -1
- package/src/http/lifecycleGate.ts +78 -0
- package/src/http/middleware.ts +104 -2
- package/src/http/providerRefusal.ts +10 -0
- package/src/http/resolve.ts +8 -3
- package/src/http/responses.ts +245 -0
- package/src/http/routes.ts +93 -4
- package/src/http/schemas.ts +110 -0
- package/src/http/views.ts +147 -2
- package/src/instance/auth.ts +74 -2
- package/src/instance/microsoftEmail.ts +111 -0
- package/src/instance/providerSignInGate.ts +7 -6
- package/src/instance/providers.ts +8 -4
- package/src/instance/secrets.ts +59 -5
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +139 -0
- package/src/lifecycle/hooks.ts +54 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +39 -0
- package/src/lifecycle/state.ts +101 -0
- package/src/lifecycle/transitions.ts +872 -0
- package/src/migrations/0004_user_lifecycle.ts +68 -0
- package/src/migrations/0005_purge_once.ts +42 -0
- package/src/migrations/pluginTables.ts +19 -1
- package/src/migrations/set.ts +5 -1
- package/src/purge/contribution.ts +191 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +185 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +144 -0
- package/src/test-utils/accountFootprint.ts +95 -0
- package/src/test-utils/liveApp.ts +2 -1
- package/src/test-utils/scopedBackend.ts +2 -1
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { workflowKey } from "@pithy-sh/core/src/workflow/naming";
|
|
5
|
+
import type { WorkflowRegistry, WorkflowSpecMap } from "@pithy-sh/core/src/workflow/spec";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
|
|
8
|
+
/** This capability's name, and the first segment of its workflow dispatch keys. */
|
|
9
|
+
export const AUTH_CAPABILITY = "auth";
|
|
10
|
+
|
|
11
|
+
/** The binding the purge of one account is started on. */
|
|
12
|
+
export const AUTH_PURGE_BINDING = "AUTH_PURGE";
|
|
13
|
+
|
|
14
|
+
/** The binding the daily pass that starts every due purge runs on. */
|
|
15
|
+
export const AUTH_PURGE_DUE_BINDING = "AUTH_PURGE_DUE";
|
|
16
|
+
|
|
17
|
+
/** The dispatch key of the purge of one account. */
|
|
18
|
+
export const AUTH_PURGE_KEY = workflowKey(AUTH_CAPABILITY, "purge");
|
|
19
|
+
|
|
20
|
+
/** One account's purge: which, and whether its last mail is sent. */
|
|
21
|
+
export const AuthPurgeParams = z
|
|
22
|
+
.object({
|
|
23
|
+
userId: z.string().min(1).max(255).describe("The account to erase, as `pithy_auth_users.id` stores it."),
|
|
24
|
+
notify: z
|
|
25
|
+
.boolean()
|
|
26
|
+
.optional()
|
|
27
|
+
.describe(
|
|
28
|
+
"Whether the deletion-complete mail is sent. Absent is true; the config can still turn it off. A hard deletion with `notify: false` passes false.",
|
|
29
|
+
),
|
|
30
|
+
})
|
|
31
|
+
.describe("One account's purge. It erases nothing unless the account is deleted and its window has closed.");
|
|
32
|
+
export type AuthPurgeParams = z.infer<typeof AuthPurgeParams>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The daily pass's parameters. Every field optional, because a cron passes none — `createEntrypoint` starts a
|
|
36
|
+
* scheduled job with `{}`.
|
|
37
|
+
*/
|
|
38
|
+
export const AuthPurgeDueParams = z
|
|
39
|
+
.object({
|
|
40
|
+
limit: z
|
|
41
|
+
.number()
|
|
42
|
+
.int()
|
|
43
|
+
.min(1)
|
|
44
|
+
.max(1000)
|
|
45
|
+
.optional()
|
|
46
|
+
.describe("How many due accounts to start a purge for in this pass, oldest first. Defaults to 500."),
|
|
47
|
+
})
|
|
48
|
+
.describe("One pass that starts a purge for every account past its window. A cron passes no field.");
|
|
49
|
+
export type AuthPurgeDueParams = z.infer<typeof AuthPurgeDueParams>;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The two durable jobs auth owns (#622) — **both hosted by the adopter's own Worker**, the one that composes
|
|
53
|
+
* auth, never a prebuilt host.
|
|
54
|
+
*
|
|
55
|
+
* **Why not a host.** A purge runs every composed capability's contribution, the adopter's own `app` among
|
|
56
|
+
* them, and those exist only in the Worker whose `pithy.config.ts` composed them. A prebuilt host composes
|
|
57
|
+
* nothing. So each class is five lines in the adopter's entry, calling `runAuthPurge` and `runAuthPurgeDue` in
|
|
58
|
+
* `./workflow.ts`, exactly as `@pithy-sh/payments`' usage pass is: Cloudflare resolves a `class_name` in the
|
|
59
|
+
* script that binds it, and the body finds the composition the way a Workflow that sends mail finds email.
|
|
60
|
+
* No `className` here, deliberately: the class is the adopter's, and so is its `workflows` entry. The docs
|
|
61
|
+
* give both (`docs/account-lifecycle.md`).
|
|
62
|
+
*
|
|
63
|
+
* **`purge-due` is daily at 02:00 UTC**, ahead of storage's and the secrets rotation at 03:00, payments' 04:00
|
|
64
|
+
* and testers' 05:00. Daily because the window is counted in days: an hourly pass would start the same purge
|
|
65
|
+
* twenty-four times and erase nothing sooner. Both stay dispatchable on demand — a hard deletion starts
|
|
66
|
+
* `purge` directly.
|
|
67
|
+
*
|
|
68
|
+
* `optional: true` for both, so a Worker composing auth still boots before the adopter has bound them. A
|
|
69
|
+
* deletion then reports its purge as `pending`, and nothing is erased until they are.
|
|
70
|
+
*/
|
|
71
|
+
export const authWorkflows = {
|
|
72
|
+
purge: {
|
|
73
|
+
binding: AUTH_PURGE_BINDING,
|
|
74
|
+
params: AuthPurgeParams,
|
|
75
|
+
optional: true,
|
|
76
|
+
},
|
|
77
|
+
"purge-due": {
|
|
78
|
+
binding: AUTH_PURGE_DUE_BINDING,
|
|
79
|
+
params: AuthPurgeDueParams,
|
|
80
|
+
schedule: "0 2 * * *",
|
|
81
|
+
optional: true,
|
|
82
|
+
},
|
|
83
|
+
} as const satisfies WorkflowSpecMap;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The jobs as a dispatch registry, keyed `auth/<job>`, built here for the reason testers builds its own: the key
|
|
87
|
+
* format is core's either way. The daily pass starts each purge on the binding directly, not through this, because
|
|
88
|
+
* it names the instance (`./start.ts`) and dispatch does not.
|
|
89
|
+
*/
|
|
90
|
+
export const authWorkflowRegistry: WorkflowRegistry = Object.fromEntries(
|
|
91
|
+
Object.entries(authWorkflows).map(([job, spec]) => {
|
|
92
|
+
const key = workflowKey(AUTH_CAPABILITY, job);
|
|
93
|
+
return [key, { key, capability: AUTH_CAPABILITY, job, spec }];
|
|
94
|
+
}),
|
|
95
|
+
);
|
|
@@ -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
|
+
}
|
|
@@ -66,6 +66,7 @@ const TABLES = [
|
|
|
66
66
|
"pithy_auth_jwks",
|
|
67
67
|
"pithy_auth_rate_limit",
|
|
68
68
|
"pithy_auth_rotated_tokens",
|
|
69
|
+
"pithy_auth_user_lifecycle",
|
|
69
70
|
"pithy_auth_sessions",
|
|
70
71
|
"pithy_auth_users",
|
|
71
72
|
"pithy_auth_verifications",
|
|
@@ -266,7 +267,7 @@ function buildApp(wiring: AuthWiring, events: AuditEventInput[]): Hono<PithyHono
|
|
|
266
267
|
app.onError(pithyErrorHandler);
|
|
267
268
|
app.use("*", async (c, next) => {
|
|
268
269
|
if (c.get("emit") === undefined) {
|
|
269
|
-
c.set("emit", async (event) => {
|
|
270
|
+
c.set("emit", async (event: AuditEventInput) => {
|
|
270
271
|
events.push(event);
|
|
271
272
|
});
|
|
272
273
|
}
|
|
@@ -45,6 +45,7 @@ export const SCOPED_SECRETS: SecretFixture<typeof SCOPED_REGISTRY> = {
|
|
|
45
45
|
"auth-apple-credentials": { clientId: "a", clientSecret: "a" },
|
|
46
46
|
"auth-facebook-credentials": { clientId: "f", clientSecret: "f" },
|
|
47
47
|
"auth-github-credentials": { clientId: "h", clientSecret: "h" },
|
|
48
|
+
"auth-microsoft-credentials": { clientId: "m", clientSecret: "m", tenantId: "common" },
|
|
48
49
|
"email-link-signing-key": "dev-link-signing-key",
|
|
49
50
|
};
|
|
50
51
|
|
|
@@ -121,7 +122,7 @@ export async function signInScoped(
|
|
|
121
122
|
verificationExpiresIn: 300,
|
|
122
123
|
otpLength: 6,
|
|
123
124
|
disableSignUp: false,
|
|
124
|
-
providerSignUp: { google: true, apple: true, facebook: true, github: true },
|
|
125
|
+
providerSignUp: { google: true, apple: true, facebook: true, github: true, microsoft: true },
|
|
125
126
|
emit: async () => {},
|
|
126
127
|
plugins: [],
|
|
127
128
|
});
|
package/src/version.generated.ts
CHANGED