@pithy-sh/auth 0.11.0 → 0.12.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 +30 -2
- package/dist/audit/actions.d.ts +39 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +40 -1
- package/dist/audit/emit.d.ts +34 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +47 -1
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +31 -11
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +38 -5
- package/dist/client/api.d.ts +55 -12
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +57 -18
- package/dist/client/bearer.d.ts +110 -0
- package/dist/client/bearer.d.ts.map +1 -0
- package/dist/client/bearer.js +265 -0
- package/dist/client/handoff.d.ts +77 -0
- package/dist/client/handoff.d.ts.map +1 -0
- package/dist/client/handoff.js +119 -0
- package/dist/client/mcp.d.ts +70 -0
- package/dist/client/mcp.d.ts.map +1 -0
- package/dist/client/mcp.js +65 -0
- package/dist/data/betterAuth.d.ts +3 -2
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +5 -3
- package/dist/data/kitFields.d.ts +5 -0
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +5 -0
- package/dist/data/tables.d.ts +25 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +9 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +6 -2
- package/dist/data/verificationOutcome.d.ts +53 -0
- package/dist/data/verificationOutcome.d.ts.map +1 -0
- package/dist/data/verificationOutcome.js +50 -0
- package/dist/email/send.js +6 -2
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +56 -10
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -11
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +46 -11
- package/dist/http/handoff.d.ts +76 -0
- package/dist/http/handoff.d.ts.map +1 -0
- package/dist/http/handoff.js +316 -0
- package/dist/http/middleware.d.ts +12 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +25 -4
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +142 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +66 -10
- package/dist/http/routes.d.ts +2 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +35 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +44 -1
- package/dist/http/views.d.ts +22 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +40 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/instance/auth.d.ts +148 -10
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +86 -41
- package/dist/instance/plugins.d.ts +6 -0
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +14 -1
- package/dist/ledger/read.d.ts +53 -0
- package/dist/ledger/read.d.ts.map +1 -0
- package/dist/ledger/read.js +85 -0
- package/dist/ledger/record.d.ts +35 -0
- package/dist/ledger/record.d.ts.map +1 -0
- package/dist/ledger/record.js +98 -0
- package/dist/lifecycle/erasure.d.ts +9 -0
- package/dist/lifecycle/erasure.d.ts.map +1 -0
- package/dist/lifecycle/erasure.js +96 -0
- package/dist/lifecycle/inactivity.d.ts +19 -0
- package/dist/lifecycle/inactivity.d.ts.map +1 -0
- package/dist/lifecycle/inactivity.js +28 -0
- package/dist/lifecycle/transitions.d.ts +22 -1
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +51 -4
- package/dist/mcp/argumentClass.d.ts +51 -0
- package/dist/mcp/argumentClass.d.ts.map +1 -0
- package/dist/mcp/argumentClass.js +69 -0
- package/dist/mcp/capability.d.ts +50 -0
- package/dist/mcp/capability.d.ts.map +1 -0
- package/dist/mcp/capability.js +140 -0
- package/dist/mcp/clientMetadata.d.ts +40 -0
- package/dist/mcp/clientMetadata.d.ts.map +1 -0
- package/dist/mcp/clientMetadata.js +68 -0
- package/dist/mcp/consent.d.ts +49 -0
- package/dist/mcp/consent.d.ts.map +1 -0
- package/dist/mcp/consent.js +69 -0
- package/dist/mcp/dispatch.d.ts +35 -0
- package/dist/mcp/dispatch.d.ts.map +1 -0
- package/dist/mcp/dispatch.js +135 -0
- package/dist/mcp/floor.d.ts +37 -0
- package/dist/mcp/floor.d.ts.map +1 -0
- package/dist/mcp/floor.js +41 -0
- package/dist/mcp/host.d.ts +34 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +2 -0
- package/dist/mcp/http/redirectList.d.ts +9 -0
- package/dist/mcp/http/redirectList.d.ts.map +1 -0
- package/dist/mcp/http/redirectList.js +24 -0
- package/dist/mcp/http/responses.d.ts +143 -0
- package/dist/mcp/http/responses.d.ts.map +1 -0
- package/dist/mcp/http/responses.js +83 -0
- package/dist/mcp/http/routes.d.ts +28 -0
- package/dist/mcp/http/routes.d.ts.map +1 -0
- package/dist/mcp/http/routes.js +517 -0
- package/dist/mcp/http/schemas.d.ts +24 -0
- package/dist/mcp/http/schemas.d.ts.map +1 -0
- package/dist/mcp/http/schemas.js +18 -0
- package/dist/mcp/marker.d.ts +15 -0
- package/dist/mcp/marker.d.ts.map +1 -0
- package/dist/mcp/marker.js +15 -0
- package/dist/mcp/provider.d.ts +78 -0
- package/dist/mcp/provider.d.ts.map +1 -0
- package/dist/mcp/provider.js +108 -0
- package/dist/mcp/purge.d.ts +15 -0
- package/dist/mcp/purge.d.ts.map +1 -0
- package/dist/mcp/purge.js +31 -0
- package/dist/mcp/rpc.d.ts +79 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +103 -0
- package/dist/mcp/toolAudit.d.ts +76 -0
- package/dist/mcp/toolAudit.d.ts.map +1 -0
- package/dist/mcp/toolAudit.js +86 -0
- package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
- package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
- package/dist/migrations/0006_verification_outcomes.js +35 -0
- package/dist/migrations/0007_erasure_record.d.ts +17 -0
- package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
- package/dist/migrations/0007_erasure_record.js +36 -0
- package/dist/migrations/0008_last_active.d.ts +15 -0
- package/dist/migrations/0008_last_active.d.ts.map +1 -0
- package/dist/migrations/0008_last_active.js +29 -0
- package/dist/migrations/set.d.ts +4 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +8 -2
- package/dist/peer.d.ts +3 -2
- package/dist/peer.d.ts.map +1 -1
- package/dist/processing/activities.d.ts +6 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +12 -0
- package/dist/purge/contribution.d.ts +20 -5
- package/dist/purge/contribution.d.ts.map +1 -1
- package/dist/purge/contribution.js +20 -6
- package/dist/purge/run.d.ts +75 -5
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +117 -14
- package/dist/purge/workflow.d.ts +15 -2
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.js +51 -7
- package/dist/test-utils/accountFootprint.d.ts +5 -2
- package/dist/test-utils/accountFootprint.d.ts.map +1 -1
- package/dist/test-utils/accountFootprint.js +7 -2
- package/dist/test-utils/liveApp.d.ts +6 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +7 -2
- package/dist/token/handoff.d.ts +80 -0
- package/dist/token/handoff.d.ts.map +1 -0
- package/dist/token/handoff.js +136 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +59 -7
- package/docs/apple-signin.md +32 -4
- package/docs/facebook-oauth.md +2 -2
- package/docs/github-oauth.md +2 -2
- package/docs/google-oauth.md +9 -7
- package/docs/microsoft-oauth.md +2 -2
- package/package.json +11 -5
- package/pithy.manifest.json +2 -2
- package/pithy.mcp.manifest.json +36 -0
- package/src/audit/actions.ts +39 -0
- package/src/audit/emit.ts +63 -0
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +80 -23
- package/src/client/api.ts +69 -19
- package/src/client/bearer.ts +388 -0
- package/src/client/handoff.ts +172 -0
- package/src/client/mcp.ts +140 -0
- package/src/data/betterAuth.ts +8 -4
- package/src/data/kitFields.ts +2 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +15 -3
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +68 -3
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +48 -11
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +29 -3
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +134 -8
- package/src/http/routes.ts +63 -4
- package/src/http/schemas.ts +85 -0
- package/src/http/views.ts +46 -2
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +51 -1
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/transitions.ts +75 -5
- package/src/mcp/argumentClass.ts +112 -0
- package/src/mcp/capability.ts +194 -0
- package/src/mcp/clientMetadata.ts +81 -0
- package/src/mcp/consent.ts +95 -0
- package/src/mcp/dispatch.ts +154 -0
- package/src/mcp/floor.ts +62 -0
- package/src/mcp/host.ts +36 -0
- package/src/mcp/http/redirectList.ts +26 -0
- package/src/mcp/http/responses.ts +157 -0
- package/src/mcp/http/routes.ts +635 -0
- package/src/mcp/http/schemas.ts +37 -0
- package/src/mcp/marker.ts +18 -0
- package/src/mcp/provider.ts +151 -0
- package/src/mcp/purge.ts +39 -0
- package/src/mcp/rpc.ts +135 -0
- package/src/mcp/toolAudit.ts +132 -0
- package/src/migrations/0006_verification_outcomes.ts +51 -0
- package/src/migrations/0007_erasure_record.ts +43 -0
- package/src/migrations/0008_last_active.ts +30 -0
- package/src/migrations/set.ts +7 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +37 -10
- package/src/purge/run.ts +179 -16
- package/src/purge/workflow.ts +65 -7
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +10 -1
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
|
@@ -2,23 +2,25 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
-
import type {
|
|
5
|
+
import type { ErasingPurgeContribution, PurgeContext } from "@pithy-sh/core/src/capability/purge";
|
|
6
6
|
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
7
|
import { type CompiledQuery, type Kysely, type SqlBool, sql } from "kysely";
|
|
8
8
|
import { Account, Session, User } from "../data/betterAuth";
|
|
9
9
|
import { Device } from "../data/device";
|
|
10
10
|
import { type AuthDatabase, authDatabase } from "../data/tables";
|
|
11
11
|
import { UserLifecycleEvent } from "../data/userLifecycle";
|
|
12
|
+
import { VerificationOutcome } from "../data/verificationOutcome";
|
|
12
13
|
import type { AuthUserExport } from "../http/responses";
|
|
13
14
|
import { authUserExportView } from "../http/views";
|
|
15
|
+
import { purgeAddress } from "../lifecycle/transitions";
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
18
|
* Auth's own purge contribution (#622): what erasing one person means for the `pithy_auth_*` tables, and what
|
|
17
19
|
* exporting them hands back.
|
|
18
20
|
*
|
|
19
21
|
* **Every row keyed to the account goes, except its history.** The user row, its sessions, its linked
|
|
20
|
-
* providers, its devices, its refresh-token ledger, any sign-in code or link still pending for its address,
|
|
21
|
-
* and its rows in every table a composed Better Auth plugin created keyed by `userId` — a two-factor secret
|
|
22
|
+
* providers, its devices, its refresh-token ledger, any sign-in code or link still pending for its address, its
|
|
23
|
+
* rows in the verification ledger (#829), and its rows in every table a composed Better Auth plugin created keyed by `userId` — a two-factor secret
|
|
22
24
|
* and its backup codes, a passkey, an API key. Those tables have no foreign key to the user row, so deleting
|
|
23
25
|
* it removes nothing from them; they are named by the plugin plan (`../migrations/pluginTables.ts`). `pithy_auth_user_lifecycle` stays: it is the record that the account existed, was deleted and was
|
|
24
26
|
* erased, and it names the account by id and holds nothing else about the person (`../data/userLifecycle.ts`).
|
|
@@ -34,7 +36,7 @@ import { authUserExportView } from "../http/views";
|
|
|
34
36
|
|
|
35
37
|
/** The one sentence the purge records with this step. */
|
|
36
38
|
export const AUTH_PURGE_SUMMARY =
|
|
37
|
-
"Deletes the account, its sessions, linked providers, devices, refresh-token ledger, pending sign-in codes and its rows in the tables its Better Auth plugins created. Its lifecycle history stays.";
|
|
39
|
+
"Deletes the account, its sessions, linked providers, devices, refresh-token ledger, pending sign-in codes, the record of the sign-in links and codes it was sent, and its rows in the tables its Better Auth plugins created. Its lifecycle history stays.";
|
|
38
40
|
|
|
39
41
|
/**
|
|
40
42
|
* A plugin table's column that holds a credential — a TOTP secret, backup codes, a key or its hash, a token.
|
|
@@ -44,12 +46,12 @@ export const AUTH_PURGE_SUMMARY =
|
|
|
44
46
|
const CREDENTIAL_COLUMN = /secret|token|key|code|hash|password|credential/i;
|
|
45
47
|
|
|
46
48
|
/** The auth Kysely without its table map — a plugin's table is named by the plan, not by `authTables`. */
|
|
47
|
-
function untyped(db: AuthDatabase): Kysely<Record<string, Record<string, unknown>>> {
|
|
49
|
+
export function untyped(db: AuthDatabase): Kysely<Record<string, Record<string, unknown>>> {
|
|
48
50
|
return db as unknown as Kysely<Record<string, Record<string, unknown>>>;
|
|
49
51
|
}
|
|
50
52
|
|
|
51
53
|
/** The D1 binding the auth tables live in, off a run's env — or a wiring fault naming it. */
|
|
52
|
-
function bindingOf(env: Record<string, unknown>, database: string): D1Database {
|
|
54
|
+
export function bindingOf(env: Record<string, unknown>, database: string): D1Database {
|
|
53
55
|
const binding = env[database];
|
|
54
56
|
if (typeof binding !== "object" || binding === null) {
|
|
55
57
|
throw new InternalError({
|
|
@@ -67,7 +69,7 @@ function literal(value: string): string {
|
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
/** Bind a compiled statement to D1, so it can join a `batch`. */
|
|
70
|
-
function prepared(d1: D1Database, compiled: CompiledQuery) {
|
|
72
|
+
export function prepared(d1: D1Database, compiled: CompiledQuery) {
|
|
71
73
|
return d1.prepare(compiled.sql).bind(...(compiled.parameters as unknown[]));
|
|
72
74
|
}
|
|
73
75
|
|
|
@@ -91,6 +93,9 @@ export async function eraseAuthUser(
|
|
|
91
93
|
db.deleteFrom("pithyAuthAccounts").where("userId", "=", userId),
|
|
92
94
|
db.deleteFrom("pithyAuthDevices").where("userId", "=", userId),
|
|
93
95
|
db.deleteFrom("pithyAuthRotatedTokens").where("userId", "=", userId),
|
|
96
|
+
// The sign-in links and codes it was sent (#829). A sign-up nobody completed names no account and holds no
|
|
97
|
+
// address, so there is nothing of the person's in it to find.
|
|
98
|
+
db.deleteFrom("pithyAuthVerificationOutcomes").where("userId", "=", userId),
|
|
94
99
|
].map((query) => prepared(d1, query.compile()));
|
|
95
100
|
// A plugin's rows, in the same batch: `CamelCasePlugin` snake-cases the table and `user_id` as it does for
|
|
96
101
|
// the plugin's own migration, so the names match what `pithy migrate` created.
|
|
@@ -127,7 +132,7 @@ export async function exportAuthUser(
|
|
|
127
132
|
): Promise<AuthUserExport | null> {
|
|
128
133
|
const row = await db.selectFrom("pithyAuthUsers").selectAll().where("id", "=", userId).executeTakeFirst();
|
|
129
134
|
if (!row) return null;
|
|
130
|
-
const [sessions, accounts, devices, history, plugins] = await Promise.all([
|
|
135
|
+
const [sessions, accounts, devices, history, verifications, plugins] = await Promise.all([
|
|
131
136
|
db
|
|
132
137
|
.selectFrom("pithyAuthSessions")
|
|
133
138
|
.selectAll()
|
|
@@ -150,20 +155,29 @@ export async function exportAuthUser(
|
|
|
150
155
|
.orderBy("id", "desc")
|
|
151
156
|
.execute(),
|
|
152
157
|
db.selectFrom("pithyAuthUserLifecycle").selectAll().where("userId", "=", userId).orderBy("id", "asc").execute(),
|
|
158
|
+
db
|
|
159
|
+
.selectFrom("pithyAuthVerificationOutcomes")
|
|
160
|
+
.selectAll()
|
|
161
|
+
.where("userId", "=", userId)
|
|
162
|
+
.orderBy("issuedAt", "desc")
|
|
163
|
+
.orderBy("id", "desc")
|
|
164
|
+
.execute(),
|
|
153
165
|
Promise.all(pluginTables.map(async (table) => [table, await pluginRows(db, table, userId)] as const)),
|
|
154
166
|
]);
|
|
155
167
|
return authUserExportView({
|
|
168
|
+
now: new Date(),
|
|
156
169
|
user: User.parse(row),
|
|
157
170
|
sessions: sessions.map((session) => Session.parse(session)),
|
|
158
171
|
accounts: accounts.map((account) => Account.pick({ providerId: true, createdAt: true }).parse(account)),
|
|
159
172
|
devices: devices.map((device) => Device.parse(device)),
|
|
160
173
|
history: history.map((event) => UserLifecycleEvent.parse(event)),
|
|
174
|
+
verifications: verifications.map((row) => VerificationOutcome.parse(row)),
|
|
161
175
|
plugins: Object.fromEntries(plugins),
|
|
162
176
|
});
|
|
163
177
|
}
|
|
164
178
|
|
|
165
179
|
/** One plugin table's rows about the account, every column but a credential's. */
|
|
166
|
-
async function pluginRows(db: AuthDatabase, table: string, userId: string): Promise<Record<string, unknown>[]> {
|
|
180
|
+
export async function pluginRows(db: AuthDatabase, table: string, userId: string): Promise<Record<string, unknown>[]> {
|
|
167
181
|
const rows = await untyped(db).selectFrom(table).selectAll().where("userId", "=", userId).execute();
|
|
168
182
|
return rows.map((row) =>
|
|
169
183
|
Object.fromEntries(Object.entries(row).filter(([column]) => !CREDENTIAL_COLUMN.test(column))),
|
|
@@ -174,7 +188,20 @@ async function pluginRows(db: AuthDatabase, table: string, userId: string): Prom
|
|
|
174
188
|
* The contribution `auth()` declares, over the D1 binding its config names. The export of an account that is
|
|
175
189
|
* not there is an empty object, which the route never reaches: it answers 404 before it reads any capability.
|
|
176
190
|
*/
|
|
177
|
-
|
|
191
|
+
/**
|
|
192
|
+
* An account's address by user id, over the env's auth database — what auth answers through core's `addressOf`
|
|
193
|
+
* seam, so a capability holding state by address (email's suppression list) finds it without importing auth.
|
|
194
|
+
* `null` for an account that has none, or no longer exists.
|
|
195
|
+
*/
|
|
196
|
+
export function authAddressOf(database: string) {
|
|
197
|
+
return (env: Record<string, unknown>, userId: string): Promise<string | null> =>
|
|
198
|
+
purgeAddress(authDatabase(bindingOf(env, database)), userId);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function authPurgeContribution(
|
|
202
|
+
database: string,
|
|
203
|
+
pluginTables: readonly string[] = [],
|
|
204
|
+
): ErasingPurgeContribution {
|
|
178
205
|
const open = (context: PurgeContext) => {
|
|
179
206
|
const d1 = bindingOf(context.env, database);
|
|
180
207
|
return { d1, db: authDatabase(d1) };
|
package/src/purge/run.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
-
import type
|
|
4
|
+
import { isRetained, type PurgeContext, type PurgeStep } from "@pithy-sh/core/src/capability/purge";
|
|
5
|
+
import type { LegalHolds } from "@pithy-sh/core/src/retention/holds";
|
|
5
6
|
import {
|
|
6
7
|
classifiedSteps,
|
|
7
8
|
type TerminalErrorConstructor,
|
|
@@ -13,7 +14,9 @@ import {
|
|
|
13
14
|
duePurges,
|
|
14
15
|
type LifecycleDeps,
|
|
15
16
|
mailPurgeComplete,
|
|
17
|
+
purgeAddress,
|
|
16
18
|
purgeSubject,
|
|
19
|
+
recordPurgeFailure,
|
|
17
20
|
recordPurgeStep,
|
|
18
21
|
} from "../lifecycle/transitions";
|
|
19
22
|
import { authWorkflowRetry } from "./retryPolicy";
|
|
@@ -28,7 +31,8 @@ import { AUTH_CAPABILITY, type AuthPurgeDueParams, type AuthPurgeParams } from "
|
|
|
28
31
|
* and one already erased all end the run here, having erased nothing. This is the one check a cron-started
|
|
29
32
|
* purge and a hard deletion's both pass through, so re-running a purge for the same subject exits cleanly.
|
|
30
33
|
* 2. **`erase <capability>`** — one step per composed contribution, in composition order, each recording that it
|
|
31
|
-
* ran in `pithy_auth_user_lifecycle`.
|
|
34
|
+
* ran in `pithy_auth_user_lifecycle`. A contribution that **retains** its rows (#814) is a `retain <capability>`
|
|
35
|
+
* step instead: it erases nothing, and records `purge_retained` with the basis it gave. Handed to the platform's retry unclassified: an `erase` is idempotent by
|
|
32
36
|
* contract and runs code the kit did not write, so any fault in it is worth another attempt (`./retryPolicy.ts`).
|
|
33
37
|
* A failing contribution retries alone, and the ones that finished are served from the journal.
|
|
34
38
|
* 3. **`mail`** — the deletion-complete mail, **before the address is erased**: every other capability's rows are
|
|
@@ -36,6 +40,24 @@ import { AUTH_CAPABILITY, type AuthPurgeDueParams, type AuthPurgeParams } from "
|
|
|
36
40
|
* one, so it is in no Workflow's journal.
|
|
37
41
|
* 4. **`erase auth`** — auth's own contribution, last for that reason.
|
|
38
42
|
* 5. **`complete`** — the `purged` record, the audit event, `onUserPurged`. Once.
|
|
43
|
+
*
|
|
44
|
+
* Every step from 2 on records an audit event as well as its row (#823), which the erasure attestation cites.
|
|
45
|
+
*
|
|
46
|
+
* ## A legal hold stops it
|
|
47
|
+
*
|
|
48
|
+
* Before `due` hands over, and again before every step after it, the purge asks whether a legal hold stands on the
|
|
49
|
+
* account — each ask its own step, `hold <next>`, so a replay serves the answer it got. A hold found ends the run as
|
|
50
|
+
* `held`, having erased nothing more: the steps that finished stay finished, the rest wait. Released, the account is
|
|
51
|
+
* still deleted and still due, so the next daily pass starts a fresh purge, whose idempotent steps find nothing to
|
|
52
|
+
* erase where the first one did and carry on from there. A hold that cannot be read fails its step, which retries:
|
|
53
|
+
* a purge never erases past a hold it could not see.
|
|
54
|
+
*
|
|
55
|
+
* ## A purge that gives up says where (#823)
|
|
56
|
+
*
|
|
57
|
+
* A step that exhausts its retries fails the instance, and the daily pass starts a fresh one tomorrow. Until then the
|
|
58
|
+
* record would read as a purge still running. So the failure is caught once, recorded in its own `fail` step —
|
|
59
|
+
* the step it stopped at, in the history and the trail — and thrown on unchanged, so the instance still fails
|
|
60
|
+
* exactly as it did. A `fail` step that cannot write either is swallowed: the original failure is the one to report.
|
|
39
61
|
*/
|
|
40
62
|
|
|
41
63
|
/** What a purge does with the account's own records — the transitions, over one set of dependencies. */
|
|
@@ -44,6 +66,13 @@ export interface PurgeOps {
|
|
|
44
66
|
due(userId: string): Promise<"due" | "not_due" | "gone">;
|
|
45
67
|
/** Record that one capability's step erased its rows. */
|
|
46
68
|
recordStep(userId: string, step: string, summary: string): Promise<void>;
|
|
69
|
+
/** Record that one capability's step kept its rows, and why (#814). */
|
|
70
|
+
recordRetained(userId: string, step: string, basis: string): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* The account's address, read now, or `null` once it is gone (#814). Handed to each step as
|
|
73
|
+
* `PurgeContext.address`, so a capability holding rows by address reads it inside its own step.
|
|
74
|
+
*/
|
|
75
|
+
address(userId: string): Promise<string | null>;
|
|
47
76
|
/**
|
|
48
77
|
* Send the deletion-complete mail to the account's address, if it is still there to read, unless this purge's
|
|
49
78
|
* `notify` or the deletion's own saved choice is false. Says whether.
|
|
@@ -51,13 +80,19 @@ export interface PurgeOps {
|
|
|
51
80
|
mailComplete(userId: string, notify: boolean | undefined): Promise<boolean>;
|
|
52
81
|
/** Write the `purged` record, the audit event and the hook. Says whether this call wrote them. */
|
|
53
82
|
complete(userId: string): Promise<boolean>;
|
|
83
|
+
/** Record that the purge gave up at `step`, in the history and the trail (#823). */
|
|
84
|
+
fail(userId: string, step: string): Promise<void>;
|
|
85
|
+
/** Whether a legal hold stands on the account. Throws when it cannot say. */
|
|
86
|
+
held(userId: string): Promise<boolean>;
|
|
54
87
|
}
|
|
55
88
|
|
|
56
89
|
/** The operations, over the lifecycle transitions. */
|
|
57
|
-
export function purgeOps(deps: LifecycleDeps): PurgeOps {
|
|
90
|
+
export function purgeOps(deps: LifecycleDeps, holds: LegalHolds): PurgeOps {
|
|
58
91
|
return {
|
|
59
92
|
due: async (userId) => (await purgeSubject(deps, userId)).state,
|
|
60
93
|
recordStep: (userId, step, summary) => recordPurgeStep(deps, { userId, step, summary }),
|
|
94
|
+
recordRetained: (userId, step, basis) => recordPurgeStep(deps, { userId, step, summary: basis, retained: true }),
|
|
95
|
+
address: (userId) => purgeAddress(deps.db, userId),
|
|
61
96
|
mailComplete: async (userId, notify) => {
|
|
62
97
|
const subject = await purgeSubject(deps, userId);
|
|
63
98
|
if (subject.state !== "due") return false;
|
|
@@ -68,6 +103,8 @@ export function purgeOps(deps: LifecycleDeps): PurgeOps {
|
|
|
68
103
|
.mailed;
|
|
69
104
|
},
|
|
70
105
|
complete: async (userId) => (await completePurge(deps, { userId })).changed,
|
|
106
|
+
fail: (userId, step) => recordPurgeFailure(deps, { userId, step }),
|
|
107
|
+
held: (userId) => holds.held("user", userId),
|
|
71
108
|
};
|
|
72
109
|
}
|
|
73
110
|
|
|
@@ -75,10 +112,15 @@ export function purgeOps(deps: LifecycleDeps): PurgeOps {
|
|
|
75
112
|
export interface PurgeOutcome {
|
|
76
113
|
/** The account. */
|
|
77
114
|
readonly userId: string;
|
|
78
|
-
/**
|
|
79
|
-
|
|
115
|
+
/**
|
|
116
|
+
* `purged`; or why nothing was erased: `not_due` (restored, or inside its window) and `gone` (no account); or
|
|
117
|
+
* `held`, a legal hold stopped it before the step it would have run next.
|
|
118
|
+
*/
|
|
119
|
+
readonly state: "purged" | "not_due" | "gone" | "held";
|
|
80
120
|
/** Every step that erased its rows, in the order it ran. Empty when nothing was erased. */
|
|
81
121
|
readonly erased: readonly string[];
|
|
122
|
+
/** Every step that kept its rows under a stated basis (#814), in the order it ran. */
|
|
123
|
+
readonly retained: readonly string[];
|
|
82
124
|
/** Whether the deletion-complete mail was enqueued. */
|
|
83
125
|
readonly mailed: boolean;
|
|
84
126
|
}
|
|
@@ -103,21 +145,63 @@ export async function purgeUser(
|
|
|
103
145
|
const own = classifiedSteps(step, authWorkflowRetry, terminalError);
|
|
104
146
|
const userId = params.userId;
|
|
105
147
|
const state = await own.do("due", () => run.ops.due(userId));
|
|
106
|
-
if (state !== "due") return { userId, state, erased: [], mailed: false };
|
|
148
|
+
if (state !== "due") return { userId, state, erased: [], retained: [], mailed: false };
|
|
149
|
+
// Asked before every step from here on, each its own step, so a hold placed mid-run stops the next one.
|
|
150
|
+
const stopped = (next: string) => own.do(`hold ${next}`, () => run.ops.held(userId));
|
|
107
151
|
|
|
108
|
-
const context: PurgeContext = {
|
|
152
|
+
const context: PurgeContext = {
|
|
153
|
+
subject: { type: "user", id: userId },
|
|
154
|
+
env: run.env,
|
|
155
|
+
address: () => run.ops.address(userId),
|
|
156
|
+
};
|
|
109
157
|
const auth = run.steps.filter((each) => each.step === AUTH_CAPABILITY);
|
|
110
158
|
const others = run.steps.filter((each) => each.step !== AUTH_CAPABILITY);
|
|
111
159
|
const erased: string[] = [];
|
|
112
|
-
|
|
113
|
-
|
|
160
|
+
const retained: string[] = [];
|
|
161
|
+
// The step running now, so a failure records where it stopped.
|
|
162
|
+
let current = "due";
|
|
163
|
+
const held = { userId, state: "held", erased, retained, mailed: false } as const;
|
|
164
|
+
const runStep = async (each: PurgeStep) => {
|
|
165
|
+
const { contribution } = each;
|
|
166
|
+
current = each.step;
|
|
167
|
+
if (isRetained(contribution))
|
|
168
|
+
retained.push(await retainStep(step, run.ops, each.step, contribution.retain.basis, userId));
|
|
169
|
+
else erased.push(await eraseStep(step, run.ops, each, context));
|
|
170
|
+
};
|
|
171
|
+
try {
|
|
172
|
+
for (const each of others) {
|
|
173
|
+
if (await stopped(each.step)) return held;
|
|
174
|
+
await runStep(each);
|
|
175
|
+
}
|
|
176
|
+
current = "mail";
|
|
177
|
+
if (await stopped("mail")) return held;
|
|
178
|
+
const mailed = await own.do("mail", () => run.ops.mailComplete(userId, params.notify));
|
|
179
|
+
for (const each of auth) {
|
|
180
|
+
if (await stopped(each.step)) return { ...held, mailed };
|
|
181
|
+
await runStep(each);
|
|
182
|
+
}
|
|
183
|
+
current = "complete";
|
|
184
|
+
await own.do("complete", () => run.ops.complete(userId));
|
|
185
|
+
return { userId, state: "purged", erased, retained, mailed };
|
|
186
|
+
} catch (error) {
|
|
187
|
+
await recordFailure(step, run.ops, userId, current);
|
|
188
|
+
throw error;
|
|
114
189
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Record where a purge gave up, in its own step, and never mask the failure that stopped it: a `fail` step that
|
|
194
|
+
* cannot write is swallowed. See the file header.
|
|
195
|
+
*/
|
|
196
|
+
async function recordFailure(step: WorkflowStepLike, ops: PurgeOps, userId: string, at: string): Promise<void> {
|
|
197
|
+
try {
|
|
198
|
+
await step.do("fail", async () => {
|
|
199
|
+
await ops.fail(userId, at);
|
|
200
|
+
return at;
|
|
201
|
+
});
|
|
202
|
+
} catch {
|
|
203
|
+
// The original failure is the one to report, and the next daily pass starts the purge again.
|
|
118
204
|
}
|
|
119
|
-
await own.do("complete", () => run.ops.complete(userId));
|
|
120
|
-
return { userId, state: "purged", erased, mailed };
|
|
121
205
|
}
|
|
122
206
|
|
|
123
207
|
/**
|
|
@@ -127,12 +211,29 @@ export async function purgeUser(
|
|
|
127
211
|
*/
|
|
128
212
|
function eraseStep(step: WorkflowStepLike, ops: PurgeOps, each: PurgeStep, context: PurgeContext): Promise<string> {
|
|
129
213
|
return step.do(`erase ${each.step}`, async () => {
|
|
130
|
-
await each.contribution.erase(context);
|
|
214
|
+
await each.contribution.erase?.(context);
|
|
131
215
|
await ops.recordStep(context.subject.id, each.step, each.contribution.summary);
|
|
132
216
|
return each.step;
|
|
133
217
|
});
|
|
134
218
|
}
|
|
135
219
|
|
|
220
|
+
/**
|
|
221
|
+
* One capability's retained step (#814): nothing is erased, and the record says the rows were kept and why. Its own
|
|
222
|
+
* step, so the trail names it in the order it would have run, and a replay serves it from the journal.
|
|
223
|
+
*/
|
|
224
|
+
function retainStep(
|
|
225
|
+
step: WorkflowStepLike,
|
|
226
|
+
ops: PurgeOps,
|
|
227
|
+
name: string,
|
|
228
|
+
basis: string,
|
|
229
|
+
userId: string,
|
|
230
|
+
): Promise<string> {
|
|
231
|
+
return step.do(`retain ${name}`, async () => {
|
|
232
|
+
await ops.recordRetained(userId, name, basis);
|
|
233
|
+
return name;
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
136
237
|
/** How many purges one `start` step dispatches — a page, so one pass over a backlog is a bounded number of steps. */
|
|
137
238
|
export const PURGE_START_PAGE = 50;
|
|
138
239
|
|
|
@@ -149,6 +250,11 @@ export interface PurgeDueRun {
|
|
|
149
250
|
* started, and the pass does not count it.
|
|
150
251
|
*/
|
|
151
252
|
start(due: DuePurge): Promise<boolean>;
|
|
253
|
+
/**
|
|
254
|
+
* Whether a legal hold stands on the account. A held account is not started; absent, every due account is,
|
|
255
|
+
* and each purge's own hold check stops it before its first step.
|
|
256
|
+
*/
|
|
257
|
+
held?(userId: string): Promise<boolean>;
|
|
152
258
|
}
|
|
153
259
|
|
|
154
260
|
/**
|
|
@@ -172,7 +278,10 @@ export async function startDuePurges(
|
|
|
172
278
|
// Counted from what each start answered, never from the page's length: a purge the binding could not start
|
|
173
279
|
// is not running, and `{ started }` is what an operator reads to learn whether they are.
|
|
174
280
|
let running = 0;
|
|
175
|
-
for (const each of ids)
|
|
281
|
+
for (const each of ids) {
|
|
282
|
+
if (run.held && (await run.held(each.userId))) continue;
|
|
283
|
+
if (await run.start(each)) running += 1;
|
|
284
|
+
}
|
|
176
285
|
return running;
|
|
177
286
|
});
|
|
178
287
|
}
|
|
@@ -183,3 +292,57 @@ export async function startDuePurges(
|
|
|
183
292
|
export function duePurgesOf(deps: LifecycleDeps): PurgeDueRun["due"] {
|
|
184
293
|
return (limit) => duePurges(deps, limit);
|
|
185
294
|
}
|
|
295
|
+
|
|
296
|
+
/** How many inactive accounts one pass soft-deletes, at most: a backlog drains over nights, never in one. */
|
|
297
|
+
export const INACTIVE_DEFAULT_LIMIT = 200;
|
|
298
|
+
|
|
299
|
+
/** What the inactivity pass reads and deletes through. */
|
|
300
|
+
export interface InactivityRun {
|
|
301
|
+
/**
|
|
302
|
+
* The longest an account may sit inactive, in days — the strictest class age it holds — or null for no limit.
|
|
303
|
+
* Asked inside a step, so a replay serves the answer it got.
|
|
304
|
+
*/
|
|
305
|
+
days(): Promise<number | null>;
|
|
306
|
+
/** Every account inactive since `cutoff`, oldest first, at most `limit`. */
|
|
307
|
+
inactive(cutoff: Date, limit: number): Promise<string[]>;
|
|
308
|
+
/** Whether a legal hold stands on the account. */
|
|
309
|
+
held(userId: string): Promise<boolean>;
|
|
310
|
+
/** Soft-delete one account through the lifecycle, with its notice mail and window. Says whether it was deleted. */
|
|
311
|
+
remove(userId: string, days: number): Promise<boolean>;
|
|
312
|
+
/** Now. */
|
|
313
|
+
now(): Date;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The inactivity pass: every account untouched for longer than the strictest class age it holds is
|
|
318
|
+
* soft-deleted through the lifecycle — its deletion-scheduled mail, its window, then the purge the daily pass starts
|
|
319
|
+
* once that window closes. A held account is skipped. With no class age that applies, the pass does nothing.
|
|
320
|
+
*
|
|
321
|
+
* Listed in one step, deleted in pages of steps, so a pass that dies part-way resumes after the page it finished.
|
|
322
|
+
* A deletion is no transition on an account already deleted, so a repeated page deletes nobody twice.
|
|
323
|
+
*/
|
|
324
|
+
export async function deleteInactiveAccounts(
|
|
325
|
+
run: InactivityRun,
|
|
326
|
+
step: WorkflowStepLike,
|
|
327
|
+
terminalError: TerminalErrorConstructor,
|
|
328
|
+
limit = INACTIVE_DEFAULT_LIMIT,
|
|
329
|
+
): Promise<{ deleted: number }> {
|
|
330
|
+
const own = classifiedSteps(step, authWorkflowRetry, terminalError);
|
|
331
|
+
const days = await own.do("class age", () => run.days());
|
|
332
|
+
if (days === null) return { deleted: 0 };
|
|
333
|
+
// The cutoff is read inside the step, so a replay serves the same list rather than one drawn at a later instant.
|
|
334
|
+
const ids = await own.do("inactive", () => run.inactive(new Date(run.now().getTime() - days * 86_400_000), limit));
|
|
335
|
+
let deleted = 0;
|
|
336
|
+
for (let page = 0; page * PURGE_START_PAGE < ids.length; page += 1) {
|
|
337
|
+
const slice = ids.slice(page * PURGE_START_PAGE, (page + 1) * PURGE_START_PAGE);
|
|
338
|
+
deleted += await own.do(`inactive ${page + 1}`, async () => {
|
|
339
|
+
let count = 0;
|
|
340
|
+
for (const userId of slice) {
|
|
341
|
+
if (await run.held(userId)) continue;
|
|
342
|
+
if (await run.remove(userId, days)) count += 1;
|
|
343
|
+
}
|
|
344
|
+
return count;
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
return { deleted };
|
|
348
|
+
}
|
package/src/purge/workflow.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
-
import { composedCapability } from "@pithy-sh/core/src/capability/composition";
|
|
4
|
+
import { composedCapabilities, composedCapability } from "@pithy-sh/core/src/capability/composition";
|
|
5
5
|
import { messageOf } from "@pithy-sh/core/src/error/pithyError";
|
|
6
6
|
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
7
7
|
import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
|
|
8
|
+
import { composedRetention, subjectClasses } from "@pithy-sh/core/src/retention/composed";
|
|
9
|
+
import { type LegalHolds, legalHolds } from "@pithy-sh/core/src/retention/holds";
|
|
10
|
+
import { inactivityDays } from "@pithy-sh/core/src/retention/policy";
|
|
8
11
|
import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
|
|
9
12
|
import type { TerminalErrorConstructor, WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
|
|
10
13
|
import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
|
|
@@ -12,8 +15,18 @@ import { enqueueFromEnv } from "@pithy-sh/email/src/send/fromComposition";
|
|
|
12
15
|
import { type AuthCapability, isAuthCapability } from "../capability";
|
|
13
16
|
import { authDatabase } from "../data/tables";
|
|
14
17
|
import { resolveDb } from "../http/resolve";
|
|
15
|
-
import
|
|
16
|
-
import {
|
|
18
|
+
import { inactiveAccounts } from "../lifecycle/inactivity";
|
|
19
|
+
import { deleteUser, type LifecycleDeps } from "../lifecycle/transitions";
|
|
20
|
+
import {
|
|
21
|
+
deleteInactiveAccounts,
|
|
22
|
+
duePurgesOf,
|
|
23
|
+
type InactivityRun,
|
|
24
|
+
type PurgeDueRun,
|
|
25
|
+
type PurgeOutcome,
|
|
26
|
+
purgeOps,
|
|
27
|
+
purgeUser,
|
|
28
|
+
startDuePurges,
|
|
29
|
+
} from "./run";
|
|
17
30
|
import { AUTH_PURGE_BINDING, AUTH_PURGE_KEY, AuthPurgeDueParams, AuthPurgeParams } from "./specs";
|
|
18
31
|
import { startPurgeInstance } from "./start";
|
|
19
32
|
|
|
@@ -88,21 +101,66 @@ export async function runAuthPurge(
|
|
|
88
101
|
const params = AuthPurgeParams.parse(event.payload ?? {});
|
|
89
102
|
const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
|
|
90
103
|
const lifecycle = lifecycleFor(auth, env, runLog(env, event, "auth:purge"));
|
|
91
|
-
return purgeUser(
|
|
104
|
+
return purgeUser(
|
|
105
|
+
{ steps: auth.purgeSteps, env, ops: purgeOps(lifecycle, legalHolds(env)) },
|
|
106
|
+
step,
|
|
107
|
+
terminalError,
|
|
108
|
+
params,
|
|
109
|
+
);
|
|
92
110
|
}
|
|
93
111
|
|
|
94
|
-
/**
|
|
112
|
+
/**
|
|
113
|
+
* The daily pass: start a purge for every account past its window, then soft-delete every account inactive past the
|
|
114
|
+
* strictest class age it holds. See `./run.ts`.
|
|
115
|
+
*/
|
|
95
116
|
export async function runAuthPurgeDue(
|
|
96
117
|
env: Record<string, unknown>,
|
|
97
118
|
event: PurgeEvent,
|
|
98
119
|
step: WorkflowStepLike,
|
|
99
120
|
terminalError: TerminalErrorConstructor,
|
|
100
|
-
): Promise<{ started: number }> {
|
|
121
|
+
): Promise<{ started: number; inactive: number }> {
|
|
101
122
|
const params = AuthPurgeDueParams.parse(event.payload ?? {});
|
|
102
123
|
const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
|
|
103
124
|
const log = runLog(env, event, "auth:purge-due");
|
|
104
125
|
const lifecycle = lifecycleFor(auth, env, log);
|
|
105
|
-
|
|
126
|
+
const holds = legalHolds(env);
|
|
127
|
+
const { started } = await startDuePurges(
|
|
128
|
+
{ due: duePurgesOf(lifecycle), start: purgeStarter(env, log), held: (userId) => holds.held("user", userId) },
|
|
129
|
+
step,
|
|
130
|
+
terminalError,
|
|
131
|
+
params,
|
|
132
|
+
);
|
|
133
|
+
const { deleted } = await deleteInactiveAccounts(inactivityRun(lifecycle, holds), step, terminalError);
|
|
134
|
+
return { started, inactive: deleted };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The inactivity pass over this composition: the strictest class age among the classes a user's rows hold, from
|
|
139
|
+
* the Worker's resolved `retention` block, and the lifecycle's own soft deletion, by the system, with its notice mail.
|
|
140
|
+
*/
|
|
141
|
+
export function inactivityRun(lifecycle: LifecycleDeps, holds: LegalHolds): InactivityRun {
|
|
142
|
+
return inactivityOps(lifecycle, holds, () => {
|
|
143
|
+
const retention = composedRetention();
|
|
144
|
+
return retention ? inactivityDays(retention, subjectClasses(composedCapabilities(), "user")) : null;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The inactivity pass's reads and deletions over one set of lifecycle dependencies, for a class age in days. */
|
|
149
|
+
export function inactivityOps(lifecycle: LifecycleDeps, holds: LegalHolds, days: () => number | null): InactivityRun {
|
|
150
|
+
return {
|
|
151
|
+
days: async () => days(),
|
|
152
|
+
inactive: (cutoff, limit) => inactiveAccounts(lifecycle.db, cutoff, limit),
|
|
153
|
+
held: (userId) => holds.held("user", userId),
|
|
154
|
+
remove: async (userId, limit) => {
|
|
155
|
+
const deletion = await deleteUser(lifecycle, {
|
|
156
|
+
userId,
|
|
157
|
+
actor: { type: "system", id: null },
|
|
158
|
+
reason: `Inactive for more than ${limit} days, the retention policy's limit for the personal data it holds.`,
|
|
159
|
+
});
|
|
160
|
+
return deletion.outcome === "deleted";
|
|
161
|
+
},
|
|
162
|
+
now: lifecycle.now ?? (() => new Date()),
|
|
163
|
+
};
|
|
106
164
|
}
|
|
107
165
|
|
|
108
166
|
/**
|
package/src/seeds/example.ts
CHANGED
|
@@ -33,8 +33,8 @@ export const authExampleSeed: SeedSet = defineSeed({
|
|
|
33
33
|
User,
|
|
34
34
|
EXAMPLE_IDENTITIES.map((identity) => ({
|
|
35
35
|
id: identity.id,
|
|
36
|
-
name: identity.name,
|
|
37
|
-
email: identity.email,
|
|
36
|
+
name: identity.name as User["name"],
|
|
37
|
+
email: identity.email as User["email"],
|
|
38
38
|
emailVerified: true,
|
|
39
39
|
image: null,
|
|
40
40
|
// The example cast has never picked a language, which is the state most real users are in:
|
|
@@ -19,9 +19,13 @@ export const FOOTPRINT_TABLES = [
|
|
|
19
19
|
["pithy_auth_accounts", "user_id"],
|
|
20
20
|
["pithy_auth_devices", "user_id"],
|
|
21
21
|
["pithy_auth_rotated_tokens", "user_id"],
|
|
22
|
+
["pithy_auth_verification_outcomes", "user_id"],
|
|
22
23
|
] as const;
|
|
23
24
|
|
|
24
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending
|
|
27
|
+
* codes, and the ledger row of a sign-in link it used.
|
|
28
|
+
*/
|
|
25
29
|
export async function seedAccountFootprint(
|
|
26
30
|
d1: D1Database,
|
|
27
31
|
userId: string,
|
|
@@ -51,6 +55,11 @@ export async function seedAccountFootprint(
|
|
|
51
55
|
d1
|
|
52
56
|
.prepare("insert into pithy_auth_rotated_tokens (token, family_id, user_id, rotated_at) values (?, ?, ?, ?)")
|
|
53
57
|
.bind(`spent-${userId}`, `f-${userId}`, userId, AT_MS),
|
|
58
|
+
d1
|
|
59
|
+
.prepare(
|
|
60
|
+
"insert into pithy_auth_verification_outcomes (verification_id, type, user_id, email_job_id, issued_at, expires_at, used_at) values (?, 'magic_link', ?, ?, ?, ?, ?)",
|
|
61
|
+
)
|
|
62
|
+
.bind(`used-link-${userId}`, userId, `job-${userId}`, AT_MS, AT_MS + 300_000, AT_MS + 60_000),
|
|
54
63
|
d1
|
|
55
64
|
.prepare(
|
|
56
65
|
"insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, '123456:0', ?, ?, ?)",
|
|
@@ -67,6 +67,7 @@ const TABLES = [
|
|
|
67
67
|
"pithy_auth_rate_limit",
|
|
68
68
|
"pithy_auth_rotated_tokens",
|
|
69
69
|
"pithy_auth_user_lifecycle",
|
|
70
|
+
"pithy_auth_verification_outcomes",
|
|
70
71
|
"pithy_auth_sessions",
|
|
71
72
|
"pithy_auth_users",
|
|
72
73
|
"pithy_auth_verifications",
|
|
@@ -140,6 +141,11 @@ export interface LiveApp {
|
|
|
140
141
|
* happened rather than a code that was blank.
|
|
141
142
|
*/
|
|
142
143
|
mailedOtp(to: string): Promise<string | null>;
|
|
144
|
+
/**
|
|
145
|
+
* The app database, for a suite that has to put a row where time would have put it — a rotation
|
|
146
|
+
* ledger entry aged past its grace window — or count what a route left behind.
|
|
147
|
+
*/
|
|
148
|
+
db: D1Database;
|
|
143
149
|
/** Stop the server and dispose the runtime. Always from a `finally` or an `afterAll`. */
|
|
144
150
|
close(): Promise<void>;
|
|
145
151
|
}
|
|
@@ -196,7 +202,9 @@ export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
|
|
|
196
202
|
}),
|
|
197
203
|
resolveGithubUserInfo: undefined,
|
|
198
204
|
enqueueEmail: emailCapability.enqueue,
|
|
199
|
-
turnstile: options.turnstile
|
|
205
|
+
turnstile: options.turnstile
|
|
206
|
+
? { mode: options.turnstile.mode, token: { field: "cf-turnstile-response" } }
|
|
207
|
+
: undefined,
|
|
200
208
|
};
|
|
201
209
|
|
|
202
210
|
const app = buildApp(wiring, events);
|
|
@@ -209,6 +217,7 @@ export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
|
|
|
209
217
|
basePath: options.basePath,
|
|
210
218
|
callbackUrl: (provider) => `${origin}${options.basePath}/callback/${provider}`,
|
|
211
219
|
events,
|
|
220
|
+
db,
|
|
212
221
|
enqueued: async () => {
|
|
213
222
|
const rows = await db.prepare("select template, to_address from pithy_email_jobs order by rowid").all();
|
|
214
223
|
return (rows.results as { template: string; to_address: string }[]).map((row) => ({
|