@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
package/src/index.ts
CHANGED
package/src/instance/auth.ts
CHANGED
|
@@ -17,7 +17,9 @@ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
|
|
|
17
17
|
import type { AuthDatabase } from "../data/tables";
|
|
18
18
|
import { parseDeviceMeta, registerDevice } from "../device/registry";
|
|
19
19
|
import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
|
|
20
|
+
import { verificationLedger } from "../ledger/record";
|
|
20
21
|
import { admitsDeletionSignIn, lifecycleRefusalFor } from "../lifecycle/enforce";
|
|
22
|
+
import { recordActivity } from "../lifecycle/inactivity";
|
|
21
23
|
import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
|
|
22
24
|
import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
|
|
23
25
|
import { microsoftProfileToUser } from "./microsoftEmail";
|
|
@@ -378,6 +380,9 @@ export type AuthInstance<Plugins extends readonly BetterAuthPlugin[] = readonly
|
|
|
378
380
|
* UUIDs; rate limiting is durable (D1-backed) since memory limiting is per-isolate on Workers.
|
|
379
381
|
*/
|
|
380
382
|
export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps: AuthInstanceDeps<Plugins>) {
|
|
383
|
+
// The verification ledger (#829): written from three database hooks below and from the send callback the kit's
|
|
384
|
+
// own plugins close over, so one instance of it pairs what each of them saw in a request. See `../ledger/record.ts`.
|
|
385
|
+
const ledger = verificationLedger(deps.db);
|
|
381
386
|
return betterAuth({
|
|
382
387
|
appName: "Pithy",
|
|
383
388
|
baseURL: deps.baseURL,
|
|
@@ -412,6 +417,27 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
412
417
|
// outcome is by throwing, which is what this is.
|
|
413
418
|
onAPIError: { throw: true },
|
|
414
419
|
databaseHooks: {
|
|
420
|
+
/**
|
|
421
|
+
* The verification ledger's two hooks on Better Auth's own verification rows (#829).
|
|
422
|
+
*
|
|
423
|
+
* **`create.after` remembers the row** — a sign-in link or code about to be sent, OAuth state, or a wrong
|
|
424
|
+
* code re-created with one more attempt counted; `../ledger/record.ts` tells them apart by what follows.
|
|
425
|
+
* **`delete.before` remembers the row about to be consumed**, and changes nothing: it returns nothing, so it
|
|
426
|
+
* never vetoes, and it is not a `delete.after` because claiming a verification removal the way
|
|
427
|
+
* `claimedDelete` does would delete the row before the consume could read it.
|
|
428
|
+
*/
|
|
429
|
+
verification: {
|
|
430
|
+
create: {
|
|
431
|
+
after: async (verification, ctx) => {
|
|
432
|
+
await ledger.created(verification, (ctx as { context?: unknown } | null | undefined)?.context);
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
delete: {
|
|
436
|
+
before: async (verification, ctx) => {
|
|
437
|
+
ledger.consuming(verification, (ctx as { context?: unknown } | null | undefined)?.context);
|
|
438
|
+
},
|
|
439
|
+
},
|
|
440
|
+
},
|
|
415
441
|
user: {
|
|
416
442
|
create: {
|
|
417
443
|
// Seeding guard: refuse to create a user whose email a provider has not verified. Every
|
|
@@ -545,6 +571,30 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
545
571
|
});
|
|
546
572
|
return { data: { ...session, deviceId: meta.id, authenticatedAt } };
|
|
547
573
|
},
|
|
574
|
+
/**
|
|
575
|
+
* Stamp the sign-in link or code this session was made from as used (#829), and name the account a
|
|
576
|
+
* sign-up just created. Only a row consumed earlier in this same request is stamped, so a token
|
|
577
|
+
* refresh, an OAuth callback and every other session stamp nothing — see `../ledger/record.ts`.
|
|
578
|
+
* After, because the session exists by now: a sign-in the `before` above refused stamps nothing.
|
|
579
|
+
*/
|
|
580
|
+
after: async (session, ctx) => {
|
|
581
|
+
await ledger.signedIn((ctx as { context?: unknown } | null | undefined)?.context, session.userId);
|
|
582
|
+
// The account's activity clock, which the retention policy's class ages count from. After, so a
|
|
583
|
+
// refused sign-in stamps nothing; swallowed, because the session it records already exists.
|
|
584
|
+
await recordActivity(deps.db, session.userId, new Date()).catch(() => undefined);
|
|
585
|
+
},
|
|
586
|
+
},
|
|
587
|
+
update: {
|
|
588
|
+
/**
|
|
589
|
+
* The activity clock again, for a session that stays open. Better Auth slides a session forward in place
|
|
590
|
+
* once `updateAge` has passed, and that refresh is an update, never a create, so the hook above never
|
|
591
|
+
* sees it. Without this, signing out after weeks of use on one session would read as weeks idle.
|
|
592
|
+
*/
|
|
593
|
+
after: async (session) => {
|
|
594
|
+
const userId = (session as { userId?: unknown } | null)?.userId;
|
|
595
|
+
if (typeof userId !== "string") return;
|
|
596
|
+
await recordActivity(deps.db, userId, new Date()).catch(() => undefined);
|
|
597
|
+
},
|
|
548
598
|
},
|
|
549
599
|
/**
|
|
550
600
|
* Tell whoever keyed state on this session that it has gone, and record that it did.
|
|
@@ -730,6 +780,6 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
730
780
|
// endpoints by id and a later registration wins, so composing the adopter's list first would let
|
|
731
781
|
// it quietly redefine the sign-in this product promises. `assertAdditivePlugins` has already
|
|
732
782
|
// refused a list that names one of the four; this order is what makes that refusal the only way in.
|
|
733
|
-
plugins: [...kitPlugins(deps), ...deps.plugins],
|
|
783
|
+
plugins: [...kitPlugins({ ...deps, ledger }), ...deps.plugins],
|
|
734
784
|
});
|
|
735
785
|
}
|
package/src/instance/plugins.ts
CHANGED
|
@@ -10,8 +10,9 @@ import { emailOTP } from "better-auth/plugins/email-otp";
|
|
|
10
10
|
import { jwt } from "better-auth/plugins/jwt";
|
|
11
11
|
import { magicLink } from "better-auth/plugins/magic-link";
|
|
12
12
|
import { z } from "zod";
|
|
13
|
-
import { markMessageDelivery, SEND_FAULT } from "../audit/evidence";
|
|
13
|
+
import { type AuthEmailDelivery, markMessageDelivery, SEND_FAULT } from "../audit/evidence";
|
|
14
14
|
import { authErrorTranslations } from "../i18n/errorCopy";
|
|
15
|
+
import type { VerificationLedger } from "../ledger/record";
|
|
15
16
|
import type { AuthEmailMessage, SendAuthEmail } from "./auth";
|
|
16
17
|
import { PROVIDER_SIGN_IN_GATE_ID, providerSignInGate } from "./providerSignInGate";
|
|
17
18
|
import { refusalTransportVerdict } from "./refusalTransport";
|
|
@@ -66,6 +67,11 @@ export interface KitPluginDeps {
|
|
|
66
67
|
* built the instance — the schema baseline, a seed, a unit test. See `./providerSignInGate`.
|
|
67
68
|
*/
|
|
68
69
|
requestHeaders?: Headers;
|
|
70
|
+
/**
|
|
71
|
+
* The verification ledger (#829) — told what each send was and which mail carries it, once the email seam
|
|
72
|
+
* has answered. Absent where no instance will ever send: the schema baseline in `../migrations/pluginTables.ts`.
|
|
73
|
+
*/
|
|
74
|
+
ledger?: VerificationLedger;
|
|
69
75
|
}
|
|
70
76
|
|
|
71
77
|
/**
|
|
@@ -186,12 +192,24 @@ async function sendAndRecord(
|
|
|
186
192
|
ctx: { context?: unknown } | undefined,
|
|
187
193
|
): Promise<void> {
|
|
188
194
|
const requestContext = ctx?.context;
|
|
195
|
+
const type = message.template === "magicLink" ? "magic_link" : "otp";
|
|
196
|
+
let delivery: AuthEmailDelivery;
|
|
189
197
|
try {
|
|
190
|
-
|
|
198
|
+
delivery = await deps.sendEmail(message);
|
|
191
199
|
} catch (error) {
|
|
192
200
|
markMessageDelivery(requestContext, { delivery: "failed", reason: SEND_FAULT });
|
|
201
|
+
// The link exists whether or not its mail does, so the ledger counts it, with no job to join.
|
|
202
|
+
await deps.ledger?.issued(requestContext, { type, email: message.to, emailJobId: null });
|
|
193
203
|
throw error;
|
|
194
204
|
}
|
|
205
|
+
markMessageDelivery(requestContext, delivery);
|
|
206
|
+
// A withheld message has a job too — the suppressed row — and that row is what a reader joins a
|
|
207
|
+
// suppression on, so it is recorded exactly like a queued one.
|
|
208
|
+
await deps.ledger?.issued(requestContext, {
|
|
209
|
+
type,
|
|
210
|
+
email: message.to,
|
|
211
|
+
emailJobId: delivery.delivery === "failed" ? null : (delivery.jobId ?? null),
|
|
212
|
+
});
|
|
195
213
|
}
|
|
196
214
|
|
|
197
215
|
/** Is this value shaped like a Better Auth plugin — an object carrying a non-empty string `id`? */
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import { decodeCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
|
|
6
|
+
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { sql } from "kysely";
|
|
8
|
+
import type { AdminPage } from "../admin/users";
|
|
9
|
+
import type { AuthDatabase } from "../data/tables";
|
|
10
|
+
import { VerificationOutcome, type VerificationState, VerificationType } from "../data/verificationOutcome";
|
|
11
|
+
import type { VerificationTypeCounts } from "../http/responses";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Reading the verification ledger (#829): what `GET {auth}/admin/verifications` answers.
|
|
15
|
+
*
|
|
16
|
+
* Two reads over one window of issue times: the counts by type and state, and the rows themselves, paged. The
|
|
17
|
+
* state is computed at read time — an unused row becomes expired the moment its expiry passes, with nothing
|
|
18
|
+
* written — so both reads take the same `now`, and a row counted as pending is listed as pending.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** How far back a window reaches when the caller names no start. */
|
|
22
|
+
export const DEFAULT_WINDOW_DAYS = 30;
|
|
23
|
+
|
|
24
|
+
/** A window of issue times: `since` inclusive, `until` exclusive. */
|
|
25
|
+
export interface VerificationWindow {
|
|
26
|
+
since: Date;
|
|
27
|
+
until: Date;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The window a read covers. `until` defaults to now and `since` to 30 days before it; a window that ends where it
|
|
32
|
+
* starts, or before, is refused rather than answered with nothing, because an empty answer would read as "no
|
|
33
|
+
* sign-ins".
|
|
34
|
+
*/
|
|
35
|
+
export function resolveVerificationWindow(input: { since?: Date; until?: Date }, now: Date): VerificationWindow {
|
|
36
|
+
const until = input.until ?? now;
|
|
37
|
+
const since = input.since ?? new Date(until.getTime() - DEFAULT_WINDOW_DAYS * 86_400_000);
|
|
38
|
+
if (since.getTime() >= until.getTime()) {
|
|
39
|
+
throw new ValidationError({
|
|
40
|
+
message: "The window must start before it ends.",
|
|
41
|
+
detail: `since ${since.toISOString()} is not before until ${until.toISOString()}`,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return { since, until };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The counts by type and state over a window: one aggregate, grouped by type, and every type answered — a type
|
|
49
|
+
* nothing was issued for reads as zeros rather than going missing, so a reader never has to tell "none" from
|
|
50
|
+
* "not reported".
|
|
51
|
+
*/
|
|
52
|
+
export async function verificationCounts(
|
|
53
|
+
db: AuthDatabase,
|
|
54
|
+
window: VerificationWindow,
|
|
55
|
+
now: Date,
|
|
56
|
+
): Promise<VerificationTypeCounts[]> {
|
|
57
|
+
const at = SQLiteDate.encode(now);
|
|
58
|
+
const rows = await db
|
|
59
|
+
.selectFrom("pithyAuthVerificationOutcomes")
|
|
60
|
+
.select((eb) => [
|
|
61
|
+
"type",
|
|
62
|
+
eb.fn.countAll<number>().as("issued"),
|
|
63
|
+
sql<number>`sum(case when ${eb.ref("usedAt")} is not null then 1 else 0 end)`.as("used"),
|
|
64
|
+
sql<number>`sum(case when ${eb.ref("usedAt")} is null and ${eb.ref("expiresAt")} <= ${at} then 1 else 0 end)`.as(
|
|
65
|
+
"expired",
|
|
66
|
+
),
|
|
67
|
+
])
|
|
68
|
+
.where("issuedAt", ">=", SQLiteDate.encode(window.since))
|
|
69
|
+
.where("issuedAt", "<", SQLiteDate.encode(window.until))
|
|
70
|
+
.groupBy("type")
|
|
71
|
+
.execute();
|
|
72
|
+
return VerificationType.options.map((type) => {
|
|
73
|
+
const row = rows.find((candidate) => candidate.type === type);
|
|
74
|
+
const issued = Number(row?.issued ?? 0);
|
|
75
|
+
const used = Number(row?.used ?? 0);
|
|
76
|
+
const expired = Number(row?.expired ?? 0);
|
|
77
|
+
return { type, issued, used, expired, pending: issued - used - expired };
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** What the row listing filters on and where it resumes. */
|
|
82
|
+
export interface ListVerificationOutcomesOptions {
|
|
83
|
+
window: VerificationWindow;
|
|
84
|
+
/** Only this type. */
|
|
85
|
+
type?: VerificationType | undefined;
|
|
86
|
+
/** Only rows in this state at `now`. */
|
|
87
|
+
state?: VerificationState | undefined;
|
|
88
|
+
/** The moment `state` is judged at — the same `now` the counts took. */
|
|
89
|
+
now: Date;
|
|
90
|
+
cursor?: string | undefined;
|
|
91
|
+
limit?: number | undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The window's rows, newest issue first, paged by keyset on `(issuedAt, id)` — the index the migration built for
|
|
96
|
+
* exactly this. A malformed cursor is a first page, as everywhere in the kit.
|
|
97
|
+
*/
|
|
98
|
+
export async function listVerificationOutcomes(
|
|
99
|
+
db: AuthDatabase,
|
|
100
|
+
options: ListVerificationOutcomesOptions,
|
|
101
|
+
): Promise<AdminPage<VerificationOutcome>> {
|
|
102
|
+
const limit = pageLimit(options.limit);
|
|
103
|
+
const at = SQLiteDate.encode(options.now);
|
|
104
|
+
let query = db
|
|
105
|
+
.selectFrom("pithyAuthVerificationOutcomes")
|
|
106
|
+
.selectAll()
|
|
107
|
+
.where("issuedAt", ">=", SQLiteDate.encode(options.window.since))
|
|
108
|
+
.where("issuedAt", "<", SQLiteDate.encode(options.window.until))
|
|
109
|
+
.orderBy("issuedAt", "desc")
|
|
110
|
+
.orderBy("id", "desc")
|
|
111
|
+
.limit(limit + 1);
|
|
112
|
+
if (options.type) query = query.where("type", "=", options.type);
|
|
113
|
+
if (options.state === "used") query = query.where("usedAt", "is not", null);
|
|
114
|
+
if (options.state === "expired") query = query.where("usedAt", "is", null).where("expiresAt", "<=", at);
|
|
115
|
+
if (options.state === "pending") query = query.where("usedAt", "is", null).where("expiresAt", ">", at);
|
|
116
|
+
|
|
117
|
+
const cursor = decodeCursor(options.cursor);
|
|
118
|
+
const sort = cursor ? Number(cursor.sort) : Number.NaN;
|
|
119
|
+
const id = cursor ? Number(cursor.id) : Number.NaN;
|
|
120
|
+
// A cursor whose halves are not both numbers came from some other listing. It reads as a first page.
|
|
121
|
+
if (Number.isFinite(sort) && Number.isFinite(id)) {
|
|
122
|
+
query = query.where((eb) =>
|
|
123
|
+
eb.or([eb("issuedAt", "<", sort), eb.and([eb("issuedAt", "=", sort), eb("id", "<", id)])]),
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const rows = await query.execute();
|
|
128
|
+
return toPage(
|
|
129
|
+
rows.map((row) => VerificationOutcome.parse(row)),
|
|
130
|
+
limit,
|
|
131
|
+
(row) => ({ sort: row.issuedAt.getTime(), id: row.id }),
|
|
132
|
+
);
|
|
133
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import type { AuthDatabase } from "../data/tables";
|
|
6
|
+
import type { VerificationType } from "../data/verificationOutcome";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Writing the verification ledger (#829): a row when auth issues a sign-in link or code, a stamp when one is used.
|
|
10
|
+
*
|
|
11
|
+
* ## Four moments, one request each, and none of them knows everything
|
|
12
|
+
*
|
|
13
|
+
* Better Auth creates the verification row, then calls the kit's send callback, then — in a later request —
|
|
14
|
+
* consumes the row and creates a session. No single one of those holds the whole record:
|
|
15
|
+
*
|
|
16
|
+
* - **`verification.create.after`** has the row's id and expiry, and no idea what it is for: the same table
|
|
17
|
+
* holds OAuth state.
|
|
18
|
+
* - **The send callback** knows it is a sign-in link or code and, once the email seam answers, the job that
|
|
19
|
+
* carries it — and not the row's id, which Better Auth never hands it.
|
|
20
|
+
* - **`verification.delete.before`** sees the row about to be consumed, and not whether the consume wins.
|
|
21
|
+
* - **`session.create.after`** knows somebody signed in, and as whom, and not with what.
|
|
22
|
+
*
|
|
23
|
+
* So each moment leaves what it saw on the request, and the next one in the same request completes the record:
|
|
24
|
+
* the send pairs with the row created just before it, and the session pairs with the row consumed just before
|
|
25
|
+
* it. The request is the endpoint's own per-dispatch context object — the one `../audit/evidence.ts` keys on,
|
|
26
|
+
* which Better Auth hands to database hooks and send callbacks alike — held weakly, so nothing outlives it.
|
|
27
|
+
*
|
|
28
|
+
* ## Why the pairing is safe
|
|
29
|
+
*
|
|
30
|
+
* - **A row created and never sent is never recorded.** OAuth state, and a code Better Auth's own enumeration
|
|
31
|
+
* guard drops before the send, both stop at the first moment.
|
|
32
|
+
* - **A consume that loses, or one that ends in a refusal, is never stamped.** Only a session created in the
|
|
33
|
+
* same request stamps it, and Better Auth creates none unless the consume returned the row.
|
|
34
|
+
* - **A row consumed for any other reason matches nothing.** An OAuth callback deletes its state row and
|
|
35
|
+
* creates a session; the stamp looks for that id in the ledger and finds no row.
|
|
36
|
+
* - **A wrong code moves its row.** Better Auth consumes the code to check it, and on a mismatch creates a new
|
|
37
|
+
* row with the same value and expiry and one more attempt counted. Recognized by that expiry, the ledger row
|
|
38
|
+
* follows it, so the right code entered next stamps the row the mail was counted against.
|
|
39
|
+
*
|
|
40
|
+
* ## Never fatal
|
|
41
|
+
*
|
|
42
|
+
* A ledger write that fails is swallowed. The ledger reports on sign-in; it must never be the reason one fails,
|
|
43
|
+
* and every caller here is mid-sign-in.
|
|
44
|
+
*
|
|
45
|
+
* **Not through `delete.after`**, deliberately: every `delete.after` in this package goes through `claimedDelete`
|
|
46
|
+
* (`../audit/evidence.ts`), and claiming a verification removal would delete the row before the consume could
|
|
47
|
+
* read it. `delete.before` sees the same row and changes nothing.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/** What one request has seen so far. */
|
|
51
|
+
interface Pending {
|
|
52
|
+
/** The verification row created in this request, awaiting the send that says what it is for. */
|
|
53
|
+
created?: { id: string; issuedAt: Date; expiresAt: Date };
|
|
54
|
+
/** The live verification row about to be consumed in this request, awaiting the session that proves its use. */
|
|
55
|
+
consuming?: { id: string; expiresAt: Date };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The verification ledger's four writers. */
|
|
59
|
+
export interface VerificationLedger {
|
|
60
|
+
/** `verification.create.after`: remember the row, and move a wrong code's ledger row onto its re-issue. */
|
|
61
|
+
created(row: unknown, requestContext: unknown): Promise<void>;
|
|
62
|
+
/** `verification.delete.before`: remember the live row about to be consumed. */
|
|
63
|
+
consuming(row: unknown, requestContext: unknown): void;
|
|
64
|
+
/** The send callback, once the email seam has answered: record the row created in this request. */
|
|
65
|
+
issued(requestContext: unknown, input: IssuedInput): Promise<void>;
|
|
66
|
+
/** `session.create.after`: stamp the row consumed in this request as used, by this user. */
|
|
67
|
+
signedIn(requestContext: unknown, userId: unknown): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What the send callback knows. The address is read to find the account and is never stored. */
|
|
71
|
+
export interface IssuedInput {
|
|
72
|
+
/** What was issued. */
|
|
73
|
+
type: VerificationType;
|
|
74
|
+
/** Who it was sent to — looked up, never written. */
|
|
75
|
+
email: string;
|
|
76
|
+
/** The `pithy_email_jobs` row that carries it, or null when the seam queued nothing. */
|
|
77
|
+
emailJobId: string | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A date off a Better Auth row: a `Date` from the adapter, an ISO string or a number from anywhere else. */
|
|
81
|
+
export function dateOf(value: unknown): Date | null {
|
|
82
|
+
const date =
|
|
83
|
+
value instanceof Date ? value : typeof value === "string" || typeof value === "number" ? new Date(value) : null;
|
|
84
|
+
return date && Number.isFinite(date.getTime()) ? date : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The id and dates off a verification row, or null for anything not shaped like one. */
|
|
88
|
+
export function verificationRowOf(row: unknown): { id: string; createdAt: Date | null; expiresAt: Date } | null {
|
|
89
|
+
if (typeof row !== "object" || row === null) return null;
|
|
90
|
+
const { id, createdAt, expiresAt } = row as { id?: unknown; createdAt?: unknown; expiresAt?: unknown };
|
|
91
|
+
if (typeof id !== "string" || id === "") return null;
|
|
92
|
+
const expires = dateOf(expiresAt);
|
|
93
|
+
if (!expires) return null;
|
|
94
|
+
return { id, createdAt: dateOf(createdAt), expiresAt: expires };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Build the ledger's writers over one database. `now` is injectable for the tests that pin a clock. */
|
|
98
|
+
export function verificationLedger(db: AuthDatabase, now: () => Date = () => new Date()): VerificationLedger {
|
|
99
|
+
const pending = new WeakMap<object, Pending>();
|
|
100
|
+
const stateOf = (requestContext: unknown): Pending | null => {
|
|
101
|
+
if (typeof requestContext !== "object" || requestContext === null) return null;
|
|
102
|
+
let state = pending.get(requestContext);
|
|
103
|
+
if (!state) {
|
|
104
|
+
state = {};
|
|
105
|
+
pending.set(requestContext, state);
|
|
106
|
+
}
|
|
107
|
+
return state;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
async created(row, requestContext) {
|
|
112
|
+
const state = stateOf(requestContext);
|
|
113
|
+
const verification = verificationRowOf(row);
|
|
114
|
+
if (!state || !verification) return;
|
|
115
|
+
const consumed = state.consuming;
|
|
116
|
+
// A wrong code: consumed to be checked, and re-created with the same expiry. The ledger row follows it.
|
|
117
|
+
if (consumed && consumed.expiresAt.getTime() === verification.expiresAt.getTime()) {
|
|
118
|
+
state.consuming = undefined;
|
|
119
|
+
await swallow(() =>
|
|
120
|
+
db
|
|
121
|
+
.updateTable("pithyAuthVerificationOutcomes")
|
|
122
|
+
.set({ verificationId: verification.id })
|
|
123
|
+
.where("verificationId", "=", consumed.id)
|
|
124
|
+
.execute(),
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
state.created = {
|
|
128
|
+
id: verification.id,
|
|
129
|
+
issuedAt: verification.createdAt ?? now(),
|
|
130
|
+
expiresAt: verification.expiresAt,
|
|
131
|
+
};
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
consuming(row, requestContext) {
|
|
135
|
+
const state = stateOf(requestContext);
|
|
136
|
+
const verification = verificationRowOf(row);
|
|
137
|
+
if (!state || !verification) return;
|
|
138
|
+
// An expired row is being swept, not consumed: Better Auth's cleanup deletes those on any read.
|
|
139
|
+
if (verification.expiresAt.getTime() <= now().getTime()) return;
|
|
140
|
+
state.consuming = { id: verification.id, expiresAt: verification.expiresAt };
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
async issued(requestContext, input) {
|
|
144
|
+
const state = stateOf(requestContext);
|
|
145
|
+
const created = state?.created;
|
|
146
|
+
if (!state || !created) return;
|
|
147
|
+
state.created = undefined;
|
|
148
|
+
await swallow(async () => {
|
|
149
|
+
const user = await db
|
|
150
|
+
.selectFrom("pithyAuthUsers")
|
|
151
|
+
.select("id")
|
|
152
|
+
// Better Auth stores and finds emails lowercased; `/sign-in/magic-link` hands the address on as typed.
|
|
153
|
+
.where("email", "=", input.email.toLowerCase())
|
|
154
|
+
.executeTakeFirst();
|
|
155
|
+
await db
|
|
156
|
+
.insertInto("pithyAuthVerificationOutcomes")
|
|
157
|
+
.values({
|
|
158
|
+
verificationId: created.id,
|
|
159
|
+
type: input.type,
|
|
160
|
+
userId: user?.id ?? null,
|
|
161
|
+
emailJobId: input.emailJobId,
|
|
162
|
+
issuedAt: SQLiteDate.encode(created.issuedAt),
|
|
163
|
+
expiresAt: SQLiteDate.encode(created.expiresAt),
|
|
164
|
+
usedAt: null,
|
|
165
|
+
})
|
|
166
|
+
.execute();
|
|
167
|
+
});
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
async signedIn(requestContext, userId) {
|
|
171
|
+
const state = stateOf(requestContext);
|
|
172
|
+
const consumed = state?.consuming;
|
|
173
|
+
if (!state || !consumed || typeof userId !== "string" || userId === "") return;
|
|
174
|
+
state.consuming = undefined;
|
|
175
|
+
await swallow(() =>
|
|
176
|
+
db
|
|
177
|
+
.updateTable("pithyAuthVerificationOutcomes")
|
|
178
|
+
.set((eb) => ({
|
|
179
|
+
usedAt: SQLiteDate.encode(now()),
|
|
180
|
+
// A sign-up's row had no account to name at issue; the one its use just created is it.
|
|
181
|
+
userId: eb.fn.coalesce("userId", eb.val(userId)),
|
|
182
|
+
}))
|
|
183
|
+
.where("verificationId", "=", consumed.id)
|
|
184
|
+
.where("usedAt", "is", null)
|
|
185
|
+
.execute(),
|
|
186
|
+
);
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Run a ledger write and drop its failure: the ledger reports on sign-in and is never the reason one fails. */
|
|
192
|
+
async function swallow(write: () => Promise<unknown>): Promise<void> {
|
|
193
|
+
try {
|
|
194
|
+
await write();
|
|
195
|
+
} catch {
|
|
196
|
+
// Deliberately empty. See the file header: every caller is mid-sign-in.
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { ErasureHistoryReader, ErasureHistoryRow, ErasureRecords } from "@pithy-sh/core/src/capability/erasure";
|
|
5
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
6
|
+
import { AuthAuditActions } from "../audit/actions";
|
|
7
|
+
import { type AuthDatabase, authDatabase } from "../data/tables";
|
|
8
|
+
import { UserLifecycleEvent } from "../data/userLifecycle";
|
|
9
|
+
import { resolveDb } from "../http/resolve";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* **A user's erasure record, read back for the control plane's attestation (#823).**
|
|
13
|
+
*
|
|
14
|
+
* `pithy_auth_user_lifecycle` is the one `pithy_auth_*` table a purge leaves behind, and it names the account by id
|
|
15
|
+
* and nothing else. This reads the rows an erasure is made of — the deletion, any restore, each step, a failure, the
|
|
16
|
+
* end — and hands them to core through the {@link ErasureRecords} seam, so the control plane never imports auth.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The rows an erasure is made of. A suspension is not one. */
|
|
20
|
+
const ERASURE_ACTIONS = ["deleted", "restored", "purge_step", "purge_retained", "purge_failed", "purged"] as const;
|
|
21
|
+
|
|
22
|
+
/** The rows that are the purge itself, rather than the deletion it runs under. */
|
|
23
|
+
const PURGE_ACTIONS = ["purge_step", "purge_retained", "purge_failed", "purged"] as const;
|
|
24
|
+
|
|
25
|
+
/** The rows that end a deletion: its purge finishing, or the subject coming back. */
|
|
26
|
+
const CLOSING_ACTIONS = ["purged", "restored"] as const;
|
|
27
|
+
|
|
28
|
+
/** The reader, over one auth database. */
|
|
29
|
+
export function userErasureReader(db: AuthDatabase): ErasureHistoryReader {
|
|
30
|
+
return {
|
|
31
|
+
history: async (userIds) => {
|
|
32
|
+
if (userIds.length === 0) return [];
|
|
33
|
+
const rows = await db
|
|
34
|
+
.selectFrom("pithyAuthUserLifecycle")
|
|
35
|
+
.selectAll()
|
|
36
|
+
.where("userId", "in", [...userIds])
|
|
37
|
+
.where("action", "in", [...ERASURE_ACTIONS])
|
|
38
|
+
.orderBy("id", "asc")
|
|
39
|
+
.execute();
|
|
40
|
+
return rows.map((raw): ErasureHistoryRow => {
|
|
41
|
+
const row = UserLifecycleEvent.parse(raw);
|
|
42
|
+
return {
|
|
43
|
+
subjectId: row.userId,
|
|
44
|
+
action: row.action as ErasureHistoryRow["action"],
|
|
45
|
+
actorType: row.actorType,
|
|
46
|
+
reason: row.reason,
|
|
47
|
+
step: row.step,
|
|
48
|
+
mode: row.mode,
|
|
49
|
+
purgeAfter: row.purgeAfter,
|
|
50
|
+
at: row.createdAt,
|
|
51
|
+
};
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
subjectsIn: async (since, until) => {
|
|
55
|
+
const from = SQLiteDate.encode(since);
|
|
56
|
+
const to = SQLiteDate.encode(until);
|
|
57
|
+
const rows = await db
|
|
58
|
+
.selectFrom("pithyAuthUserLifecycle as row")
|
|
59
|
+
.select("row.userId")
|
|
60
|
+
.distinct()
|
|
61
|
+
.where((eb) =>
|
|
62
|
+
eb.or([
|
|
63
|
+
eb.and([
|
|
64
|
+
eb("row.action", "in", [...PURGE_ACTIONS]),
|
|
65
|
+
eb("row.createdAt", ">=", from),
|
|
66
|
+
eb("row.createdAt", "<=", to),
|
|
67
|
+
]),
|
|
68
|
+
eb.and([
|
|
69
|
+
eb("row.action", "=", "deleted"),
|
|
70
|
+
eb("row.purgeAfter", ">=", from),
|
|
71
|
+
eb("row.purgeAfter", "<=", to),
|
|
72
|
+
]),
|
|
73
|
+
// Outstanding in the window: due by its end, or recorded before the due instant was, and neither purged
|
|
74
|
+
// nor restored before it opened. A purge that came due earlier and has written nothing since is the one
|
|
75
|
+
// the period read exists to name.
|
|
76
|
+
eb.and([
|
|
77
|
+
eb("row.action", "=", "deleted"),
|
|
78
|
+
eb("row.createdAt", "<=", to),
|
|
79
|
+
eb.or([eb("row.purgeAfter", "<=", to), eb("row.purgeAfter", "is", null)]),
|
|
80
|
+
eb.not(
|
|
81
|
+
eb.exists(
|
|
82
|
+
eb
|
|
83
|
+
.selectFrom("pithyAuthUserLifecycle as closed")
|
|
84
|
+
.select("closed.id")
|
|
85
|
+
.whereRef("closed.userId", "=", "row.userId")
|
|
86
|
+
.whereRef("closed.id", ">", "row.id")
|
|
87
|
+
.where("closed.action", "in", [...CLOSING_ACTIONS])
|
|
88
|
+
.where("closed.createdAt", "<", from),
|
|
89
|
+
),
|
|
90
|
+
),
|
|
91
|
+
]),
|
|
92
|
+
]),
|
|
93
|
+
)
|
|
94
|
+
.orderBy("row.userId")
|
|
95
|
+
.execute();
|
|
96
|
+
return rows.map((row) => row.userId);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** What auth declares: the `user` subject, the actions its purge records, and the reader over its database. */
|
|
102
|
+
export function authErasureRecords(database: string): ErasureRecords {
|
|
103
|
+
return {
|
|
104
|
+
subject: "user",
|
|
105
|
+
resourceType: "user",
|
|
106
|
+
auditActions: {
|
|
107
|
+
deleted: [
|
|
108
|
+
AuthAuditActions.adminUserSoftDeleted,
|
|
109
|
+
AuthAuditActions.adminUserHardDeleted,
|
|
110
|
+
AuthAuditActions.userSelfDeleted,
|
|
111
|
+
],
|
|
112
|
+
step: AuthAuditActions.adminUserPurgeStep,
|
|
113
|
+
failed: AuthAuditActions.adminUserPurgeFailed,
|
|
114
|
+
purged: AuthAuditActions.adminUserPurged,
|
|
115
|
+
},
|
|
116
|
+
read: (env) => userErasureReader(authDatabase(resolveDb(env, database))),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import type { AuthDatabase } from "../data/tables";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* **Inactivity, as the retention policy's class ages count it.**
|
|
9
|
+
*
|
|
10
|
+
* An account is active when it opens a session: a sign-in, or a token refresh. Each one stamps `lastActiveAt` on the
|
|
11
|
+
* account, and a live session refreshed since counts too. An account untouched for longer than the strictest class
|
|
12
|
+
* age it holds is soft-deleted through the lifecycle — `../purge/run.ts` runs the pass — with the same notice mail,
|
|
13
|
+
* the same window and the same purge as any other deletion.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Stamp an account active now. Moves the clock forward only, so a late write never makes it look older. */
|
|
17
|
+
export async function recordActivity(db: AuthDatabase, userId: string, at: Date): Promise<void> {
|
|
18
|
+
const ms = SQLiteDate.encode(at);
|
|
19
|
+
await db
|
|
20
|
+
.updateTable("pithyAuthUsers")
|
|
21
|
+
.set({ lastActiveAt: ms })
|
|
22
|
+
.where("id", "=", userId)
|
|
23
|
+
.where((eb) => eb.or([eb("lastActiveAt", "is", null), eb("lastActiveAt", "<", ms)]))
|
|
24
|
+
.execute();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The accounts inactive since `cutoff`, oldest first, at most `limit`: not deleted, last active before it (or, never
|
|
29
|
+
* stamped, created before it), and holding no session refreshed since.
|
|
30
|
+
*/
|
|
31
|
+
export async function inactiveAccounts(db: AuthDatabase, cutoff: Date, limit: number): Promise<string[]> {
|
|
32
|
+
const ms = SQLiteDate.encode(cutoff);
|
|
33
|
+
const iso = cutoff.toISOString();
|
|
34
|
+
const rows = await db
|
|
35
|
+
.selectFrom("pithyAuthUsers")
|
|
36
|
+
.select("id")
|
|
37
|
+
.where("deletedAt", "is", null)
|
|
38
|
+
.where((eb) =>
|
|
39
|
+
eb.or([eb("lastActiveAt", "<", ms), eb.and([eb("lastActiveAt", "is", null), eb("createdAt", "<", iso)])]),
|
|
40
|
+
)
|
|
41
|
+
.where(({ not, exists, selectFrom }) =>
|
|
42
|
+
not(
|
|
43
|
+
exists(
|
|
44
|
+
selectFrom("pithyAuthSessions")
|
|
45
|
+
.select("pithyAuthSessions.id")
|
|
46
|
+
.whereRef("pithyAuthSessions.userId", "=", "pithyAuthUsers.id")
|
|
47
|
+
.where("pithyAuthSessions.updatedAt", ">=", iso),
|
|
48
|
+
),
|
|
49
|
+
),
|
|
50
|
+
)
|
|
51
|
+
.orderBy("lastActiveAt", "asc")
|
|
52
|
+
.orderBy("id", "asc")
|
|
53
|
+
.limit(limit)
|
|
54
|
+
.execute();
|
|
55
|
+
return rows.map((row) => row.id);
|
|
56
|
+
}
|