@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,68 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { Kysely } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/** The four state columns, in the order `up` adds them and `down` takes them away in reverse. */
|
|
8
|
+
const STATE_COLUMNS = ["suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"] as const;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The account lifecycle (#620): whether an account is suspended or deleted, and the record of how it got
|
|
12
|
+
* there.
|
|
13
|
+
*
|
|
14
|
+
* **Four columns on `pithy_auth_users`, so a session read already carries the state.** Better Auth loads the
|
|
15
|
+
* user row for every session it resolves, and returns these because `../data/kitFields.ts` declares them —
|
|
16
|
+
* so refusing a suspended account costs no query on the request that is refused, and none on the requests
|
|
17
|
+
* that are not.
|
|
18
|
+
*
|
|
19
|
+
* **One kit-owned table beside them, `pithy_auth_user_lifecycle`**, holding every transition with its
|
|
20
|
+
* actor, its reason and its time. The columns say what is true now; the table says what happened. No
|
|
21
|
+
* foreign key from it to the user: a purge erases the user row, and this table is the record that must
|
|
22
|
+
* outlive it (`../data/userLifecycle.ts`).
|
|
23
|
+
*
|
|
24
|
+
* **`integer`, not `text`, unlike every Better Auth date on the same table.** Better Auth writes those, as
|
|
25
|
+
* ISO-8601. Nothing but the kit writes these — they are `input: false` — so they take the house ms-epoch
|
|
26
|
+
* convention, and `type: "number"` in `kitFields.ts` keeps Better Auth from converting what it reads back.
|
|
27
|
+
*
|
|
28
|
+
* **Nullable, with no backfill.** Every account that exists when this runs is in neither state, and null is
|
|
29
|
+
* exactly that. SQLite would refuse `ADD COLUMN … NOT NULL` without a constant default anyway.
|
|
30
|
+
*
|
|
31
|
+
* **A `0004`, appended, never folded into `0001`.** `@pithy-sh/auth` has shipped, so its chain is history.
|
|
32
|
+
*/
|
|
33
|
+
export const auth_0004_user_lifecycle: Migration = {
|
|
34
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
35
|
+
for (const column of STATE_COLUMNS) {
|
|
36
|
+
await db.schema.alterTable("pithyAuthUsers").addColumn(column, "integer").execute();
|
|
37
|
+
}
|
|
38
|
+
await db.schema
|
|
39
|
+
.createTable("pithyAuthUserLifecycle")
|
|
40
|
+
.addColumn("id", "integer", (c) => c.primaryKey().autoIncrement())
|
|
41
|
+
.addColumn("userId", "text", (c) => c.notNull())
|
|
42
|
+
.addColumn("action", "text", (c) => c.notNull())
|
|
43
|
+
.addColumn("actorType", "text", (c) => c.notNull())
|
|
44
|
+
.addColumn("actorId", "text")
|
|
45
|
+
.addColumn("reason", "text")
|
|
46
|
+
.addColumn("suspendedUntil", "integer")
|
|
47
|
+
.addColumn("step", "text")
|
|
48
|
+
.addColumn("createdAt", "integer", (c) => c.notNull())
|
|
49
|
+
.execute();
|
|
50
|
+
// A user's history, newest first, is the one read this table serves — the refusal that shows a
|
|
51
|
+
// suspended person the reason, and an operator's view of what happened to one account. The trailing
|
|
52
|
+
// id orders two transitions written in the same millisecond the way they were written.
|
|
53
|
+
await db.schema
|
|
54
|
+
.createIndex("pithyAuthUserLifecycleUserIdIdx")
|
|
55
|
+
.on("pithyAuthUserLifecycle")
|
|
56
|
+
.columns(["userId", "id"])
|
|
57
|
+
.execute();
|
|
58
|
+
},
|
|
59
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
60
|
+
// The exact inverse. Nothing else references this table or these columns, and SQLite has supported
|
|
61
|
+
// `DROP COLUMN` since 3.35, which D1 is well past.
|
|
62
|
+
await db.schema.dropIndex("pithyAuthUserLifecycleUserIdIdx").execute();
|
|
63
|
+
await db.schema.dropTable("pithyAuthUserLifecycle").execute();
|
|
64
|
+
for (const column of [...STATE_COLUMNS].reverse()) {
|
|
65
|
+
await db.schema.alterTable("pithyAuthUsers").dropColumn(column).execute();
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { type Kysely, type SqlBool, sql } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/** The one index this adds: at most one `purged` row per account. */
|
|
8
|
+
const PURGED_ONCE_INDEX = "pithyAuthUserLifecyclePurgedOnceIdx";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The purge, once (#622): what a deletion asked of its last mail, and a constraint that a purge finishes once.
|
|
12
|
+
*
|
|
13
|
+
* **`notify` on `pithy_auth_user_lifecycle`.** A hard deletion with `notify: false` asks the purge to send no
|
|
14
|
+
* deletion-complete mail, and the purge that sends it is not always the one the deletion started: with no
|
|
15
|
+
* purge Workflow bound, or a start that failed, the daily pass starts it, and the pass has no request to read
|
|
16
|
+
* the choice from. So the deletion's own history row carries it, and the purge reads it there. `1` or `0` on a
|
|
17
|
+
* hard deletion's `deleted` row that named it; null on every other row, and on one that did not.
|
|
18
|
+
*
|
|
19
|
+
* **A unique partial index on `userId` where `action` is `purged`.** Two purges of one account can overlap —
|
|
20
|
+
* the daily pass and a hard deletion's own, or a purge still retrying when the next pass starts another — and
|
|
21
|
+
* both reach `complete`. A read-then-insert lets both write the record, and both fire `onUserPurged`. With the
|
|
22
|
+
* index the insert is the check: the one that lands fires, the other finds the row there and does nothing.
|
|
23
|
+
*
|
|
24
|
+
* **A `0005`, appended.** `0004` has shipped. No backfill, and no duplicate to clean up first: nothing before
|
|
25
|
+
* this release ran a purge, so no account has a `purged` row yet.
|
|
26
|
+
*/
|
|
27
|
+
export const auth_0005_purge_once: Migration = {
|
|
28
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
29
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("notify", "integer").execute();
|
|
30
|
+
await db.schema
|
|
31
|
+
.createIndex(PURGED_ONCE_INDEX)
|
|
32
|
+
.on("pithyAuthUserLifecycle")
|
|
33
|
+
.column("userId")
|
|
34
|
+
.unique()
|
|
35
|
+
.where(sql<SqlBool>`action = 'purged'`)
|
|
36
|
+
.execute();
|
|
37
|
+
},
|
|
38
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
39
|
+
await db.schema.dropIndex(PURGED_ONCE_INDEX).execute();
|
|
40
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("notify").execute();
|
|
41
|
+
},
|
|
42
|
+
};
|
|
@@ -279,8 +279,22 @@ export interface AuthPluginPlan {
|
|
|
279
279
|
migrations: Record<string, Migration>;
|
|
280
280
|
/** One entry per plugin, whatever it declared — what `pithy doctor` reports. */
|
|
281
281
|
extensions: { id: string; tables: string[] }[];
|
|
282
|
+
/**
|
|
283
|
+
* The tables a plugin created that are keyed to one account by a `userId` column — `twoFactor`, `passkey`,
|
|
284
|
+
* an API key's table — which the purge erases and the export reads with auth's own (#622). Every one of them
|
|
285
|
+
* holds rows about the person and nothing else does, because a plugin's tables have no foreign key to cascade
|
|
286
|
+
* from the user row. `organization`'s are not here: a membership is the organization's as much as the
|
|
287
|
+
* person's, and what erasing one means is #623's.
|
|
288
|
+
*/
|
|
289
|
+
userTables: string[];
|
|
282
290
|
}
|
|
283
291
|
|
|
292
|
+
/** The column a plugin's table names its account by — Better Auth's own convention for a user-keyed row. */
|
|
293
|
+
const USER_KEY = "userId";
|
|
294
|
+
|
|
295
|
+
/** Plugins whose user-keyed tables the purge leaves to their own issue — see {@link AuthPluginPlan.userTables}. */
|
|
296
|
+
const PURGE_DEFERRED_PLUGINS: readonly string[] = ["organization"];
|
|
297
|
+
|
|
284
298
|
/**
|
|
285
299
|
* Derive everything the auth capability needs from an adopter's plugin list, in one pass.
|
|
286
300
|
*
|
|
@@ -297,6 +311,7 @@ export interface AuthPluginPlan {
|
|
|
297
311
|
export function authPluginPlan(plugins: readonly BetterAuthPlugin[]): AuthPluginPlan {
|
|
298
312
|
const migrations: Record<string, Migration> = {};
|
|
299
313
|
const extensions: { id: string; tables: string[] }[] = [];
|
|
314
|
+
const userTables: string[] = [];
|
|
300
315
|
const claimed = new Map<string, string>();
|
|
301
316
|
|
|
302
317
|
for (const plugin of plugins) {
|
|
@@ -319,6 +334,9 @@ export function authPluginPlan(plugins: readonly BetterAuthPlugin[]): AuthPlugin
|
|
|
319
334
|
});
|
|
320
335
|
}
|
|
321
336
|
claimed.set(table.name, plugin.id);
|
|
337
|
+
if (!PURGE_DEFERRED_PLUGINS.includes(plugin.id) && table.columns.some((column) => column.name === USER_KEY)) {
|
|
338
|
+
userTables.push(table.name);
|
|
339
|
+
}
|
|
322
340
|
}
|
|
323
341
|
|
|
324
342
|
if (delta.tables.length === 0 && delta.columns.length === 0) continue;
|
|
@@ -333,5 +351,5 @@ export function authPluginPlan(plugins: readonly BetterAuthPlugin[]): AuthPlugin
|
|
|
333
351
|
migrations[key] = pluginMigration(delta);
|
|
334
352
|
}
|
|
335
353
|
|
|
336
|
-
return { migrations, extensions };
|
|
354
|
+
return { migrations, extensions, userTables };
|
|
337
355
|
}
|
package/src/migrations/set.ts
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
import { auth_0001_init } from "./0001_init";
|
|
5
5
|
import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at";
|
|
6
6
|
import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullable";
|
|
7
|
+
import { auth_0004_user_lifecycle } from "./0004_user_lifecycle";
|
|
8
|
+
import { auth_0005_purge_once } from "./0005_purge_once";
|
|
7
9
|
|
|
8
10
|
/**
|
|
9
11
|
* Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
|
|
@@ -15,11 +17,13 @@ import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullabl
|
|
|
15
17
|
* migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
|
|
16
18
|
* was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
|
|
17
19
|
*
|
|
18
|
-
* `0003` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
|
|
20
|
+
* `0003`, `0004` and `0005` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
|
|
19
21
|
* its subject is that one migration's own `up` and `down`, so it names it directly.
|
|
20
22
|
*/
|
|
21
23
|
export const AUTH_MIGRATIONS = {
|
|
22
24
|
"0001_init": auth_0001_init,
|
|
23
25
|
"0002_session_authenticated_at": auth_0002_session_authenticated_at,
|
|
24
26
|
"0003_account_issuer_nullable": auth_0003_account_issuer_nullable,
|
|
27
|
+
"0004_user_lifecycle": auth_0004_user_lifecycle,
|
|
28
|
+
"0005_purge_once": auth_0005_purge_once,
|
|
25
29
|
} as const;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import type { PurgeContext, PurgeContribution } from "@pithy-sh/core/src/capability/purge";
|
|
6
|
+
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { type CompiledQuery, type Kysely, type SqlBool, sql } from "kysely";
|
|
8
|
+
import { Account, Session, User } from "../data/betterAuth";
|
|
9
|
+
import { Device } from "../data/device";
|
|
10
|
+
import { type AuthDatabase, authDatabase } from "../data/tables";
|
|
11
|
+
import { UserLifecycleEvent } from "../data/userLifecycle";
|
|
12
|
+
import type { AuthUserExport } from "../http/responses";
|
|
13
|
+
import { authUserExportView } from "../http/views";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Auth's own purge contribution (#622): what erasing one person means for the `pithy_auth_*` tables, and what
|
|
17
|
+
* exporting them hands back.
|
|
18
|
+
*
|
|
19
|
+
* **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
|
+
* and its backup codes, a passkey, an API key. Those tables have no foreign key to the user row, so deleting
|
|
23
|
+
* 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
|
+
* erased, and it names the account by id and holds nothing else about the person (`../data/userLifecycle.ts`).
|
|
25
|
+
* The rate-limit and JWKS tables are keyed to no person and are not touched.
|
|
26
|
+
*
|
|
27
|
+
* **One transaction.** The deletes are one `d1.batch()`, which D1 runs as one, so a failure leaves every row
|
|
28
|
+
* where it was and the retried step erases the lot. **Idempotent**, as the contract requires: a second run
|
|
29
|
+
* finds no rows and deletes nothing, and succeeds.
|
|
30
|
+
*
|
|
31
|
+
* The purge Workflow runs this step **last**, after every other capability's and after the deletion-complete
|
|
32
|
+
* mail, because the address that mail is sent to lives on the user row this deletes.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** The one sentence the purge records with this step. */
|
|
36
|
+
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.";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A plugin table's column that holds a credential — a TOTP secret, backup codes, a key or its hash, a token.
|
|
41
|
+
* The export leaves these out, as it leaves out a session's token and a provider's: an access request is
|
|
42
|
+
* answered with what is held, never with the means to sign in as the person.
|
|
43
|
+
*/
|
|
44
|
+
const CREDENTIAL_COLUMN = /secret|token|key|code|hash|password|credential/i;
|
|
45
|
+
|
|
46
|
+
/** 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>>> {
|
|
48
|
+
return db as unknown as Kysely<Record<string, Record<string, unknown>>>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 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 {
|
|
53
|
+
const binding = env[database];
|
|
54
|
+
if (typeof binding !== "object" || binding === null) {
|
|
55
|
+
throw new InternalError({
|
|
56
|
+
message: "The auth database is not bound, so this purge step could not run.",
|
|
57
|
+
action: `Bind the ${database} D1 database to the Worker that runs the purge.`,
|
|
58
|
+
detail: `auth purge contribution found no ${database} binding on the env`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return binding as D1Database;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `%` and `_` escaped, so an address is matched as itself inside a LIKE pattern and nothing wider. */
|
|
65
|
+
function literal(value: string): string {
|
|
66
|
+
return value.replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Bind a compiled statement to D1, so it can join a `batch`. */
|
|
70
|
+
function prepared(d1: D1Database, compiled: CompiledQuery) {
|
|
71
|
+
return d1.prepare(compiled.sql).bind(...(compiled.parameters as unknown[]));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Erase one account's `pithy_auth_*` rows, its history excepted. Succeeds, having found nothing, when they are
|
|
76
|
+
* already gone.
|
|
77
|
+
*
|
|
78
|
+
* The pending sign-in codes are found by the address, which is why it is read first: an email OTP's identifier
|
|
79
|
+
* is `<type>-otp-<address>`, and a magic link's value is JSON carrying `"email":"<address>"`. With the user row
|
|
80
|
+
* already gone there is no address to look for, and none is needed — a code lives for minutes.
|
|
81
|
+
*/
|
|
82
|
+
export async function eraseAuthUser(
|
|
83
|
+
db: AuthDatabase,
|
|
84
|
+
d1: D1Database,
|
|
85
|
+
userId: string,
|
|
86
|
+
pluginTables: readonly string[] = [],
|
|
87
|
+
): Promise<void> {
|
|
88
|
+
const user = await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst();
|
|
89
|
+
const statements = [
|
|
90
|
+
db.deleteFrom("pithyAuthSessions").where("userId", "=", userId),
|
|
91
|
+
db.deleteFrom("pithyAuthAccounts").where("userId", "=", userId),
|
|
92
|
+
db.deleteFrom("pithyAuthDevices").where("userId", "=", userId),
|
|
93
|
+
db.deleteFrom("pithyAuthRotatedTokens").where("userId", "=", userId),
|
|
94
|
+
].map((query) => prepared(d1, query.compile()));
|
|
95
|
+
// A plugin's rows, in the same batch: `CamelCasePlugin` snake-cases the table and `user_id` as it does for
|
|
96
|
+
// the plugin's own migration, so the names match what `pithy migrate` created.
|
|
97
|
+
for (const table of pluginTables) {
|
|
98
|
+
statements.push(prepared(d1, untyped(db).deleteFrom(table).where("userId", "=", userId).compile()));
|
|
99
|
+
}
|
|
100
|
+
if (user) {
|
|
101
|
+
const address = literal(user.email);
|
|
102
|
+
const otp = `%-otp-${address}`;
|
|
103
|
+
const changingFrom = `%-otp-${address}-%`;
|
|
104
|
+
const link = `%"email":${literal(JSON.stringify(user.email))}%`;
|
|
105
|
+
// Raw SQL for the predicate, for `users.ts`'s reason: SQLite's `ESCAPE` belongs to the `LIKE` operator, so
|
|
106
|
+
// there is no expression-builder form of it. Both columns are single words, so `CamelCasePlugin` has
|
|
107
|
+
// nothing to rewrite.
|
|
108
|
+
const pending = db
|
|
109
|
+
.deleteFrom("pithyAuthVerifications")
|
|
110
|
+
.where(
|
|
111
|
+
sql<SqlBool>`(identifier like ${otp} escape '\\' or identifier like ${changingFrom} escape '\\' or value like ${link} escape '\\')`,
|
|
112
|
+
);
|
|
113
|
+
statements.push(prepared(d1, pending.compile()));
|
|
114
|
+
}
|
|
115
|
+
statements.push(prepared(d1, db.deleteFrom("pithyAuthUsers").where("id", "=", userId).compile()));
|
|
116
|
+
await d1.batch(statements);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* What auth holds about one account, for an export: the account, its sessions, providers, devices and
|
|
121
|
+
* history, every list whole. `null` when there is no account to export.
|
|
122
|
+
*/
|
|
123
|
+
export async function exportAuthUser(
|
|
124
|
+
db: AuthDatabase,
|
|
125
|
+
userId: string,
|
|
126
|
+
pluginTables: readonly string[] = [],
|
|
127
|
+
): Promise<AuthUserExport | null> {
|
|
128
|
+
const row = await db.selectFrom("pithyAuthUsers").selectAll().where("id", "=", userId).executeTakeFirst();
|
|
129
|
+
if (!row) return null;
|
|
130
|
+
const [sessions, accounts, devices, history, plugins] = await Promise.all([
|
|
131
|
+
db
|
|
132
|
+
.selectFrom("pithyAuthSessions")
|
|
133
|
+
.selectAll()
|
|
134
|
+
.where("userId", "=", userId)
|
|
135
|
+
.orderBy("createdAt", "desc")
|
|
136
|
+
.orderBy("id", "desc")
|
|
137
|
+
.execute(),
|
|
138
|
+
// Two columns, never `select *`: the account row holds the provider's tokens, and they are never loaded.
|
|
139
|
+
db
|
|
140
|
+
.selectFrom("pithyAuthAccounts")
|
|
141
|
+
.select(["providerId", "createdAt"])
|
|
142
|
+
.where("userId", "=", userId)
|
|
143
|
+
.orderBy("providerId", "asc")
|
|
144
|
+
.execute(),
|
|
145
|
+
db
|
|
146
|
+
.selectFrom("pithyAuthDevices")
|
|
147
|
+
.selectAll()
|
|
148
|
+
.where("userId", "=", userId)
|
|
149
|
+
.orderBy("lastSeenAt", "desc")
|
|
150
|
+
.orderBy("id", "desc")
|
|
151
|
+
.execute(),
|
|
152
|
+
db.selectFrom("pithyAuthUserLifecycle").selectAll().where("userId", "=", userId).orderBy("id", "asc").execute(),
|
|
153
|
+
Promise.all(pluginTables.map(async (table) => [table, await pluginRows(db, table, userId)] as const)),
|
|
154
|
+
]);
|
|
155
|
+
return authUserExportView({
|
|
156
|
+
user: User.parse(row),
|
|
157
|
+
sessions: sessions.map((session) => Session.parse(session)),
|
|
158
|
+
accounts: accounts.map((account) => Account.pick({ providerId: true, createdAt: true }).parse(account)),
|
|
159
|
+
devices: devices.map((device) => Device.parse(device)),
|
|
160
|
+
history: history.map((event) => UserLifecycleEvent.parse(event)),
|
|
161
|
+
plugins: Object.fromEntries(plugins),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 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>[]> {
|
|
167
|
+
const rows = await untyped(db).selectFrom(table).selectAll().where("userId", "=", userId).execute();
|
|
168
|
+
return rows.map((row) =>
|
|
169
|
+
Object.fromEntries(Object.entries(row).filter(([column]) => !CREDENTIAL_COLUMN.test(column))),
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The contribution `auth()` declares, over the D1 binding its config names. The export of an account that is
|
|
175
|
+
* not there is an empty object, which the route never reaches: it answers 404 before it reads any capability.
|
|
176
|
+
*/
|
|
177
|
+
export function authPurgeContribution(database: string, pluginTables: readonly string[] = []): PurgeContribution {
|
|
178
|
+
const open = (context: PurgeContext) => {
|
|
179
|
+
const d1 = bindingOf(context.env, database);
|
|
180
|
+
return { d1, db: authDatabase(d1) };
|
|
181
|
+
};
|
|
182
|
+
return {
|
|
183
|
+
subject: "user",
|
|
184
|
+
summary: AUTH_PURGE_SUMMARY,
|
|
185
|
+
erase: async (context) => {
|
|
186
|
+
const { d1, db } = open(context);
|
|
187
|
+
await eraseAuthUser(db, d1, context.subject.id, pluginTables);
|
|
188
|
+
},
|
|
189
|
+
export: async (context) => (await exportAuthUser(open(context).db, context.subject.id, pluginTables)) ?? {},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { WorkflowRetryPolicy } from "@pithy-sh/core/src/workflow/faults";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* **What the purge's own steps retry, and what they refuse to** (#622).
|
|
8
|
+
*
|
|
9
|
+
* The purge's own steps — reading whether the account is due, the last mail, the final record — and the daily
|
|
10
|
+
* pass's are D1, and core answers for D1's transient vocabulary through `withD1Retry`. There is no `auth/*`
|
|
11
|
+
* code a second attempt can answer differently, so the record is empty, and that is a statement: an account
|
|
12
|
+
* that is not due, or a binding that is not there, is the same answer next time.
|
|
13
|
+
*
|
|
14
|
+
* **A capability's erase step is not classified here, deliberately.** It runs the contribution's own code —
|
|
15
|
+
* another capability's, or the adopter's — whose fault vocabulary the kit cannot know, and the contract makes
|
|
16
|
+
* every `erase` idempotent precisely so that any fault in it can be retried. So the purge hands those steps to
|
|
17
|
+
* the platform's own retry, with its backoff: a failing contribution retries alone, and the steps that finished
|
|
18
|
+
* are served from the journal. That is the classification, stated at its one site, `./run.ts`.
|
|
19
|
+
*
|
|
20
|
+
* **The cron is the outer retry.** A pass whose `start` step fails is run again the next day, and a purge whose
|
|
21
|
+
* instance failed is started again for the account still past its window.
|
|
22
|
+
*/
|
|
23
|
+
export const authWorkflowRetry: WorkflowRetryPolicy = {
|
|
24
|
+
capability: "auth",
|
|
25
|
+
retryable: {},
|
|
26
|
+
};
|
package/src/purge/run.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { PurgeContext, PurgeStep } from "@pithy-sh/core/src/capability/purge";
|
|
5
|
+
import {
|
|
6
|
+
classifiedSteps,
|
|
7
|
+
type TerminalErrorConstructor,
|
|
8
|
+
type WorkflowStepLike,
|
|
9
|
+
} from "@pithy-sh/core/src/workflow/faults";
|
|
10
|
+
import {
|
|
11
|
+
completePurge,
|
|
12
|
+
type DuePurge,
|
|
13
|
+
duePurges,
|
|
14
|
+
type LifecycleDeps,
|
|
15
|
+
mailPurgeComplete,
|
|
16
|
+
purgeSubject,
|
|
17
|
+
recordPurgeStep,
|
|
18
|
+
} from "../lifecycle/transitions";
|
|
19
|
+
import { authWorkflowRetry } from "./retryPolicy";
|
|
20
|
+
import { AUTH_CAPABILITY, type AuthPurgeDueParams, type AuthPurgeParams } from "./specs";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The purge, as steps (#622) — the bodies `./workflow.ts` hands a Workflow's step runner to.
|
|
24
|
+
*
|
|
25
|
+
* ## One step per contribution, and the order they run in
|
|
26
|
+
*
|
|
27
|
+
* 1. **`due`** — is the account deleted, and has its window closed? A restored account, one inside its window,
|
|
28
|
+
* and one already erased all end the run here, having erased nothing. This is the one check a cron-started
|
|
29
|
+
* purge and a hard deletion's both pass through, so re-running a purge for the same subject exits cleanly.
|
|
30
|
+
* 2. **`erase <capability>`** — one step per composed contribution, in composition order, each recording that it
|
|
31
|
+
* ran in `pithy_auth_user_lifecycle`. Handed to the platform's retry unclassified: an `erase` is idempotent by
|
|
32
|
+
* contract and runs code the kit did not write, so any fault in it is worth another attempt (`./retryPolicy.ts`).
|
|
33
|
+
* A failing contribution retries alone, and the ones that finished are served from the journal.
|
|
34
|
+
* 3. **`mail`** — the deletion-complete mail, **before the address is erased**: every other capability's rows are
|
|
35
|
+
* gone, and auth's, which hold the address, are not yet. The address is read in the step, never carried out of
|
|
36
|
+
* one, so it is in no Workflow's journal.
|
|
37
|
+
* 4. **`erase auth`** — auth's own contribution, last for that reason.
|
|
38
|
+
* 5. **`complete`** — the `purged` record, the audit event, `onUserPurged`. Once.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/** What a purge does with the account's own records — the transitions, over one set of dependencies. */
|
|
42
|
+
export interface PurgeOps {
|
|
43
|
+
/** Whether the account is due: deleted, with its window closed. `gone` when there is no account. */
|
|
44
|
+
due(userId: string): Promise<"due" | "not_due" | "gone">;
|
|
45
|
+
/** Record that one capability's step erased its rows. */
|
|
46
|
+
recordStep(userId: string, step: string, summary: string): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Send the deletion-complete mail to the account's address, if it is still there to read, unless this purge's
|
|
49
|
+
* `notify` or the deletion's own saved choice is false. Says whether.
|
|
50
|
+
*/
|
|
51
|
+
mailComplete(userId: string, notify: boolean | undefined): Promise<boolean>;
|
|
52
|
+
/** Write the `purged` record, the audit event and the hook. Says whether this call wrote them. */
|
|
53
|
+
complete(userId: string): Promise<boolean>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The operations, over the lifecycle transitions. */
|
|
57
|
+
export function purgeOps(deps: LifecycleDeps): PurgeOps {
|
|
58
|
+
return {
|
|
59
|
+
due: async (userId) => (await purgeSubject(deps, userId)).state,
|
|
60
|
+
recordStep: (userId, step, summary) => recordPurgeStep(deps, { userId, step, summary }),
|
|
61
|
+
mailComplete: async (userId, notify) => {
|
|
62
|
+
const subject = await purgeSubject(deps, userId);
|
|
63
|
+
if (subject.state !== "due") return false;
|
|
64
|
+
// Either can silence it: the parameter a hard deletion started this purge with, or the choice that deletion
|
|
65
|
+
// wrote on its history row — the one a purge the daily pass started still has (#622).
|
|
66
|
+
const silenced = notify === false || subject.notify === false;
|
|
67
|
+
return (await mailPurgeComplete(deps, { recipient: subject.recipient, ...(silenced ? { notify: false } : {}) }))
|
|
68
|
+
.mailed;
|
|
69
|
+
},
|
|
70
|
+
complete: async (userId) => (await completePurge(deps, { userId })).changed,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** What one purge did: the account, how it ended, and the capabilities whose rows it erased. */
|
|
75
|
+
export interface PurgeOutcome {
|
|
76
|
+
/** The account. */
|
|
77
|
+
readonly userId: string;
|
|
78
|
+
/** `purged`, or why nothing was erased: `not_due` (restored, or inside its window) and `gone` (no account). */
|
|
79
|
+
readonly state: "purged" | "not_due" | "gone";
|
|
80
|
+
/** Every step that erased its rows, in the order it ran. Empty when nothing was erased. */
|
|
81
|
+
readonly erased: readonly string[];
|
|
82
|
+
/** Whether the deletion-complete mail was enqueued. */
|
|
83
|
+
readonly mailed: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** What one purge reads its plan from: the composed contributions, this run's env, and its operations. */
|
|
87
|
+
export interface PurgeRun {
|
|
88
|
+
/** Every composed purge step for `user`, auth's own among them. */
|
|
89
|
+
readonly steps: readonly PurgeStep[];
|
|
90
|
+
/** This run's bindings, handed to each contribution. */
|
|
91
|
+
readonly env: Record<string, unknown>;
|
|
92
|
+
/** The account's own records. */
|
|
93
|
+
readonly ops: PurgeOps;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Run one account's purge, one step per contribution, auth's last. See the file header for the order. */
|
|
97
|
+
export async function purgeUser(
|
|
98
|
+
run: PurgeRun,
|
|
99
|
+
step: WorkflowStepLike,
|
|
100
|
+
terminalError: TerminalErrorConstructor,
|
|
101
|
+
params: AuthPurgeParams,
|
|
102
|
+
): Promise<PurgeOutcome> {
|
|
103
|
+
const own = classifiedSteps(step, authWorkflowRetry, terminalError);
|
|
104
|
+
const userId = params.userId;
|
|
105
|
+
const state = await own.do("due", () => run.ops.due(userId));
|
|
106
|
+
if (state !== "due") return { userId, state, erased: [], mailed: false };
|
|
107
|
+
|
|
108
|
+
const context: PurgeContext = { subject: { type: "user", id: userId }, env: run.env };
|
|
109
|
+
const auth = run.steps.filter((each) => each.step === AUTH_CAPABILITY);
|
|
110
|
+
const others = run.steps.filter((each) => each.step !== AUTH_CAPABILITY);
|
|
111
|
+
const erased: string[] = [];
|
|
112
|
+
for (const each of others) {
|
|
113
|
+
erased.push(await eraseStep(step, run.ops, each, context));
|
|
114
|
+
}
|
|
115
|
+
const mailed = await own.do("mail", () => run.ops.mailComplete(userId, params.notify));
|
|
116
|
+
for (const each of auth) {
|
|
117
|
+
erased.push(await eraseStep(step, run.ops, each, context));
|
|
118
|
+
}
|
|
119
|
+
await own.do("complete", () => run.ops.complete(userId));
|
|
120
|
+
return { userId, state: "purged", erased, mailed };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* One capability's step: erase, then record that it ran. On the platform's own retry, unclassified — see the
|
|
125
|
+
* file header. Recorded inside the same step, so a step that erased and failed to record is retried whole, and
|
|
126
|
+
* the second erase finds nothing.
|
|
127
|
+
*/
|
|
128
|
+
function eraseStep(step: WorkflowStepLike, ops: PurgeOps, each: PurgeStep, context: PurgeContext): Promise<string> {
|
|
129
|
+
return step.do(`erase ${each.step}`, async () => {
|
|
130
|
+
await each.contribution.erase(context);
|
|
131
|
+
await ops.recordStep(context.subject.id, each.step, each.contribution.summary);
|
|
132
|
+
return each.step;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** How many purges one `start` step dispatches — a page, so one pass over a backlog is a bounded number of steps. */
|
|
137
|
+
export const PURGE_START_PAGE = 50;
|
|
138
|
+
|
|
139
|
+
/** The default size of one daily pass. */
|
|
140
|
+
export const PURGE_DUE_DEFAULT_LIMIT = 500;
|
|
141
|
+
|
|
142
|
+
/** What the daily pass reads and starts through. */
|
|
143
|
+
export interface PurgeDueRun {
|
|
144
|
+
/** Every account whose purge is due, oldest first, at most `limit`, with the deletion it is due under. */
|
|
145
|
+
due(limit: number): Promise<DuePurge[]>;
|
|
146
|
+
/**
|
|
147
|
+
* Start one account's purge — under the instance id its deletion names, so a start repeated is the same one.
|
|
148
|
+
* Says whether the purge is running: started now, or found already started. `false` when it could not be
|
|
149
|
+
* started, and the pass does not count it.
|
|
150
|
+
*/
|
|
151
|
+
start(due: DuePurge): Promise<boolean>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The daily pass (#622): list every account past its window, and start a purge for each — in pages, one step
|
|
156
|
+
* each, so a pass that dies part-way resumes after the page it finished rather than starting every purge
|
|
157
|
+
* again. An account still inside its window is not listed, so it is not started.
|
|
158
|
+
*/
|
|
159
|
+
export async function startDuePurges(
|
|
160
|
+
run: PurgeDueRun,
|
|
161
|
+
step: WorkflowStepLike,
|
|
162
|
+
terminalError: TerminalErrorConstructor,
|
|
163
|
+
params: AuthPurgeDueParams,
|
|
164
|
+
): Promise<{ started: number }> {
|
|
165
|
+
const own = classifiedSteps(step, authWorkflowRetry, terminalError);
|
|
166
|
+
const limit = params.limit ?? PURGE_DUE_DEFAULT_LIMIT;
|
|
167
|
+
const due = await own.do("due", () => run.due(limit));
|
|
168
|
+
let started = 0;
|
|
169
|
+
for (let page = 0; page * PURGE_START_PAGE < due.length; page += 1) {
|
|
170
|
+
const ids = due.slice(page * PURGE_START_PAGE, (page + 1) * PURGE_START_PAGE);
|
|
171
|
+
started += await own.do(`start ${page + 1}`, async () => {
|
|
172
|
+
// Counted from what each start answered, never from the page's length: a purge the binding could not start
|
|
173
|
+
// is not running, and `{ started }` is what an operator reads to learn whether they are.
|
|
174
|
+
let running = 0;
|
|
175
|
+
for (const each of ids) if (await run.start(each)) running += 1;
|
|
176
|
+
return running;
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return { started };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The daily pass's reads, over the lifecycle transitions. */
|
|
183
|
+
export function duePurgesOf(deps: LifecycleDeps): PurgeDueRun["due"] {
|
|
184
|
+
return (limit) => duePurges(deps, limit);
|
|
185
|
+
}
|