@pithy-sh/auth 0.10.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/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +58 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +59 -1
- package/dist/audit/emit.d.ts +36 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +48 -2
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +47 -8
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +56 -6
- 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 +26 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +10 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +8 -3
- 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 +319 -8
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -10
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +76 -10
- 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 +37 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +68 -6
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +322 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +202 -5
- package/dist/http/routes.d.ts +3 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +78 -5
- package/dist/http/schemas.d.ts +114 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +94 -1
- package/dist/http/views.d.ts +60 -3
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +143 -3
- 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 +87 -42
- 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/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 +37 -2
- package/dist/lifecycle/enforce.d.ts.map +1 -1
- package/dist/lifecycle/enforce.js +46 -5
- 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/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 +5 -2
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +6 -2
- package/dist/lifecycle/transitions.d.ts +179 -18
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +391 -70
- 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/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/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/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 +5 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +10 -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 +62 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +155 -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 +158 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +205 -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 +71 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +140 -0
- package/dist/test-utils/accountFootprint.d.ts +13 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +49 -0
- 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 +176 -12
- 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 +58 -0
- package/src/audit/emit.ts +66 -1
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +122 -18
- 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 +19 -4
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +465 -4
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +79 -10
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +74 -5
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +374 -3
- package/src/http/routes.ts +116 -5
- package/src/http/schemas.ts +195 -0
- package/src/http/views.ts +192 -3
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +58 -3
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +55 -5
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +10 -2
- package/src/lifecycle/transitions.ts +552 -93
- 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/0005_purge_once.ts +42 -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/pluginTables.ts +19 -1
- package/src/migrations/set.ts +9 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +218 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +348 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +202 -0
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +104 -0
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { composedCapabilities, composedCapability } from "@pithy-sh/core/src/capability/composition";
|
|
5
|
+
import { messageOf } from "@pithy-sh/core/src/error/pithyError";
|
|
6
|
+
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
7
|
+
import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
|
|
8
|
+
import { 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";
|
|
11
|
+
import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
|
|
12
|
+
import type { TerminalErrorConstructor, WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
|
|
13
|
+
import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
|
|
14
|
+
import { enqueueFromEnv } from "@pithy-sh/email/src/send/fromComposition";
|
|
15
|
+
import { type AuthCapability, isAuthCapability } from "../capability";
|
|
16
|
+
import { authDatabase } from "../data/tables";
|
|
17
|
+
import { resolveDb } from "../http/resolve";
|
|
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";
|
|
30
|
+
import { AUTH_PURGE_BINDING, AUTH_PURGE_KEY, AuthPurgeDueParams, AuthPurgeParams } from "./specs";
|
|
31
|
+
import { startPurgeInstance } from "./start";
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The purge's two Workflow bodies (#622) — run by classes **the adopter's own Worker** exports, beside the
|
|
35
|
+
* `createEntrypoint` it already exports, because a purge runs every composed capability's contribution and
|
|
36
|
+
* those exist nowhere else:
|
|
37
|
+
*
|
|
38
|
+
* // apps/api/src/index.ts
|
|
39
|
+
* import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
|
|
40
|
+
* import { NonRetryableError } from "cloudflare:workflows";
|
|
41
|
+
* import { runAuthPurge, runAuthPurgeDue } from "@pithy-sh/auth/src/purge/workflow";
|
|
42
|
+
*
|
|
43
|
+
* export class AuthPurgeWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
|
|
44
|
+
* override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
|
|
45
|
+
* return runAuthPurge(this.env, event, step, NonRetryableError);
|
|
46
|
+
* }
|
|
47
|
+
* }
|
|
48
|
+
* export class AuthPurgeDueWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
|
|
49
|
+
* override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
|
|
50
|
+
* return runAuthPurgeDue(this.env, event, step, NonRetryableError);
|
|
51
|
+
* }
|
|
52
|
+
* }
|
|
53
|
+
*
|
|
54
|
+
* plus a `workflows` entry binding `AUTH_PURGE` and `AUTH_PURGE_DUE` to them and the daily cron —
|
|
55
|
+
* `docs/account-lifecycle.md` has the stanza. **The class is the adopter's, the body is the kit's**, the split
|
|
56
|
+
* `@pithy-sh/payments`' usage pass has, for the same reason.
|
|
57
|
+
*
|
|
58
|
+
* Each body finds the composed auth capability the way a Workflow that sends mail finds email: the class is
|
|
59
|
+
* exported from the entry that calls `createEntrypoint`, so the composition has happened in this isolate. The
|
|
60
|
+
* steps, the hooks, the config and the audit recorder are on the capability; the mail is email's own enqueue.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
/** What a Workflow event hands a body. */
|
|
64
|
+
interface PurgeEvent {
|
|
65
|
+
readonly payload?: unknown;
|
|
66
|
+
readonly workflowName?: string;
|
|
67
|
+
readonly instanceId?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The lifecycle transitions' dependencies, for a run with no request: this env, and the composition's seams. */
|
|
71
|
+
function lifecycleFor(auth: AuthCapability, env: Record<string, unknown>, log: Logger): LifecycleDeps {
|
|
72
|
+
const d1 = resolveDb(env, auth.authConfig.database);
|
|
73
|
+
return {
|
|
74
|
+
db: authDatabase(d1),
|
|
75
|
+
d1,
|
|
76
|
+
emit: auth.auditFor(env),
|
|
77
|
+
config: auth.authConfig,
|
|
78
|
+
hooks: auth.lifecycleHooks,
|
|
79
|
+
enqueueEmail: (input) => enqueueFromEnv(env as unknown as EmailEnqueueEnv, input),
|
|
80
|
+
log,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** This run's logger, bound to the instance an operator reads it under. */
|
|
85
|
+
function runLog(env: Record<string, unknown>, event: PurgeEvent, name: string): Logger {
|
|
86
|
+
return bindWorkflowContext(createWorkerLogger({ name }), {
|
|
87
|
+
workflow: event.workflowName ?? name,
|
|
88
|
+
instance: event.instanceId ?? "unknown",
|
|
89
|
+
env: typeof env.ENVIRONMENT === "string" ? env.ENVIRONMENT : "unknown",
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Purge one account: every composed contribution, one step each, auth's last. See `./run.ts`. */
|
|
94
|
+
export async function runAuthPurge(
|
|
95
|
+
env: Record<string, unknown>,
|
|
96
|
+
event: PurgeEvent,
|
|
97
|
+
step: WorkflowStepLike,
|
|
98
|
+
terminalError: TerminalErrorConstructor,
|
|
99
|
+
): Promise<PurgeOutcome> {
|
|
100
|
+
// Parsed rather than trusted: an instance can be started by the daily pass, by a hard deletion, or by hand.
|
|
101
|
+
const params = AuthPurgeParams.parse(event.payload ?? {});
|
|
102
|
+
const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
|
|
103
|
+
const lifecycle = lifecycleFor(auth, env, runLog(env, event, "auth:purge"));
|
|
104
|
+
return purgeUser(
|
|
105
|
+
{ steps: auth.purgeSteps, env, ops: purgeOps(lifecycle, legalHolds(env)) },
|
|
106
|
+
step,
|
|
107
|
+
terminalError,
|
|
108
|
+
params,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
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
|
+
*/
|
|
116
|
+
export async function runAuthPurgeDue(
|
|
117
|
+
env: Record<string, unknown>,
|
|
118
|
+
event: PurgeEvent,
|
|
119
|
+
step: WorkflowStepLike,
|
|
120
|
+
terminalError: TerminalErrorConstructor,
|
|
121
|
+
): Promise<{ started: number; inactive: number }> {
|
|
122
|
+
const params = AuthPurgeDueParams.parse(event.payload ?? {});
|
|
123
|
+
const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
|
|
124
|
+
const log = runLog(env, event, "auth:purge-due");
|
|
125
|
+
const lifecycle = lifecycleFor(auth, env, log);
|
|
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
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
|
|
168
|
+
* deletion already started today is the same instance, not a second one. No `notify`: the deletion's own row
|
|
169
|
+
* carries it, and the purge reads it there.
|
|
170
|
+
*
|
|
171
|
+
* **It answers whether the purge is running**, and the pass counts that. A Worker that has not bound the purge,
|
|
172
|
+
* and a start that failed, each log the skip rather than throwing inside a cron nobody watches — tomorrow's pass
|
|
173
|
+
* starts it again — and answer `false`, so the pass does not report a purge it never started.
|
|
174
|
+
*/
|
|
175
|
+
export function purgeStarter(
|
|
176
|
+
env: Record<string, unknown>,
|
|
177
|
+
log: Logger,
|
|
178
|
+
now: () => Date = () => new Date(),
|
|
179
|
+
): PurgeDueRun["start"] {
|
|
180
|
+
return async (due) => {
|
|
181
|
+
const binding = workflowBindingFor(env, AUTH_PURGE_BINDING);
|
|
182
|
+
if (!binding) {
|
|
183
|
+
log.warn("workflow skipped", {
|
|
184
|
+
workflow: AUTH_PURGE_KEY,
|
|
185
|
+
binding: AUTH_PURGE_BINDING,
|
|
186
|
+
reason: "binding absent — the purge Workflow is not bound",
|
|
187
|
+
});
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
await startPurgeInstance(binding, { userId: due.userId, deletedAt: due.deletedAt, at: now() });
|
|
192
|
+
return true;
|
|
193
|
+
} catch (error) {
|
|
194
|
+
log.warn("workflow skipped", {
|
|
195
|
+
workflow: AUTH_PURGE_KEY,
|
|
196
|
+
binding: AUTH_PURGE_BINDING,
|
|
197
|
+
reason: messageOf(error),
|
|
198
|
+
});
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
}
|
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:
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One account's rows across every `pithy_auth_*` table that keys a row to a person — what a purge must erase
|
|
8
|
+
* and an export must read (#622). For the workers suites; the tables are the real ones, written by raw SQL in
|
|
9
|
+
* the shapes the kit's own writers produce, so a test reads back exactly what production would hold.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const AT = "2026-10-01T00:00:00.000Z";
|
|
13
|
+
const AT_MS = Date.parse(AT);
|
|
14
|
+
|
|
15
|
+
/** Every table a footprint writes to, with the column that names the person in it. */
|
|
16
|
+
export const FOOTPRINT_TABLES = [
|
|
17
|
+
["pithy_auth_users", "id"],
|
|
18
|
+
["pithy_auth_sessions", "user_id"],
|
|
19
|
+
["pithy_auth_accounts", "user_id"],
|
|
20
|
+
["pithy_auth_devices", "user_id"],
|
|
21
|
+
["pithy_auth_rotated_tokens", "user_id"],
|
|
22
|
+
["pithy_auth_verification_outcomes", "user_id"],
|
|
23
|
+
] as const;
|
|
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
|
+
*/
|
|
29
|
+
export async function seedAccountFootprint(
|
|
30
|
+
d1: D1Database,
|
|
31
|
+
userId: string,
|
|
32
|
+
email = `${userId}@test.com`,
|
|
33
|
+
): Promise<void> {
|
|
34
|
+
await d1.batch([
|
|
35
|
+
d1
|
|
36
|
+
.prepare(
|
|
37
|
+
"insert into pithy_auth_users (id, name, email, email_verified, locale, created_at, updated_at) values (?, 'Sam', ?, 1, null, ?, ?)",
|
|
38
|
+
)
|
|
39
|
+
.bind(userId, email, AT, AT),
|
|
40
|
+
d1
|
|
41
|
+
.prepare(
|
|
42
|
+
"insert into pithy_auth_sessions (id, expires_at, token, created_at, updated_at, ip_address, user_agent, user_id, device_id) values (?, ?, ?, ?, ?, '203.0.113.9', 'Pithy/1.0', ?, ?)",
|
|
43
|
+
)
|
|
44
|
+
.bind(`s-${userId}`, "2099-01-01T00:00:00.000Z", `token-${userId}`, AT, AT, userId, `d-${userId}`),
|
|
45
|
+
d1
|
|
46
|
+
.prepare(
|
|
47
|
+
"insert into pithy_auth_accounts (id, account_id, provider_id, user_id, access_token, refresh_token, created_at, updated_at) values (?, ?, 'google', ?, ?, ?, ?, ?)",
|
|
48
|
+
)
|
|
49
|
+
.bind(`a-${userId}`, `g-${userId}`, userId, `access-${userId}`, `refresh-${userId}`, AT, AT),
|
|
50
|
+
d1
|
|
51
|
+
.prepare(
|
|
52
|
+
"insert into pithy_auth_devices (id, user_id, platform, push_token, last_ip, last_seen_at, created_at) values (?, ?, 'ios', ?, '203.0.113.9', ?, ?)",
|
|
53
|
+
)
|
|
54
|
+
.bind(`d-${userId}`, userId, `push-${userId}`, AT_MS, AT_MS),
|
|
55
|
+
d1
|
|
56
|
+
.prepare("insert into pithy_auth_rotated_tokens (token, family_id, user_id, rotated_at) values (?, ?, ?, ?)")
|
|
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),
|
|
63
|
+
d1
|
|
64
|
+
.prepare(
|
|
65
|
+
"insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, '123456:0', ?, ?, ?)",
|
|
66
|
+
)
|
|
67
|
+
.bind(`otp-${userId}`, `sign-in-otp-${email}`, "2099-01-01T00:00:00.000Z", AT, AT),
|
|
68
|
+
d1
|
|
69
|
+
.prepare(
|
|
70
|
+
"insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, ?, ?, ?, ?)",
|
|
71
|
+
)
|
|
72
|
+
.bind(
|
|
73
|
+
`link-${userId}`,
|
|
74
|
+
`magic-link-${userId}`,
|
|
75
|
+
JSON.stringify({ email, name: "", attempt: 0 }),
|
|
76
|
+
"2099-01-01T00:00:00.000Z",
|
|
77
|
+
AT,
|
|
78
|
+
AT,
|
|
79
|
+
),
|
|
80
|
+
]);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** How many rows one account still holds in each footprint table, and in the pending codes for its address. */
|
|
84
|
+
export async function footprintCounts(d1: D1Database, userId: string, email = `${userId}@test.com`) {
|
|
85
|
+
const counts: Record<string, number> = {};
|
|
86
|
+
for (const [table, column] of FOOTPRINT_TABLES) {
|
|
87
|
+
const row = await d1
|
|
88
|
+
.prepare(`select count(*) as n from ${table} where ${column} = ?`)
|
|
89
|
+
.bind(userId)
|
|
90
|
+
.first<{ n: number }>();
|
|
91
|
+
counts[table] = row?.n ?? 0;
|
|
92
|
+
}
|
|
93
|
+
const codes = await d1
|
|
94
|
+
.prepare("select count(*) as n from pithy_auth_verifications where identifier = ? or instr(value, ?) > 0")
|
|
95
|
+
.bind(`sign-in-otp-${email}`, JSON.stringify(email))
|
|
96
|
+
.first<{ n: number }>();
|
|
97
|
+
counts.pithy_auth_verifications = codes?.n ?? 0;
|
|
98
|
+
const history = await d1
|
|
99
|
+
.prepare("select count(*) as n from pithy_auth_user_lifecycle where user_id = ?")
|
|
100
|
+
.bind(userId)
|
|
101
|
+
.first<{ n: number }>();
|
|
102
|
+
counts.pithy_auth_user_lifecycle = history?.n ?? 0;
|
|
103
|
+
return counts;
|
|
104
|
+
}
|
|
@@ -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) => ({
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { sha256Base64Url, timingSafeEqual } from "@pithy-sh/core/src/controlPlane/token/digest";
|
|
5
|
+
import { sqliteJson } from "@pithy-sh/core/src/data/codecs";
|
|
6
|
+
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { Verification } from "../data/betterAuth";
|
|
9
|
+
import type { AuthDatabase } from "../data/tables";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The one-time code that hands a redirect sign-in back to a native app.
|
|
13
|
+
*
|
|
14
|
+
* A social sign-in that ends on an app's deep link cannot carry the session the way a browser does: the
|
|
15
|
+
* cookie lands in the system browser, which the app never reads. So the callback answers the deep link with
|
|
16
|
+
* this code instead, and the app trades it once, over `POST {base}/handoff`, for the session token.
|
|
17
|
+
*
|
|
18
|
+
* **Sixty seconds.** The trade happens the moment the app is opened from the link, so a slow device and a
|
|
19
|
+
* cold start are the whole of what the window has to cover. Anything longer only lengthens the time a code
|
|
20
|
+
* read off a URL log, or caught by another app claiming the same scheme, is still worth something.
|
|
21
|
+
*
|
|
22
|
+
* **Only the code's SHA-256 is stored.** The code carries 256 random bits, so a lookup by its digest leaks
|
|
23
|
+
* nothing a timing comparison could, and a read of the table yields nothing anybody can redeem. The row
|
|
24
|
+
* names the session by id, never by token, so the table holds no credential at all.
|
|
25
|
+
*
|
|
26
|
+
* **The code is bound to the app that started the sign-in**, the way RFC 7636 binds an authorization code. The
|
|
27
|
+
* app makes a random verifier, sends its S256 challenge with the sign-in, and presents the verifier with the
|
|
28
|
+
* code. Another app that claims the same scheme and catches the link holds the code but not the verifier, so
|
|
29
|
+
* the code is worth nothing to it. A code is never issued without a challenge.
|
|
30
|
+
*
|
|
31
|
+
* The rows live in `pithy_auth_verifications`, under their own identifier prefix, as Better Auth's own
|
|
32
|
+
* one-time tokens do. The redemption is one `DELETE … RETURNING`, so one code yields one session however
|
|
33
|
+
* many requests present it at once, and a wrong verifier spends the code as surely as the right one. Each issue
|
|
34
|
+
* also deletes a bounded batch of lapsed codes, so codes nobody traded do not pile up.
|
|
35
|
+
*/
|
|
36
|
+
export const HANDOFF_TTL_SECONDS = 60;
|
|
37
|
+
|
|
38
|
+
/** The most lapsed codes one issue deletes. The next issue takes the rest. */
|
|
39
|
+
export const HANDOFF_SWEEP_LIMIT = 50;
|
|
40
|
+
|
|
41
|
+
/** The identifier prefix that keeps these rows apart from every other verification. */
|
|
42
|
+
const IDENTIFIER_PREFIX = "pithy-handoff:";
|
|
43
|
+
|
|
44
|
+
/** An S256 challenge: the base64url SHA-256 of a verifier, unpadded, which is always 43 characters. */
|
|
45
|
+
const CHALLENGE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
|
|
46
|
+
|
|
47
|
+
/** An RFC 7636 code verifier: 43 to 128 characters, each unreserved (`A-Z a-z 0-9 - . _ ~`). */
|
|
48
|
+
const VERIFIER_SHAPE = /^[A-Za-z0-9\-._~]{43,128}$/;
|
|
49
|
+
|
|
50
|
+
/** Whether a value has the shape RFC 7636 gives a code verifier. */
|
|
51
|
+
export function isHandoffVerifier(value: string): boolean {
|
|
52
|
+
return VERIFIER_SHAPE.test(value);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Whether a value has the shape of an S256 challenge. */
|
|
56
|
+
export function isHandoffChallenge(value: string): boolean {
|
|
57
|
+
return CHALLENGE_SHAPE.test(value);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The S256 challenge a verifier hashes to: `BASE64URL(SHA-256(verifier))`. */
|
|
61
|
+
export function handoffChallengeOf(verifier: string): Promise<string> {
|
|
62
|
+
return sha256Base64Url(new TextEncoder().encode(verifier));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** What a code's row holds in its `value`: the session it stands for and the challenge its verifier must meet. */
|
|
66
|
+
export const StoredHandoff = z
|
|
67
|
+
.object({
|
|
68
|
+
sessionId: z.string().describe("The id of the session the code stands for. Never its token."),
|
|
69
|
+
challenge: z
|
|
70
|
+
.string()
|
|
71
|
+
.regex(CHALLENGE_SHAPE)
|
|
72
|
+
.describe("The S256 challenge the app sent with the sign-in. The trade's verifier must hash to it."),
|
|
73
|
+
})
|
|
74
|
+
.describe("A handoff code's row value: the session and the challenge that binds the code to one app.");
|
|
75
|
+
export type StoredHandoff = z.output<typeof StoredHandoff>;
|
|
76
|
+
|
|
77
|
+
/** The `value` column as a handoff: JSON text in SQLite, validated both ways. */
|
|
78
|
+
const StoredHandoffValue = sqliteJson(StoredHandoff);
|
|
79
|
+
|
|
80
|
+
/** What issuing a code answers: the code itself, which is never stored, and when it lapses. */
|
|
81
|
+
export interface IssuedHandoff {
|
|
82
|
+
readonly code: string;
|
|
83
|
+
readonly expiresAt: Date;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* What a redemption answers. `unknown` covers a code already spent and one never issued alike. The reasons are
|
|
88
|
+
* for the audit trail; the caller answers every refusal the same way.
|
|
89
|
+
*/
|
|
90
|
+
export type HandoffRedemption =
|
|
91
|
+
| { readonly ok: true; readonly sessionId: string }
|
|
92
|
+
| { readonly ok: false; readonly reason: HandoffRefusal };
|
|
93
|
+
|
|
94
|
+
/** Why a code was refused. `malformed` is a verifier outside RFC 7636's shape, which no challenge was made from. */
|
|
95
|
+
export type HandoffRefusal = "expired" | "unknown" | "mismatch" | "malformed";
|
|
96
|
+
|
|
97
|
+
async function identifierOf(code: string): Promise<string> {
|
|
98
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(code));
|
|
99
|
+
const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
100
|
+
return `${IDENTIFIER_PREFIX}${hex}`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function randomCode(): string {
|
|
104
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
105
|
+
let binary = "";
|
|
106
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
107
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Delete up to {@link HANDOFF_SWEEP_LIMIT} codes that lapsed by `now`. */
|
|
111
|
+
async function sweepLapsed(db: AuthDatabase, now: Date): Promise<void> {
|
|
112
|
+
await db
|
|
113
|
+
.deleteFrom("pithyAuthVerifications")
|
|
114
|
+
.where("id", "in", (lapsed) =>
|
|
115
|
+
lapsed
|
|
116
|
+
.selectFrom("pithyAuthVerifications")
|
|
117
|
+
.select("id")
|
|
118
|
+
.where("identifier", "like", `${IDENTIFIER_PREFIX}%`)
|
|
119
|
+
.where("expiresAt", "<=", Verification.shape.expiresAt.encode(now))
|
|
120
|
+
.limit(HANDOFF_SWEEP_LIMIT),
|
|
121
|
+
)
|
|
122
|
+
.execute();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Issue a code for a session that already exists, bound to the S256 challenge the app sent. A challenge of any
|
|
127
|
+
* other shape throws: an unbound code is never written.
|
|
128
|
+
*/
|
|
129
|
+
export async function issueHandoff(
|
|
130
|
+
db: AuthDatabase,
|
|
131
|
+
input: { sessionId: string; challenge: string; now: Date },
|
|
132
|
+
): Promise<IssuedHandoff> {
|
|
133
|
+
if (!isHandoffChallenge(input.challenge)) {
|
|
134
|
+
throw new InternalError({ detail: "a handoff code was asked for without an S256 challenge to bind it to" });
|
|
135
|
+
}
|
|
136
|
+
await sweepLapsed(db, input.now);
|
|
137
|
+
const code = randomCode();
|
|
138
|
+
const expiresAt = new Date(input.now.getTime() + HANDOFF_TTL_SECONDS * 1000);
|
|
139
|
+
await db
|
|
140
|
+
.insertInto("pithyAuthVerifications")
|
|
141
|
+
.values(
|
|
142
|
+
Verification.encode({
|
|
143
|
+
id: crypto.randomUUID(),
|
|
144
|
+
identifier: await identifierOf(code),
|
|
145
|
+
value: z.string().parse(StoredHandoffValue.encode({ sessionId: input.sessionId, challenge: input.challenge })),
|
|
146
|
+
expiresAt,
|
|
147
|
+
createdAt: input.now,
|
|
148
|
+
updatedAt: input.now,
|
|
149
|
+
}),
|
|
150
|
+
)
|
|
151
|
+
.execute();
|
|
152
|
+
return { code, expiresAt };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Spend a code against the verifier the app holds. The row goes whatever the answer, so an expired code, or one
|
|
157
|
+
* presented with the wrong or a malformed verifier, is spent by that attempt and a second attempt reads it as unknown.
|
|
158
|
+
*/
|
|
159
|
+
export async function redeemHandoff(
|
|
160
|
+
db: AuthDatabase,
|
|
161
|
+
input: { code: string; verifier: string },
|
|
162
|
+
now: Date,
|
|
163
|
+
): Promise<HandoffRedemption> {
|
|
164
|
+
const row = await db
|
|
165
|
+
.deleteFrom("pithyAuthVerifications")
|
|
166
|
+
.where("identifier", "=", await identifierOf(input.code))
|
|
167
|
+
.returning(["value", "expiresAt"])
|
|
168
|
+
.executeTakeFirst();
|
|
169
|
+
if (!row) return { ok: false, reason: "unknown" };
|
|
170
|
+
const parsed = StoredHandoffValue.safeParse(row.value);
|
|
171
|
+
if (!parsed.success) return { ok: false, reason: "unknown" };
|
|
172
|
+
const stored = parsed.data;
|
|
173
|
+
const expiresAt = Verification.shape.expiresAt.parse(row.expiresAt);
|
|
174
|
+
if (expiresAt.getTime() <= now.getTime()) return { ok: false, reason: "expired" };
|
|
175
|
+
if (!isHandoffVerifier(input.verifier)) return { ok: false, reason: "malformed" };
|
|
176
|
+
if (!timingSafeEqual(await handoffChallengeOf(input.verifier), stored.challenge)) {
|
|
177
|
+
return { ok: false, reason: "mismatch" };
|
|
178
|
+
}
|
|
179
|
+
return { ok: true, sessionId: stored.sessionId };
|
|
180
|
+
}
|
package/src/version.generated.ts
CHANGED