@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,872 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { D1Database, D1PreparedStatement } from "@cloudflare/workers-types";
|
|
5
|
+
import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
|
|
6
|
+
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
7
|
+
import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
8
|
+
import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
9
|
+
import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
|
|
10
|
+
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
11
|
+
import type { EnqueueInput } from "@pithy-sh/email/src/send/enqueue";
|
|
12
|
+
import { type CompiledQuery, sql } from "kysely";
|
|
13
|
+
import { type AuthAuditAction, AuthAuditActions } from "../audit/actions";
|
|
14
|
+
import type { AuthConfig } from "../capability";
|
|
15
|
+
import type { AuthDatabase } from "../data/tables";
|
|
16
|
+
import type { UserLifecycleAction, UserLifecycleActorType } from "../data/userLifecycle";
|
|
17
|
+
import type { UserLifecycleHookEvent, UserLifecycleHooks, UserLifecycleListener } from "./hooks";
|
|
18
|
+
import { MAX_REASON } from "./reason";
|
|
19
|
+
import { accountStanding, LifecycleColumns } from "./state";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The account-lifecycle transitions — the one place an account's state is ever changed (#620).
|
|
23
|
+
*
|
|
24
|
+
* The admin routes (#621, #622), the self-service deletion, and the purge Workflow call these and write
|
|
25
|
+
* nothing themselves, so each transition happens the same way whoever asked for it:
|
|
26
|
+
*
|
|
27
|
+
* 1. **The columns move, conditionally, and the history row is written with them.** The `update` names the
|
|
28
|
+
* state it expects to find, so of two concurrent suspensions exactly one changes a row, and only that one
|
|
29
|
+
* goes on. A request that finds the account already where it asked to put it is `changed: false` and does
|
|
30
|
+
* nothing else — no row, no mail, no hook — which is what "once per transition" means.
|
|
31
|
+
* 2. **The row in `pithy_auth_user_lifecycle`** — the actor, the reason, the time — is the second statement of
|
|
32
|
+
* the same `d1.batch()`, which D1 runs as one transaction, and it is written only when the first moved the
|
|
33
|
+
* account. Two awaits would leave a gap: a failed insert after a committed update, and a retry that finds
|
|
34
|
+
* the account already moved, returns `changed: false`, and loses the row, the event, the mail and the hook.
|
|
35
|
+
* 3. **The audit event is emitted** — the trail answers who and from where; the row answers what happened.
|
|
36
|
+
* 4. **The mail is enqueued**, when the config sends it, in the account's own language.
|
|
37
|
+
* 5. **The hook fires.**
|
|
38
|
+
*
|
|
39
|
+
* Steps 3 to 5 report something that has already happened, so none of them can undo it: each swallows its own
|
|
40
|
+
* failure, and a throwing hook or an email binding that is not there is logged and the transition stands.
|
|
41
|
+
*
|
|
42
|
+
* **What these do not do is end sessions.** Enforcement does not need them to — a suspended account's session
|
|
43
|
+
* is refused at every door the moment the column is written (`./enforce.ts`) — and revoking them is a route's
|
|
44
|
+
* decision, made through Better Auth so `onSessionRevoked` hears about it.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/** Who made a transition. */
|
|
48
|
+
export interface LifecycleActor {
|
|
49
|
+
/** The kind of principal. */
|
|
50
|
+
readonly type: UserLifecycleActorType;
|
|
51
|
+
/** Its id — the connection's for a management client, the user's own for self-service — or null. */
|
|
52
|
+
readonly id: string | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Everything a transition needs, resolved by the caller from its own context. */
|
|
56
|
+
export interface LifecycleDeps {
|
|
57
|
+
/** The auth tables. */
|
|
58
|
+
readonly db: AuthDatabase;
|
|
59
|
+
/** The same database as a binding, for the hooks — see `UserLifecycleListener`. */
|
|
60
|
+
readonly d1: D1Database;
|
|
61
|
+
/** The audit seam. A no-op when the audit capability is absent. */
|
|
62
|
+
readonly emit: AuditEmit;
|
|
63
|
+
/** The resolved config: the purge window, and which mails are sent. */
|
|
64
|
+
readonly config: Pick<AuthConfig, "retention" | "lifecycleEmails">;
|
|
65
|
+
/** The adopter's hooks. */
|
|
66
|
+
readonly hooks: UserLifecycleHooks;
|
|
67
|
+
/** The email capability's enqueue, bound to this run's env. Absent, nothing is mailed. */
|
|
68
|
+
readonly enqueueEmail?: ((input: EnqueueInput) => Promise<unknown>) | undefined;
|
|
69
|
+
/** Where a swallowed failure is reported. Absent, it is swallowed silently. */
|
|
70
|
+
readonly log?: Logger | undefined;
|
|
71
|
+
/** The clock. Defaults to the system's. */
|
|
72
|
+
readonly now?: (() => Date) | undefined;
|
|
73
|
+
/**
|
|
74
|
+
* The request a transition was asked from, carried onto its audit event: the correlation every admin event
|
|
75
|
+
* carries, and metadata the caller adds — the management connection's id, for a control-plane call.
|
|
76
|
+
*/
|
|
77
|
+
readonly context?: LifecycleAuditContext | undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** What the caller's request adds to a transition's audit event. */
|
|
81
|
+
export interface LifecycleAuditContext {
|
|
82
|
+
/** The caller's address, from `cf-connecting-ip`. */
|
|
83
|
+
readonly ip?: string | undefined;
|
|
84
|
+
/** The caller's user agent. */
|
|
85
|
+
readonly userAgent?: string | undefined;
|
|
86
|
+
/** The request's id, from `cf-ray`. */
|
|
87
|
+
readonly requestId?: string | undefined;
|
|
88
|
+
/** Extra metadata, merged under the transition's own. */
|
|
89
|
+
readonly metadata?: Record<string, unknown> | undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** What a transition did. */
|
|
93
|
+
export interface LifecycleTransition {
|
|
94
|
+
/** Whether the account moved. `false` when it was already where the call asked to put it. */
|
|
95
|
+
readonly changed: boolean;
|
|
96
|
+
/** Whether a lifecycle mail was enqueued for the account. False when the config, the call or a missing email capability sent none. */
|
|
97
|
+
readonly mailed: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** What a suspension did, and the suspension it left in force. */
|
|
101
|
+
export interface SuspendTransition extends LifecycleTransition {
|
|
102
|
+
/**
|
|
103
|
+
* True when the account was already suspended and this call restated the reason and the end instead (#621).
|
|
104
|
+
* That is not a transition — `changed` is false and no hook fires — but it is written, audited and mailed.
|
|
105
|
+
*/
|
|
106
|
+
readonly updated: boolean;
|
|
107
|
+
/** When the suspension in force began. A restatement keeps the original start. */
|
|
108
|
+
readonly suspendedAt: Date;
|
|
109
|
+
/** When it ends by itself, or null for one that lasts until a reinstatement. */
|
|
110
|
+
readonly suspendedUntil: Date | null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A reason, trimmed and bounded, or null when none was given. */
|
|
114
|
+
function reasonOf(reason: string | null | undefined): string | null {
|
|
115
|
+
if (reason === null || reason === undefined) return null;
|
|
116
|
+
const trimmed = reason.trim();
|
|
117
|
+
if (trimmed === "") return null;
|
|
118
|
+
if (trimmed.length > MAX_REASON) {
|
|
119
|
+
throw new ValidationError({
|
|
120
|
+
message: `A reason is at most ${MAX_REASON} characters.`,
|
|
121
|
+
detail: `lifecycle reason of ${trimmed.length} characters`,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return trimmed;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The account a transition acts on: who to write to, and where it stands. */
|
|
128
|
+
interface Subject {
|
|
129
|
+
readonly email: string;
|
|
130
|
+
readonly name: string;
|
|
131
|
+
readonly locale: string | null;
|
|
132
|
+
readonly columns: LifecycleColumns;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function subjectOf(db: AuthDatabase, userId: string): Promise<Subject> {
|
|
136
|
+
const row = await db
|
|
137
|
+
.selectFrom("pithyAuthUsers")
|
|
138
|
+
.select(["email", "name", "locale", "suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
|
|
139
|
+
.where("id", "=", userId)
|
|
140
|
+
.executeTakeFirst();
|
|
141
|
+
if (!row) {
|
|
142
|
+
throw new NotFoundError({
|
|
143
|
+
message: "No such account.",
|
|
144
|
+
action: "If it was deleted and its purge has run, its data is gone and there is nothing to act on.",
|
|
145
|
+
detail: `lifecycle transition for user ${userId}, which has no row`,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return { email: row.email, name: row.name, locale: row.locale ?? null, columns: LifecycleColumns.parse(row) };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A date written for its reader, in their language — the shape every lifecycle mail carries its dates in. */
|
|
152
|
+
function readable(date: Date, locale: string | null): string {
|
|
153
|
+
const tag = (locale ? formattingLocaleOf(locale) : null) ?? "en";
|
|
154
|
+
return new Intl.DateTimeFormat(tag, { dateStyle: "long", timeZone: "UTC" }).format(date);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** One row of an account's history. */
|
|
158
|
+
interface HistoryRow {
|
|
159
|
+
readonly userId: string;
|
|
160
|
+
readonly action: UserLifecycleAction;
|
|
161
|
+
readonly actor: LifecycleActor;
|
|
162
|
+
readonly reason: string | null;
|
|
163
|
+
readonly at: Date;
|
|
164
|
+
readonly suspendedUntil?: Date | null;
|
|
165
|
+
readonly step?: string | null;
|
|
166
|
+
/** A hard deletion's choice for the purge's last mail; see `UserLifecycleEvent.notify`. */
|
|
167
|
+
readonly notify?: boolean | null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The history row's values, as the table stores them. */
|
|
171
|
+
function encoded(row: HistoryRow) {
|
|
172
|
+
return {
|
|
173
|
+
userId: row.userId,
|
|
174
|
+
action: row.action,
|
|
175
|
+
actorType: row.actor.type,
|
|
176
|
+
actorId: row.actor.id,
|
|
177
|
+
reason: row.reason,
|
|
178
|
+
suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
|
|
179
|
+
step: row.step ?? null,
|
|
180
|
+
notify: row.notify === undefined || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
|
|
181
|
+
createdAt: SQLiteDate.encode(row.at),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A history row with no column change to pair it with: a purge step, a finished purge. Not swallowed. */
|
|
186
|
+
async function record(deps: LifecycleDeps, row: HistoryRow): Promise<void> {
|
|
187
|
+
await deps.db.insertInto("pithyAuthUserLifecycle").values(encoded(row)).execute();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Bind a compiled statement to D1, so it can join a `batch`. */
|
|
191
|
+
function prepared(d1: D1Database, compiled: CompiledQuery): D1PreparedStatement {
|
|
192
|
+
return d1.prepare(compiled.sql).bind(...(compiled.parameters as unknown[]));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Move the columns and write the history row as one transaction, and say whether the account moved.
|
|
197
|
+
*
|
|
198
|
+
* The insert is guarded by `changes()`, which SQLite answers for the statement just before it — the update —
|
|
199
|
+
* so a conditional update that matched nothing writes no row. Not swallowed: until both are written, nothing
|
|
200
|
+
* after them runs.
|
|
201
|
+
*/
|
|
202
|
+
async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, row: HistoryRow): Promise<boolean> {
|
|
203
|
+
const v = encoded(row);
|
|
204
|
+
const insert = deps.db
|
|
205
|
+
.insertInto("pithyAuthUserLifecycle")
|
|
206
|
+
.columns(["userId", "action", "actorType", "actorId", "reason", "suspendedUntil", "step", "notify", "createdAt"])
|
|
207
|
+
.expression(
|
|
208
|
+
deps.db
|
|
209
|
+
.selectNoFrom([
|
|
210
|
+
sql.val(v.userId).as("userId"),
|
|
211
|
+
sql.val(v.action).as("action"),
|
|
212
|
+
sql.val(v.actorType).as("actorType"),
|
|
213
|
+
sql.val(v.actorId).as("actorId"),
|
|
214
|
+
sql.val(v.reason).as("reason"),
|
|
215
|
+
sql.val(v.suspendedUntil).as("suspendedUntil"),
|
|
216
|
+
sql.val(v.step).as("step"),
|
|
217
|
+
sql.val(v.notify).as("notify"),
|
|
218
|
+
sql.val(v.createdAt).as("createdAt"),
|
|
219
|
+
])
|
|
220
|
+
.where(sql<number>`changes()`, ">", 0),
|
|
221
|
+
)
|
|
222
|
+
.compile();
|
|
223
|
+
const [updated] = await deps.d1.batch([prepared(deps.d1, update.compile()), prepared(deps.d1, insert)]);
|
|
224
|
+
return (updated?.meta.changes ?? 0) > 0;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The audit event, swallowed on failure — an audit write never breaks what it records. */
|
|
228
|
+
async function audit(
|
|
229
|
+
deps: LifecycleDeps,
|
|
230
|
+
action: AuthAuditAction,
|
|
231
|
+
userId: string,
|
|
232
|
+
actor: LifecycleActor,
|
|
233
|
+
metadata: Record<string, unknown>,
|
|
234
|
+
): Promise<void> {
|
|
235
|
+
const context = deps.context;
|
|
236
|
+
const event: AuditEventInput = {
|
|
237
|
+
action,
|
|
238
|
+
outcome: "success",
|
|
239
|
+
actorType: actor.type,
|
|
240
|
+
actorId: actor.id,
|
|
241
|
+
resourceType: "user",
|
|
242
|
+
resourceId: userId,
|
|
243
|
+
...(context?.ip ? { ip: context.ip } : {}),
|
|
244
|
+
...(context?.userAgent ? { userAgent: context.userAgent } : {}),
|
|
245
|
+
...(context?.requestId ? { requestId: context.requestId } : {}),
|
|
246
|
+
metadata: { ...context?.metadata, ...metadata },
|
|
247
|
+
};
|
|
248
|
+
try {
|
|
249
|
+
await deps.emit(event);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
deps.log?.warn(`lifecycle audit ${action} failed; the transition stands`, { reason: messageOf(error) });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. Says whether it was enqueued. */
|
|
256
|
+
async function mail(
|
|
257
|
+
deps: LifecycleDeps,
|
|
258
|
+
enabled: boolean,
|
|
259
|
+
to: string,
|
|
260
|
+
locale: string | null,
|
|
261
|
+
template: "accountSuspended" | "accountReinstated" | "deletionScheduled" | "deletionComplete",
|
|
262
|
+
payload: Record<string, unknown>,
|
|
263
|
+
): Promise<boolean> {
|
|
264
|
+
if (!enabled || !deps.enqueueEmail) return false;
|
|
265
|
+
try {
|
|
266
|
+
await deps.enqueueEmail({ to, template, payload, ...(locale ? { locale } : {}) });
|
|
267
|
+
return true;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, {
|
|
270
|
+
reason: messageOf(error),
|
|
271
|
+
});
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Fire one hook. Swallowed and logged: the transition is already written, and a retry would fire nothing. */
|
|
277
|
+
async function fire(
|
|
278
|
+
deps: LifecycleDeps,
|
|
279
|
+
name: keyof UserLifecycleHooks,
|
|
280
|
+
hook: UserLifecycleListener | undefined,
|
|
281
|
+
event: UserLifecycleHookEvent,
|
|
282
|
+
): Promise<void> {
|
|
283
|
+
if (!hook) return;
|
|
284
|
+
try {
|
|
285
|
+
await hook(event, deps.d1);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
deps.log?.warn(`${name} threw; the transition stands`, { userId: event.userId, reason: messageOf(error) });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function messageOf(error: unknown): string {
|
|
292
|
+
return error instanceof Error ? error.message : String(error);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Without a name, a greeting says "Hi," rather than greeting an empty string. */
|
|
296
|
+
function named(name: string): { name?: string } {
|
|
297
|
+
return name.trim() ? { name } : {};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The conflict for a deleted account: deletion outranks a suspension, so restore it first. */
|
|
301
|
+
function deletedConflict(restoreRoute: string | undefined, then: string): ConflictError {
|
|
302
|
+
return new ConflictError({
|
|
303
|
+
message: restoreRoute
|
|
304
|
+
? `This account is deleted. Restore it with ${restoreRoute} first.`
|
|
305
|
+
: "This account is deleted. Restore it first.",
|
|
306
|
+
action: restoreRoute ? `Restore it with ${restoreRoute}. ${then}` : `Restore it first. ${then}`,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The conflict for a write that found the account moved under it by another request. Retrying is safe. */
|
|
311
|
+
function raced(userId: string): ConflictError {
|
|
312
|
+
return new ConflictError({
|
|
313
|
+
message: "The account changed while this request was being made. Send it again.",
|
|
314
|
+
detail: `lifecycle write for user ${userId} matched no row; another request moved the account first`,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch (#622).
|
|
320
|
+
*
|
|
321
|
+
* A restore and a purge's `due` check race for one account, and each has to see the window the other saw. A
|
|
322
|
+
* timestamp the restore took before its statement went out is stale by the time D1 runs it: the window can
|
|
323
|
+
* close in between, by itself or because a hard deletion brought it forward, and a purge whose `due` check ran
|
|
324
|
+
* in that gap goes on to erase an account the restore reported back. So on the system clock the guard is the
|
|
325
|
+
* database's own time, evaluated inside the statement, and D1 runs statements one at a time: whichever lands
|
|
326
|
+
* first, the other sees it. An injected clock is a test's, and is read afresh here, at the statement.
|
|
327
|
+
*/
|
|
328
|
+
function windowClock(deps: LifecycleDeps) {
|
|
329
|
+
return deps.now
|
|
330
|
+
? sql<number>`${deps.now().getTime()}`
|
|
331
|
+
: sql<number>`cast(round(unixepoch('subsec') * 1000) as integer)`;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** The conflict for an account whose purge window has closed: nothing can restore it now. */
|
|
335
|
+
function windowClosed(userId: string, closes: Date): ConflictError {
|
|
336
|
+
return new ConflictError({
|
|
337
|
+
message: `This account's purge window closed on ${closes.toISOString()}. It can no longer be restored.`,
|
|
338
|
+
action: "The purge is due and erases its data once it runs. There is nothing to restore.",
|
|
339
|
+
detail: `restore for user ${userId}, whose purge was due at ${closes.toISOString()}`,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Suspend an account, until `until` or until it is reinstated.
|
|
345
|
+
*
|
|
346
|
+
* A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
|
|
347
|
+
* conflict rather than a no-op, and names `restoreRoute` when the caller gives one. A suspension whose end has
|
|
348
|
+
* passed is not in force, and a new one replaces it.
|
|
349
|
+
*
|
|
350
|
+
* **An account already suspended has its terms restated (#621).** The reason and the end are replaced, a
|
|
351
|
+
* `suspended` row records the new reason — the newest one is what the person is shown — and the audit event
|
|
352
|
+
* and the mail say so. The start is kept, and no hook fires: the account was suspended and still is, so
|
|
353
|
+
* nothing transitioned. A fresh suspension that loses the race to another suspension finds the account
|
|
354
|
+
* suspended, so it retries once as a restatement rather than failing. A write that finds the account moved
|
|
355
|
+
* under it any other way, by a reinstatement or a deletion that landed first, is a conflict: what the caller
|
|
356
|
+
* asked for no longer describes the account.
|
|
357
|
+
*
|
|
358
|
+
* `notify: false` sends no mail, whatever the config says; the config can only turn mail off, never on.
|
|
359
|
+
*/
|
|
360
|
+
export async function suspendUser(
|
|
361
|
+
deps: LifecycleDeps,
|
|
362
|
+
input: {
|
|
363
|
+
userId: string;
|
|
364
|
+
actor: LifecycleActor;
|
|
365
|
+
reason: string | null;
|
|
366
|
+
until?: Date | null;
|
|
367
|
+
notify?: boolean;
|
|
368
|
+
restoreRoute?: string;
|
|
369
|
+
},
|
|
370
|
+
): Promise<SuspendTransition> {
|
|
371
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
372
|
+
const reason = reasonOf(input.reason);
|
|
373
|
+
const until = input.until ?? null;
|
|
374
|
+
if (until && until.getTime() <= at.getTime()) {
|
|
375
|
+
throw new ValidationError({ message: "A suspension must end in the future, or not at all." });
|
|
376
|
+
}
|
|
377
|
+
const subject = await subjectOf(deps.db, input.userId);
|
|
378
|
+
const standing = accountStanding(subject.columns, at);
|
|
379
|
+
if (standing.state === "deleted") {
|
|
380
|
+
throw deletedConflict(input.restoreRoute, "Then suspend it, if it should be suspended instead.");
|
|
381
|
+
}
|
|
382
|
+
const encodedUntil = until ? SQLiteDate.encode(until) : null;
|
|
383
|
+
/** The same suspension, still in force: pinned by its start, so a reinstate-then-suspend in between is a different suspension and this write matches nothing. */
|
|
384
|
+
const restatement = (startedAt: Date) =>
|
|
385
|
+
deps.db
|
|
386
|
+
.updateTable("pithyAuthUsers")
|
|
387
|
+
.set({ suspendedUntil: encodedUntil })
|
|
388
|
+
.where("id", "=", input.userId)
|
|
389
|
+
.where("deletedAt", "is", null)
|
|
390
|
+
.where("suspendedAt", "=", SQLiteDate.encode(startedAt))
|
|
391
|
+
.where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
|
|
392
|
+
const fresh = deps.db
|
|
393
|
+
.updateTable("pithyAuthUsers")
|
|
394
|
+
.set({ suspendedAt: SQLiteDate.encode(at), suspendedUntil: encodedUntil })
|
|
395
|
+
.where("id", "=", input.userId)
|
|
396
|
+
.where("deletedAt", "is", null)
|
|
397
|
+
.where((eb) =>
|
|
398
|
+
eb.or([
|
|
399
|
+
eb("suspendedAt", "is", null),
|
|
400
|
+
eb.and([eb("suspendedUntil", "is not", null), eb("suspendedUntil", "<=", SQLiteDate.encode(at))]),
|
|
401
|
+
]),
|
|
402
|
+
);
|
|
403
|
+
const row: HistoryRow = {
|
|
404
|
+
userId: input.userId,
|
|
405
|
+
action: "suspended",
|
|
406
|
+
actor: input.actor,
|
|
407
|
+
reason,
|
|
408
|
+
at,
|
|
409
|
+
suspendedUntil: until,
|
|
410
|
+
};
|
|
411
|
+
let updated = standing.state === "suspended";
|
|
412
|
+
let startedAt = updated && subject.columns.suspendedAt ? subject.columns.suspendedAt : at;
|
|
413
|
+
if (!(await move(deps, updated ? restatement(startedAt) : fresh, row))) {
|
|
414
|
+
// A fresh suspension that lost to another suspension landing first finds the account suspended, which
|
|
415
|
+
// is the case a restatement answers: retry once as one. Anything else — a deletion, or a restatement
|
|
416
|
+
// that lost to a reinstatement — means what the caller asked for no longer describes the account.
|
|
417
|
+
const now = updated ? null : await subjectOf(deps.db, input.userId);
|
|
418
|
+
const moved = now ? accountStanding(now.columns, at) : null;
|
|
419
|
+
if (!now?.columns.suspendedAt || moved?.state !== "suspended") throw raced(input.userId);
|
|
420
|
+
updated = true;
|
|
421
|
+
startedAt = now.columns.suspendedAt;
|
|
422
|
+
if (!(await move(deps, restatement(startedAt), row))) throw raced(input.userId);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
|
|
426
|
+
reason,
|
|
427
|
+
suspendedUntil: until?.toISOString() ?? null,
|
|
428
|
+
updated,
|
|
429
|
+
});
|
|
430
|
+
const mailed = await mail(
|
|
431
|
+
deps,
|
|
432
|
+
deps.config.lifecycleEmails.accountSuspended && input.notify !== false,
|
|
433
|
+
subject.email,
|
|
434
|
+
subject.locale,
|
|
435
|
+
"accountSuspended",
|
|
436
|
+
{
|
|
437
|
+
...named(subject.name),
|
|
438
|
+
...(reason ? { reason } : {}),
|
|
439
|
+
...(until ? { until: readable(until, subject.locale) } : {}),
|
|
440
|
+
},
|
|
441
|
+
);
|
|
442
|
+
if (!updated) {
|
|
443
|
+
await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
|
|
444
|
+
userId: input.userId,
|
|
445
|
+
actor: input.actor,
|
|
446
|
+
reason,
|
|
447
|
+
at,
|
|
448
|
+
suspendedUntil: until,
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
return { changed: !updated, updated, mailed, suspendedAt: startedAt, suspendedUntil: until };
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Lift a suspension. An account that is not suspended — including one whose suspension ran out — is a no-op.
|
|
456
|
+
*
|
|
457
|
+
* Where the account stands is read through `accountStanding`, never off the raw column, because a suspension
|
|
458
|
+
* past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
|
|
459
|
+
* for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
|
|
460
|
+
* sign in again" to somebody every sign-in still refuses. Restore it first.
|
|
461
|
+
*
|
|
462
|
+
* `notify: false` sends no mail, on the same rule as `suspendUser`.
|
|
463
|
+
*/
|
|
464
|
+
export async function reinstateUser(
|
|
465
|
+
deps: LifecycleDeps,
|
|
466
|
+
input: { userId: string; actor: LifecycleActor; reason: string | null; notify?: boolean; restoreRoute?: string },
|
|
467
|
+
): Promise<LifecycleTransition> {
|
|
468
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
469
|
+
const reason = reasonOf(input.reason);
|
|
470
|
+
const subject = await subjectOf(deps.db, input.userId);
|
|
471
|
+
const standing = accountStanding(subject.columns, at);
|
|
472
|
+
if (standing.state === "deleted") {
|
|
473
|
+
throw deletedConflict(
|
|
474
|
+
input.restoreRoute,
|
|
475
|
+
"Its suspension stays in place through a restore, and can be lifted after.",
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
if (standing.state !== "suspended") return { changed: false, mailed: false };
|
|
479
|
+
const update = deps.db
|
|
480
|
+
.updateTable("pithyAuthUsers")
|
|
481
|
+
.set({ suspendedAt: null, suspendedUntil: null })
|
|
482
|
+
.where("id", "=", input.userId)
|
|
483
|
+
.where("deletedAt", "is", null)
|
|
484
|
+
.where("suspendedAt", "is not", null)
|
|
485
|
+
.where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
|
|
486
|
+
const row: HistoryRow = { userId: input.userId, action: "reinstated", actor: input.actor, reason, at };
|
|
487
|
+
if (!(await move(deps, update, row))) return { changed: false, mailed: false };
|
|
488
|
+
|
|
489
|
+
await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
|
|
490
|
+
const mailed = await mail(
|
|
491
|
+
deps,
|
|
492
|
+
deps.config.lifecycleEmails.accountReinstated && input.notify !== false,
|
|
493
|
+
subject.email,
|
|
494
|
+
subject.locale,
|
|
495
|
+
"accountReinstated",
|
|
496
|
+
named(subject.name),
|
|
497
|
+
);
|
|
498
|
+
await fire(deps, "onUserReinstated", deps.hooks.onUserReinstated, {
|
|
499
|
+
userId: input.userId,
|
|
500
|
+
actor: input.actor,
|
|
501
|
+
reason,
|
|
502
|
+
at,
|
|
503
|
+
});
|
|
504
|
+
return { changed: true, mailed };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** How a deletion runs: shut now and purged once the window closes, or purged now. */
|
|
508
|
+
export type DeletionMode = "soft" | "hard";
|
|
509
|
+
|
|
510
|
+
/** What a deletion did, and the deletion it left in force. */
|
|
511
|
+
export interface DeleteTransition extends LifecycleTransition {
|
|
512
|
+
/**
|
|
513
|
+
* `deleted` when this call deleted an account in good standing; `brought_forward` when the account was
|
|
514
|
+
* already deleted and a hard deletion moved its purge to now; `unchanged` when it was already deleted and
|
|
515
|
+
* this call had nothing to move.
|
|
516
|
+
*/
|
|
517
|
+
readonly outcome: "deleted" | "brought_forward" | "unchanged";
|
|
518
|
+
/** When the account was deleted. A deletion brought forward keeps its original start. */
|
|
519
|
+
readonly deletedAt: Date;
|
|
520
|
+
/** When the purge may erase it — now, for a hard deletion. Restorable until then. */
|
|
521
|
+
readonly purgeAfter: Date;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Delete an account. Audited as the account's own deletion when its holder is the actor.
|
|
526
|
+
*
|
|
527
|
+
* **Soft, the default**: it is shut now, and its data is erased once `retention.purgeAfterDays` have passed.
|
|
528
|
+
* Restorable until then. The deletion-scheduled mail carries the purge date and, when the config names one,
|
|
529
|
+
* the restore path. A deleted account deleted softly again is no transition.
|
|
530
|
+
*
|
|
531
|
+
* **Hard** (#622): `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
|
|
532
|
+
* caller starts the purge. No deletion-scheduled mail, because nothing is scheduled; the purge sends the
|
|
533
|
+
* deletion-complete one. An account already deleted softly has its purge brought forward to now, which is
|
|
534
|
+
* written and audited but fires no hook: the account was deleted and still is. One already due is unchanged.
|
|
535
|
+
*
|
|
536
|
+
* A suspension the account was under is left in place, so restoring the account does not lift it.
|
|
537
|
+
* `notify: false` sends no mail, whatever the config says.
|
|
538
|
+
*/
|
|
539
|
+
export async function deleteUser(
|
|
540
|
+
deps: LifecycleDeps,
|
|
541
|
+
input: { userId: string; actor: LifecycleActor; reason: string | null; mode?: DeletionMode; notify?: boolean },
|
|
542
|
+
): Promise<DeleteTransition> {
|
|
543
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
544
|
+
const reason = reasonOf(input.reason);
|
|
545
|
+
const hard = input.mode === "hard";
|
|
546
|
+
const purgeAfter = hard ? at : new Date(at.getTime() + deps.config.retention.purgeAfterDays * 86_400_000);
|
|
547
|
+
const subject = await subjectOf(deps.db, input.userId);
|
|
548
|
+
// A hard deletion's `notify` is the purge's to read, so it is written on the row: the purge that sends the last
|
|
549
|
+
// mail may be one the daily pass started, with no request to carry it (#622).
|
|
550
|
+
const row: HistoryRow = {
|
|
551
|
+
userId: input.userId,
|
|
552
|
+
action: "deleted",
|
|
553
|
+
actor: input.actor,
|
|
554
|
+
reason,
|
|
555
|
+
at,
|
|
556
|
+
...(hard && input.notify !== undefined ? { notify: input.notify } : {}),
|
|
557
|
+
};
|
|
558
|
+
const existing = subject.columns.deletedAt;
|
|
559
|
+
if (existing) {
|
|
560
|
+
const due = subject.columns.purgeAfter ?? existing;
|
|
561
|
+
const unchanged = {
|
|
562
|
+
changed: false,
|
|
563
|
+
mailed: false,
|
|
564
|
+
outcome: "unchanged",
|
|
565
|
+
deletedAt: existing,
|
|
566
|
+
purgeAfter: due,
|
|
567
|
+
} as const;
|
|
568
|
+
if (!hard || due.getTime() <= at.getTime()) return unchanged;
|
|
569
|
+
// Brought forward: the same deletion, with its window closed now. Pinned by its start, so a restore and a
|
|
570
|
+
// fresh deletion in between is a different deletion and this write matches nothing.
|
|
571
|
+
const forward = deps.db
|
|
572
|
+
.updateTable("pithyAuthUsers")
|
|
573
|
+
.set({ purgeAfter: SQLiteDate.encode(at) })
|
|
574
|
+
.where("id", "=", input.userId)
|
|
575
|
+
.where("deletedAt", "=", SQLiteDate.encode(existing))
|
|
576
|
+
.where("purgeAfter", ">", SQLiteDate.encode(at));
|
|
577
|
+
if (!(await move(deps, forward, row))) return unchanged;
|
|
578
|
+
await audit(deps, AuthAuditActions.adminUserHardDeleted, input.userId, input.actor, {
|
|
579
|
+
reason,
|
|
580
|
+
purgeAfter: at.toISOString(),
|
|
581
|
+
broughtForward: true,
|
|
582
|
+
});
|
|
583
|
+
return { changed: false, mailed: false, outcome: "brought_forward", deletedAt: existing, purgeAfter: at };
|
|
584
|
+
}
|
|
585
|
+
const update = deps.db
|
|
586
|
+
.updateTable("pithyAuthUsers")
|
|
587
|
+
.set({ deletedAt: SQLiteDate.encode(at), purgeAfter: SQLiteDate.encode(purgeAfter) })
|
|
588
|
+
.where("id", "=", input.userId)
|
|
589
|
+
.where("deletedAt", "is", null);
|
|
590
|
+
if (!(await move(deps, update, row))) {
|
|
591
|
+
// Another deletion landed first. The account is where this call asked to put it, so it is no transition;
|
|
592
|
+
// anything else moved it is a conflict, and a retry reads it afresh.
|
|
593
|
+
const now = await subjectOf(deps.db, input.userId);
|
|
594
|
+
if (!now.columns.deletedAt) throw raced(input.userId);
|
|
595
|
+
const due = now.columns.purgeAfter ?? now.columns.deletedAt;
|
|
596
|
+
return { changed: false, mailed: false, outcome: "unchanged", deletedAt: now.columns.deletedAt, purgeAfter: due };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const self = input.actor.type === "user" && input.actor.id === input.userId;
|
|
600
|
+
const action = hard
|
|
601
|
+
? AuthAuditActions.adminUserHardDeleted
|
|
602
|
+
: self
|
|
603
|
+
? AuthAuditActions.userSelfDeleted
|
|
604
|
+
: AuthAuditActions.adminUserSoftDeleted;
|
|
605
|
+
await audit(deps, action, input.userId, input.actor, { reason, purgeAfter: purgeAfter.toISOString() });
|
|
606
|
+
const restoreUrl = deps.config.retention.restoreUrl;
|
|
607
|
+
const mailed = hard
|
|
608
|
+
? false
|
|
609
|
+
: await mail(
|
|
610
|
+
deps,
|
|
611
|
+
deps.config.lifecycleEmails.deletionScheduled && input.notify !== false,
|
|
612
|
+
subject.email,
|
|
613
|
+
subject.locale,
|
|
614
|
+
"deletionScheduled",
|
|
615
|
+
{
|
|
616
|
+
...named(subject.name),
|
|
617
|
+
purgeOn: readable(purgeAfter, subject.locale),
|
|
618
|
+
...(restoreUrl ? { restoreUrl } : {}),
|
|
619
|
+
},
|
|
620
|
+
);
|
|
621
|
+
await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
|
|
622
|
+
userId: input.userId,
|
|
623
|
+
actor: input.actor,
|
|
624
|
+
reason,
|
|
625
|
+
at,
|
|
626
|
+
purgeAfter,
|
|
627
|
+
});
|
|
628
|
+
return { changed: true, mailed, outcome: "deleted", deletedAt: at, purgeAfter };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** What a restoration did, and where it left the account. */
|
|
632
|
+
export interface RestoreTransition extends LifecycleTransition {
|
|
633
|
+
/** Where the account stands now: `active`, or `suspended` when a suspension it was under is still in force. */
|
|
634
|
+
readonly state: "active" | "suspended";
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Restore a deleted account inside its purge window.
|
|
639
|
+
*
|
|
640
|
+
* **Only inside it.** Once `purgeAfter` has passed the purge is due, may already be running, and erases each
|
|
641
|
+
* capability's rows in turn, so restoring then would hand back an account with some of its data gone. That
|
|
642
|
+
* is a conflict naming the date the window closed. After the purge there is no account at all, and that is a
|
|
643
|
+
* 404 whose action says the data is gone — read off the history row the purge leaves behind, so it is told
|
|
644
|
+
* apart from an id that never existed.
|
|
645
|
+
*
|
|
646
|
+
* An account that is not deleted is no transition. A suspension it was under is still in force after.
|
|
647
|
+
*/
|
|
648
|
+
export async function restoreUser(
|
|
649
|
+
deps: LifecycleDeps,
|
|
650
|
+
input: { userId: string; actor: LifecycleActor; reason: string | null },
|
|
651
|
+
): Promise<RestoreTransition> {
|
|
652
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
653
|
+
const reason = reasonOf(input.reason);
|
|
654
|
+
const subject = await subjectOf(deps.db, input.userId).catch(async (error: unknown) => {
|
|
655
|
+
throw (await purgedRefusal(deps.db, input.userId)) ?? error;
|
|
656
|
+
});
|
|
657
|
+
const suspended = (columns: LifecycleColumns) =>
|
|
658
|
+
accountStanding({ ...columns, deletedAt: null, purgeAfter: null }, at).state === "suspended";
|
|
659
|
+
const state = suspended(subject.columns) ? "suspended" : "active";
|
|
660
|
+
if (!subject.columns.deletedAt) return { changed: false, mailed: false, state };
|
|
661
|
+
// Early, and only ever early: `at` was read before the account was, so a window it finds closed is closed. One
|
|
662
|
+
// it finds open may not be by the time the update runs, which is why the update guards on its own clock.
|
|
663
|
+
const closes = subject.columns.purgeAfter;
|
|
664
|
+
if (closes && closes.getTime() <= at.getTime()) throw windowClosed(input.userId, closes);
|
|
665
|
+
const update = deps.db
|
|
666
|
+
.updateTable("pithyAuthUsers")
|
|
667
|
+
.set({ deletedAt: null, purgeAfter: null })
|
|
668
|
+
.where("id", "=", input.userId)
|
|
669
|
+
.where("deletedAt", "is not", null)
|
|
670
|
+
.where("purgeAfter", ">", windowClock(deps));
|
|
671
|
+
const row: HistoryRow = { userId: input.userId, action: "restored", actor: input.actor, reason, at };
|
|
672
|
+
if (!(await move(deps, update, row))) {
|
|
673
|
+
// Another restoration landed first: no transition. A window that closed while this one was in flight — by
|
|
674
|
+
// itself, or brought forward by a hard deletion — is the conflict above. Anything else a retry reads afresh.
|
|
675
|
+
const now = await subjectOf(deps.db, input.userId).catch(async (error: unknown) => {
|
|
676
|
+
throw (await purgedRefusal(deps.db, input.userId)) ?? error;
|
|
677
|
+
});
|
|
678
|
+
if (!now.columns.deletedAt) {
|
|
679
|
+
return { changed: false, mailed: false, state: suspended(now.columns) ? "suspended" : "active" };
|
|
680
|
+
}
|
|
681
|
+
// Read afresh: a window still open now means something else moved the account — a restore and a new
|
|
682
|
+
// deletion both landed in between — and that is the retry's to read.
|
|
683
|
+
const closed = now.columns.purgeAfter;
|
|
684
|
+
if (closed && closed.getTime() <= (deps.now ?? (() => new Date()))().getTime()) {
|
|
685
|
+
throw windowClosed(input.userId, closed);
|
|
686
|
+
}
|
|
687
|
+
throw raced(input.userId);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
|
|
691
|
+
return { changed: true, mailed: false, state };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* The refusal for an account the purge has erased, or `null` when none was. A 404, because there is no
|
|
696
|
+
* account, with the date in the action so an operator answering a restore request knows it is final.
|
|
697
|
+
*/
|
|
698
|
+
async function purgedRefusal(db: AuthDatabase, userId: string): Promise<NotFoundError | null> {
|
|
699
|
+
const purged = await db
|
|
700
|
+
.selectFrom("pithyAuthUserLifecycle")
|
|
701
|
+
.select("createdAt")
|
|
702
|
+
.where("userId", "=", userId)
|
|
703
|
+
.where("action", "=", "purged")
|
|
704
|
+
.orderBy("id", "desc")
|
|
705
|
+
.executeTakeFirst();
|
|
706
|
+
if (!purged) return null;
|
|
707
|
+
const on = SQLiteDate.parse(purged.createdAt).toISOString();
|
|
708
|
+
return new NotFoundError({
|
|
709
|
+
message: "No such account.",
|
|
710
|
+
action: `This account was purged on ${on}. Its data is gone, and there is nothing to restore or export.`,
|
|
711
|
+
detail: `user ${userId} was purged at ${on}`,
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* The account's row, or the refusal for one that is not there — the 404 that says the data is gone when the
|
|
717
|
+
* purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
|
|
718
|
+
* export.
|
|
719
|
+
*/
|
|
720
|
+
export async function requirePresent(db: AuthDatabase, userId: string): Promise<void> {
|
|
721
|
+
const row = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", userId).executeTakeFirst();
|
|
722
|
+
if (row) return;
|
|
723
|
+
throw (
|
|
724
|
+
(await purgedRefusal(db, userId)) ??
|
|
725
|
+
new NotFoundError({ message: "No such user.", detail: `no pithy_auth_users row for ${userId}` })
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** The purge's own actor: a scheduled job, with nobody calling. */
|
|
730
|
+
const PURGE: LifecycleActor = { type: "system", id: null };
|
|
731
|
+
|
|
732
|
+
/** Who the purge's last mail goes to, captured before any step erases the address. */
|
|
733
|
+
export interface PurgeRecipient {
|
|
734
|
+
readonly email: string;
|
|
735
|
+
readonly name: string | null;
|
|
736
|
+
readonly locale: string | null;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Whether one account is due for its purge, who its last mail goes to, and whether it goes (#622).
|
|
741
|
+
*
|
|
742
|
+
* `due` only for an account that is deleted and whose `purgeAfter` has passed — the cron and a hard deletion
|
|
743
|
+
* both start a purge, and this is the one check either passes through, so an account restored in between is
|
|
744
|
+
* `not_due` and nothing is erased. `gone` when there is no row: the purge already erased it, or the id never
|
|
745
|
+
* existed, and either way there is nothing to do. The recipient is read here, before the first step, because
|
|
746
|
+
* the last step erases it.
|
|
747
|
+
*
|
|
748
|
+
* `notify` is what the deletion in force asked of the last mail — its newest `deleted` row's — so a hard
|
|
749
|
+
* deletion's `notify: false` holds for a purge the daily pass started, which was handed no such parameter.
|
|
750
|
+
*/
|
|
751
|
+
export async function purgeSubject(
|
|
752
|
+
deps: LifecycleDeps,
|
|
753
|
+
userId: string,
|
|
754
|
+
): Promise<
|
|
755
|
+
{ state: "due"; recipient: PurgeRecipient; notify: boolean | null } | { state: "not_due" } | { state: "gone" }
|
|
756
|
+
> {
|
|
757
|
+
// The instant is the database's, read in the same statement as the row — the clock `restoreUser` guards on, so
|
|
758
|
+
// a restore and this check agree on whether the window has closed, whichever runs first (#622).
|
|
759
|
+
const row = await deps.db
|
|
760
|
+
.selectFrom("pithyAuthUsers")
|
|
761
|
+
.select(["email", "name", "locale", "suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
|
|
762
|
+
.select(windowClock(deps).as("checkedAt"))
|
|
763
|
+
.where("id", "=", userId)
|
|
764
|
+
.executeTakeFirst();
|
|
765
|
+
if (!row) return { state: "gone" };
|
|
766
|
+
const columns = LifecycleColumns.parse(row);
|
|
767
|
+
if (!columns.deletedAt || !columns.purgeAfter || columns.purgeAfter.getTime() > Number(row.checkedAt)) {
|
|
768
|
+
return { state: "not_due" };
|
|
769
|
+
}
|
|
770
|
+
const deletion = await deps.db
|
|
771
|
+
.selectFrom("pithyAuthUserLifecycle")
|
|
772
|
+
.select("notify")
|
|
773
|
+
.where("userId", "=", userId)
|
|
774
|
+
.where("action", "=", "deleted")
|
|
775
|
+
.orderBy("id", "desc")
|
|
776
|
+
.limit(1)
|
|
777
|
+
.executeTakeFirst();
|
|
778
|
+
const saved = deletion?.notify;
|
|
779
|
+
const notify = saved === undefined || saved === null ? null : SQLiteBoolean.decode(saved);
|
|
780
|
+
return { state: "due", recipient: { email: row.email, name: row.name, locale: row.locale ?? null }, notify };
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/** One account whose purge is due: which, and the deletion it is due under — ms-epoch, so a Workflow journal holds it. */
|
|
784
|
+
export interface DuePurge {
|
|
785
|
+
readonly userId: string;
|
|
786
|
+
readonly deletedAt: number;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
|
|
791
|
+
* What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
|
|
792
|
+
* that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
|
|
793
|
+
*/
|
|
794
|
+
export async function duePurges(deps: LifecycleDeps, limit: number): Promise<DuePurge[]> {
|
|
795
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
796
|
+
const rows = await deps.db
|
|
797
|
+
.selectFrom("pithyAuthUsers")
|
|
798
|
+
.select(["id", "deletedAt"])
|
|
799
|
+
.where("deletedAt", "is not", null)
|
|
800
|
+
.where("purgeAfter", "is not", null)
|
|
801
|
+
.where("purgeAfter", "<=", SQLiteDate.encode(at))
|
|
802
|
+
.orderBy("purgeAfter", "asc")
|
|
803
|
+
.orderBy("id", "asc")
|
|
804
|
+
.limit(limit)
|
|
805
|
+
.execute();
|
|
806
|
+
return rows.map((row) => ({ userId: row.id, deletedAt: Number(row.deletedAt) }));
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
|
|
811
|
+
* the row's reason, so the history says what the step erased and not only that it ran.
|
|
812
|
+
*/
|
|
813
|
+
export async function recordPurgeStep(
|
|
814
|
+
deps: LifecycleDeps,
|
|
815
|
+
input: { userId: string; step: string; summary?: string | null },
|
|
816
|
+
): Promise<void> {
|
|
817
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
818
|
+
await record(deps, {
|
|
819
|
+
userId: input.userId,
|
|
820
|
+
action: "purge_step",
|
|
821
|
+
actor: PURGE,
|
|
822
|
+
reason: input.summary?.trim() ? input.summary.trim().slice(0, MAX_REASON) : null,
|
|
823
|
+
at,
|
|
824
|
+
step: input.step,
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
|
|
830
|
+
* other capability's rows are gone and before auth's own, which holds the address, so the last mail is
|
|
831
|
+
* enqueued while there is still an account to have sent it to. The address is handed in, captured before the
|
|
832
|
+
* first step. `notify: false` sends nothing, whatever the config says.
|
|
833
|
+
*/
|
|
834
|
+
export async function mailPurgeComplete(
|
|
835
|
+
deps: LifecycleDeps,
|
|
836
|
+
input: { recipient: PurgeRecipient; notify?: boolean },
|
|
837
|
+
): Promise<LifecycleTransition> {
|
|
838
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
839
|
+
const { email, name, locale } = input.recipient;
|
|
840
|
+
const mailed = await mail(
|
|
841
|
+
deps,
|
|
842
|
+
deps.config.lifecycleEmails.deletionComplete && input.notify !== false,
|
|
843
|
+
email,
|
|
844
|
+
locale,
|
|
845
|
+
"deletionComplete",
|
|
846
|
+
{ ...named(name ?? ""), purgedOn: readable(at, locale) },
|
|
847
|
+
);
|
|
848
|
+
return { changed: false, mailed };
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Finish a purge: the record, the audit event, the hook. The last thing that happens to the account.
|
|
853
|
+
*
|
|
854
|
+
* By the time a purge finishes the user row is gone, so this reads nothing about the account. Finishing a
|
|
855
|
+
* purge that already finished is a no-op, so a retried Workflow step records and fires once — and so do two
|
|
856
|
+
* purges of one account that overlapped. **The insert is the check**: `0005_purge_once` allows one `purged` row
|
|
857
|
+
* per account, the insert ignores a second, and only the call whose row landed audits and fires. A read
|
|
858
|
+
* before the insert would let two concurrent calls both find nothing and both write.
|
|
859
|
+
*/
|
|
860
|
+
export async function completePurge(deps: LifecycleDeps, input: { userId: string }): Promise<LifecycleTransition> {
|
|
861
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
862
|
+
const inserted = await deps.db
|
|
863
|
+
.insertInto("pithyAuthUserLifecycle")
|
|
864
|
+
.values(encoded({ userId: input.userId, action: "purged", actor: PURGE, reason: null, at }))
|
|
865
|
+
.onConflict((conflict) => conflict.doNothing())
|
|
866
|
+
.executeTakeFirst();
|
|
867
|
+
if (Number(inserted.numInsertedOrUpdatedRows ?? 0n) === 0) return { changed: false, mailed: false };
|
|
868
|
+
|
|
869
|
+
await audit(deps, AuthAuditActions.adminUserPurged, input.userId, PURGE, {});
|
|
870
|
+
await fire(deps, "onUserPurged", deps.hooks.onUserPurged, { userId: input.userId, actor: PURGE, reason: null, at });
|
|
871
|
+
return { changed: true, mailed: false };
|
|
872
|
+
}
|