@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,623 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { AuthAuditActions } from "../audit/actions.js";
|
|
4
|
+
import { LifecycleColumns, accountStanding } from "./state.js";
|
|
5
|
+
import "./reason.js";
|
|
6
|
+
import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
8
|
+
import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
|
|
9
|
+
import { sql } from "kysely";
|
|
10
|
+
//#region src/lifecycle/transitions.ts
|
|
11
|
+
/** A reason, trimmed and bounded, or null when none was given. */
|
|
12
|
+
function reasonOf(reason) {
|
|
13
|
+
if (reason === null || reason === void 0) return null;
|
|
14
|
+
const trimmed = reason.trim();
|
|
15
|
+
if (trimmed === "") return null;
|
|
16
|
+
if (trimmed.length > 500) throw new ValidationError({
|
|
17
|
+
message: `A reason is at most 500 characters.`,
|
|
18
|
+
detail: `lifecycle reason of ${trimmed.length} characters`
|
|
19
|
+
});
|
|
20
|
+
return trimmed;
|
|
21
|
+
}
|
|
22
|
+
async function subjectOf(db, userId) {
|
|
23
|
+
const row = await db.selectFrom("pithyAuthUsers").select([
|
|
24
|
+
"email",
|
|
25
|
+
"name",
|
|
26
|
+
"locale",
|
|
27
|
+
"suspendedAt",
|
|
28
|
+
"suspendedUntil",
|
|
29
|
+
"deletedAt",
|
|
30
|
+
"purgeAfter"
|
|
31
|
+
]).where("id", "=", userId).executeTakeFirst();
|
|
32
|
+
if (!row) throw new NotFoundError({
|
|
33
|
+
message: "No such account.",
|
|
34
|
+
action: "If it was deleted and its purge has run, its data is gone and there is nothing to act on.",
|
|
35
|
+
detail: `lifecycle transition for user ${userId}, which has no row`
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
email: row.email,
|
|
39
|
+
name: row.name,
|
|
40
|
+
locale: row.locale ?? null,
|
|
41
|
+
columns: LifecycleColumns.parse(row)
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** A date written for its reader, in their language — the shape every lifecycle mail carries its dates in. */
|
|
45
|
+
function readable(date, locale) {
|
|
46
|
+
const tag = (locale ? formattingLocaleOf(locale) : null) ?? "en";
|
|
47
|
+
return new Intl.DateTimeFormat(tag, {
|
|
48
|
+
dateStyle: "long",
|
|
49
|
+
timeZone: "UTC"
|
|
50
|
+
}).format(date);
|
|
51
|
+
}
|
|
52
|
+
/** The history row's values, as the table stores them. */
|
|
53
|
+
function encoded(row) {
|
|
54
|
+
return {
|
|
55
|
+
userId: row.userId,
|
|
56
|
+
action: row.action,
|
|
57
|
+
actorType: row.actor.type,
|
|
58
|
+
actorId: row.actor.id,
|
|
59
|
+
reason: row.reason,
|
|
60
|
+
suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
|
|
61
|
+
step: row.step ?? null,
|
|
62
|
+
notify: row.notify === void 0 || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
|
|
63
|
+
createdAt: SQLiteDate.encode(row.at)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** A history row with no column change to pair it with: a purge step, a finished purge. Not swallowed. */
|
|
67
|
+
async function record(deps, row) {
|
|
68
|
+
await deps.db.insertInto("pithyAuthUserLifecycle").values(encoded(row)).execute();
|
|
69
|
+
}
|
|
70
|
+
/** Bind a compiled statement to D1, so it can join a `batch`. */
|
|
71
|
+
function prepared(d1, compiled) {
|
|
72
|
+
return d1.prepare(compiled.sql).bind(...compiled.parameters);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Move the columns and write the history row as one transaction, and say whether the account moved.
|
|
76
|
+
*
|
|
77
|
+
* The insert is guarded by `changes()`, which SQLite answers for the statement just before it — the update —
|
|
78
|
+
* so a conditional update that matched nothing writes no row. Not swallowed: until both are written, nothing
|
|
79
|
+
* after them runs.
|
|
80
|
+
*/
|
|
81
|
+
async function move(deps, update, row) {
|
|
82
|
+
const v = encoded(row);
|
|
83
|
+
const insert = deps.db.insertInto("pithyAuthUserLifecycle").columns([
|
|
84
|
+
"userId",
|
|
85
|
+
"action",
|
|
86
|
+
"actorType",
|
|
87
|
+
"actorId",
|
|
88
|
+
"reason",
|
|
89
|
+
"suspendedUntil",
|
|
90
|
+
"step",
|
|
91
|
+
"notify",
|
|
92
|
+
"createdAt"
|
|
93
|
+
]).expression(deps.db.selectNoFrom([
|
|
94
|
+
sql.val(v.userId).as("userId"),
|
|
95
|
+
sql.val(v.action).as("action"),
|
|
96
|
+
sql.val(v.actorType).as("actorType"),
|
|
97
|
+
sql.val(v.actorId).as("actorId"),
|
|
98
|
+
sql.val(v.reason).as("reason"),
|
|
99
|
+
sql.val(v.suspendedUntil).as("suspendedUntil"),
|
|
100
|
+
sql.val(v.step).as("step"),
|
|
101
|
+
sql.val(v.notify).as("notify"),
|
|
102
|
+
sql.val(v.createdAt).as("createdAt")
|
|
103
|
+
]).where(sql`changes()`, ">", 0)).compile();
|
|
104
|
+
const [updated] = await deps.d1.batch([prepared(deps.d1, update.compile()), prepared(deps.d1, insert)]);
|
|
105
|
+
return (updated?.meta.changes ?? 0) > 0;
|
|
106
|
+
}
|
|
107
|
+
/** The audit event, swallowed on failure — an audit write never breaks what it records. */
|
|
108
|
+
async function audit(deps, action, userId, actor, metadata) {
|
|
109
|
+
const context = deps.context;
|
|
110
|
+
const event = {
|
|
111
|
+
action,
|
|
112
|
+
outcome: "success",
|
|
113
|
+
actorType: actor.type,
|
|
114
|
+
actorId: actor.id,
|
|
115
|
+
resourceType: "user",
|
|
116
|
+
resourceId: userId,
|
|
117
|
+
...context?.ip ? { ip: context.ip } : {},
|
|
118
|
+
...context?.userAgent ? { userAgent: context.userAgent } : {},
|
|
119
|
+
...context?.requestId ? { requestId: context.requestId } : {},
|
|
120
|
+
metadata: {
|
|
121
|
+
...context?.metadata,
|
|
122
|
+
...metadata
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
try {
|
|
126
|
+
await deps.emit(event);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
deps.log?.warn(`lifecycle audit ${action} failed; the transition stands`, { reason: messageOf$1(error) });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. Says whether it was enqueued. */
|
|
132
|
+
async function mail(deps, enabled, to, locale, template, payload) {
|
|
133
|
+
if (!enabled || !deps.enqueueEmail) return false;
|
|
134
|
+
try {
|
|
135
|
+
await deps.enqueueEmail({
|
|
136
|
+
to,
|
|
137
|
+
template,
|
|
138
|
+
payload,
|
|
139
|
+
...locale ? { locale } : {}
|
|
140
|
+
});
|
|
141
|
+
return true;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, { reason: messageOf$1(error) });
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Fire one hook. Swallowed and logged: the transition is already written, and a retry would fire nothing. */
|
|
148
|
+
async function fire(deps, name, hook, event) {
|
|
149
|
+
if (!hook) return;
|
|
150
|
+
try {
|
|
151
|
+
await hook(event, deps.d1);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
deps.log?.warn(`${name} threw; the transition stands`, {
|
|
154
|
+
userId: event.userId,
|
|
155
|
+
reason: messageOf$1(error)
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function messageOf$1(error) {
|
|
160
|
+
return error instanceof Error ? error.message : String(error);
|
|
161
|
+
}
|
|
162
|
+
/** Without a name, a greeting says "Hi," rather than greeting an empty string. */
|
|
163
|
+
function named(name) {
|
|
164
|
+
return name.trim() ? { name } : {};
|
|
165
|
+
}
|
|
166
|
+
/** The conflict for a deleted account: deletion outranks a suspension, so restore it first. */
|
|
167
|
+
function deletedConflict(restoreRoute, then) {
|
|
168
|
+
return new ConflictError({
|
|
169
|
+
message: restoreRoute ? `This account is deleted. Restore it with ${restoreRoute} first.` : "This account is deleted. Restore it first.",
|
|
170
|
+
action: restoreRoute ? `Restore it with ${restoreRoute}. ${then}` : `Restore it first. ${then}`
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/** The conflict for a write that found the account moved under it by another request. Retrying is safe. */
|
|
174
|
+
function raced(userId) {
|
|
175
|
+
return new ConflictError({
|
|
176
|
+
message: "The account changed while this request was being made. Send it again.",
|
|
177
|
+
detail: `lifecycle write for user ${userId} matched no row; another request moved the account first`
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch (#622).
|
|
182
|
+
*
|
|
183
|
+
* A restore and a purge's `due` check race for one account, and each has to see the window the other saw. A
|
|
184
|
+
* timestamp the restore took before its statement went out is stale by the time D1 runs it: the window can
|
|
185
|
+
* close in between, by itself or because a hard deletion brought it forward, and a purge whose `due` check ran
|
|
186
|
+
* in that gap goes on to erase an account the restore reported back. So on the system clock the guard is the
|
|
187
|
+
* database's own time, evaluated inside the statement, and D1 runs statements one at a time: whichever lands
|
|
188
|
+
* first, the other sees it. An injected clock is a test's, and is read afresh here, at the statement.
|
|
189
|
+
*/
|
|
190
|
+
function windowClock(deps) {
|
|
191
|
+
return deps.now ? sql`${deps.now().getTime()}` : sql`cast(round(unixepoch('subsec') * 1000) as integer)`;
|
|
192
|
+
}
|
|
193
|
+
/** The conflict for an account whose purge window has closed: nothing can restore it now. */
|
|
194
|
+
function windowClosed(userId, closes) {
|
|
195
|
+
return new ConflictError({
|
|
196
|
+
message: `This account's purge window closed on ${closes.toISOString()}. It can no longer be restored.`,
|
|
197
|
+
action: "The purge is due and erases its data once it runs. There is nothing to restore.",
|
|
198
|
+
detail: `restore for user ${userId}, whose purge was due at ${closes.toISOString()}`
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Suspend an account, until `until` or until it is reinstated.
|
|
203
|
+
*
|
|
204
|
+
* A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
|
|
205
|
+
* conflict rather than a no-op, and names `restoreRoute` when the caller gives one. A suspension whose end has
|
|
206
|
+
* passed is not in force, and a new one replaces it.
|
|
207
|
+
*
|
|
208
|
+
* **An account already suspended has its terms restated (#621).** The reason and the end are replaced, a
|
|
209
|
+
* `suspended` row records the new reason — the newest one is what the person is shown — and the audit event
|
|
210
|
+
* and the mail say so. The start is kept, and no hook fires: the account was suspended and still is, so
|
|
211
|
+
* nothing transitioned. A fresh suspension that loses the race to another suspension finds the account
|
|
212
|
+
* suspended, so it retries once as a restatement rather than failing. A write that finds the account moved
|
|
213
|
+
* under it any other way, by a reinstatement or a deletion that landed first, is a conflict: what the caller
|
|
214
|
+
* asked for no longer describes the account.
|
|
215
|
+
*
|
|
216
|
+
* `notify: false` sends no mail, whatever the config says; the config can only turn mail off, never on.
|
|
217
|
+
*/
|
|
218
|
+
async function suspendUser(deps, input) {
|
|
219
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
220
|
+
const reason = reasonOf(input.reason);
|
|
221
|
+
const until = input.until ?? null;
|
|
222
|
+
if (until && until.getTime() <= at.getTime()) throw new ValidationError({ message: "A suspension must end in the future, or not at all." });
|
|
223
|
+
const subject = await subjectOf(deps.db, input.userId);
|
|
224
|
+
const standing = accountStanding(subject.columns, at);
|
|
225
|
+
if (standing.state === "deleted") throw deletedConflict(input.restoreRoute, "Then suspend it, if it should be suspended instead.");
|
|
226
|
+
const encodedUntil = until ? SQLiteDate.encode(until) : null;
|
|
227
|
+
/** 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. */
|
|
228
|
+
const restatement = (startedAt) => deps.db.updateTable("pithyAuthUsers").set({ suspendedUntil: encodedUntil }).where("id", "=", input.userId).where("deletedAt", "is", null).where("suspendedAt", "=", SQLiteDate.encode(startedAt)).where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
|
|
229
|
+
const fresh = deps.db.updateTable("pithyAuthUsers").set({
|
|
230
|
+
suspendedAt: SQLiteDate.encode(at),
|
|
231
|
+
suspendedUntil: encodedUntil
|
|
232
|
+
}).where("id", "=", input.userId).where("deletedAt", "is", null).where((eb) => eb.or([eb("suspendedAt", "is", null), eb.and([eb("suspendedUntil", "is not", null), eb("suspendedUntil", "<=", SQLiteDate.encode(at))])]));
|
|
233
|
+
const row = {
|
|
234
|
+
userId: input.userId,
|
|
235
|
+
action: "suspended",
|
|
236
|
+
actor: input.actor,
|
|
237
|
+
reason,
|
|
238
|
+
at,
|
|
239
|
+
suspendedUntil: until
|
|
240
|
+
};
|
|
241
|
+
let updated = standing.state === "suspended";
|
|
242
|
+
let startedAt = updated && subject.columns.suspendedAt ? subject.columns.suspendedAt : at;
|
|
243
|
+
if (!await move(deps, updated ? restatement(startedAt) : fresh, row)) {
|
|
244
|
+
const now = updated ? null : await subjectOf(deps.db, input.userId);
|
|
245
|
+
const moved = now ? accountStanding(now.columns, at) : null;
|
|
246
|
+
if (!now?.columns.suspendedAt || moved?.state !== "suspended") throw raced(input.userId);
|
|
247
|
+
updated = true;
|
|
248
|
+
startedAt = now.columns.suspendedAt;
|
|
249
|
+
if (!await move(deps, restatement(startedAt), row)) throw raced(input.userId);
|
|
250
|
+
}
|
|
251
|
+
await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
|
|
252
|
+
reason,
|
|
253
|
+
suspendedUntil: until?.toISOString() ?? null,
|
|
254
|
+
updated
|
|
255
|
+
});
|
|
256
|
+
const mailed = await mail(deps, deps.config.lifecycleEmails.accountSuspended && input.notify !== false, subject.email, subject.locale, "accountSuspended", {
|
|
257
|
+
...named(subject.name),
|
|
258
|
+
...reason ? { reason } : {},
|
|
259
|
+
...until ? { until: readable(until, subject.locale) } : {}
|
|
260
|
+
});
|
|
261
|
+
if (!updated) await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
|
|
262
|
+
userId: input.userId,
|
|
263
|
+
actor: input.actor,
|
|
264
|
+
reason,
|
|
265
|
+
at,
|
|
266
|
+
suspendedUntil: until
|
|
267
|
+
});
|
|
268
|
+
return {
|
|
269
|
+
changed: !updated,
|
|
270
|
+
updated,
|
|
271
|
+
mailed,
|
|
272
|
+
suspendedAt: startedAt,
|
|
273
|
+
suspendedUntil: until
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Lift a suspension. An account that is not suspended — including one whose suspension ran out — is a no-op.
|
|
278
|
+
*
|
|
279
|
+
* Where the account stands is read through `accountStanding`, never off the raw column, because a suspension
|
|
280
|
+
* past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
|
|
281
|
+
* for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
|
|
282
|
+
* sign in again" to somebody every sign-in still refuses. Restore it first.
|
|
283
|
+
*
|
|
284
|
+
* `notify: false` sends no mail, on the same rule as `suspendUser`.
|
|
285
|
+
*/
|
|
286
|
+
async function reinstateUser(deps, input) {
|
|
287
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
288
|
+
const reason = reasonOf(input.reason);
|
|
289
|
+
const subject = await subjectOf(deps.db, input.userId);
|
|
290
|
+
const standing = accountStanding(subject.columns, at);
|
|
291
|
+
if (standing.state === "deleted") throw deletedConflict(input.restoreRoute, "Its suspension stays in place through a restore, and can be lifted after.");
|
|
292
|
+
if (standing.state !== "suspended") return {
|
|
293
|
+
changed: false,
|
|
294
|
+
mailed: false
|
|
295
|
+
};
|
|
296
|
+
if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
|
|
297
|
+
suspendedAt: null,
|
|
298
|
+
suspendedUntil: null
|
|
299
|
+
}).where("id", "=", input.userId).where("deletedAt", "is", null).where("suspendedAt", "is not", null).where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))])), {
|
|
300
|
+
userId: input.userId,
|
|
301
|
+
action: "reinstated",
|
|
302
|
+
actor: input.actor,
|
|
303
|
+
reason,
|
|
304
|
+
at
|
|
305
|
+
})) return {
|
|
306
|
+
changed: false,
|
|
307
|
+
mailed: false
|
|
308
|
+
};
|
|
309
|
+
await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
|
|
310
|
+
const mailed = await mail(deps, deps.config.lifecycleEmails.accountReinstated && input.notify !== false, subject.email, subject.locale, "accountReinstated", named(subject.name));
|
|
311
|
+
await fire(deps, "onUserReinstated", deps.hooks.onUserReinstated, {
|
|
312
|
+
userId: input.userId,
|
|
313
|
+
actor: input.actor,
|
|
314
|
+
reason,
|
|
315
|
+
at
|
|
316
|
+
});
|
|
317
|
+
return {
|
|
318
|
+
changed: true,
|
|
319
|
+
mailed
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Delete an account. Audited as the account's own deletion when its holder is the actor.
|
|
324
|
+
*
|
|
325
|
+
* **Soft, the default**: it is shut now, and its data is erased once `retention.purgeAfterDays` have passed.
|
|
326
|
+
* Restorable until then. The deletion-scheduled mail carries the purge date and, when the config names one,
|
|
327
|
+
* the restore path. A deleted account deleted softly again is no transition.
|
|
328
|
+
*
|
|
329
|
+
* **Hard** (#622): `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
|
|
330
|
+
* caller starts the purge. No deletion-scheduled mail, because nothing is scheduled; the purge sends the
|
|
331
|
+
* deletion-complete one. An account already deleted softly has its purge brought forward to now, which is
|
|
332
|
+
* written and audited but fires no hook: the account was deleted and still is. One already due is unchanged.
|
|
333
|
+
*
|
|
334
|
+
* A suspension the account was under is left in place, so restoring the account does not lift it.
|
|
335
|
+
* `notify: false` sends no mail, whatever the config says.
|
|
336
|
+
*/
|
|
337
|
+
async function deleteUser(deps, input) {
|
|
338
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
339
|
+
const reason = reasonOf(input.reason);
|
|
340
|
+
const hard = input.mode === "hard";
|
|
341
|
+
const purgeAfter = hard ? at : new Date(at.getTime() + deps.config.retention.purgeAfterDays * 864e5);
|
|
342
|
+
const subject = await subjectOf(deps.db, input.userId);
|
|
343
|
+
const row = {
|
|
344
|
+
userId: input.userId,
|
|
345
|
+
action: "deleted",
|
|
346
|
+
actor: input.actor,
|
|
347
|
+
reason,
|
|
348
|
+
at,
|
|
349
|
+
...hard && input.notify !== void 0 ? { notify: input.notify } : {}
|
|
350
|
+
};
|
|
351
|
+
const existing = subject.columns.deletedAt;
|
|
352
|
+
if (existing) {
|
|
353
|
+
const due = subject.columns.purgeAfter ?? existing;
|
|
354
|
+
const unchanged = {
|
|
355
|
+
changed: false,
|
|
356
|
+
mailed: false,
|
|
357
|
+
outcome: "unchanged",
|
|
358
|
+
deletedAt: existing,
|
|
359
|
+
purgeAfter: due
|
|
360
|
+
};
|
|
361
|
+
if (!hard || due.getTime() <= at.getTime()) return unchanged;
|
|
362
|
+
if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({ purgeAfter: SQLiteDate.encode(at) }).where("id", "=", input.userId).where("deletedAt", "=", SQLiteDate.encode(existing)).where("purgeAfter", ">", SQLiteDate.encode(at)), row)) return unchanged;
|
|
363
|
+
await audit(deps, AuthAuditActions.adminUserHardDeleted, input.userId, input.actor, {
|
|
364
|
+
reason,
|
|
365
|
+
purgeAfter: at.toISOString(),
|
|
366
|
+
broughtForward: true
|
|
367
|
+
});
|
|
368
|
+
return {
|
|
369
|
+
changed: false,
|
|
370
|
+
mailed: false,
|
|
371
|
+
outcome: "brought_forward",
|
|
372
|
+
deletedAt: existing,
|
|
373
|
+
purgeAfter: at
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
|
|
377
|
+
deletedAt: SQLiteDate.encode(at),
|
|
378
|
+
purgeAfter: SQLiteDate.encode(purgeAfter)
|
|
379
|
+
}).where("id", "=", input.userId).where("deletedAt", "is", null), row)) {
|
|
380
|
+
const now = await subjectOf(deps.db, input.userId);
|
|
381
|
+
if (!now.columns.deletedAt) throw raced(input.userId);
|
|
382
|
+
const due = now.columns.purgeAfter ?? now.columns.deletedAt;
|
|
383
|
+
return {
|
|
384
|
+
changed: false,
|
|
385
|
+
mailed: false,
|
|
386
|
+
outcome: "unchanged",
|
|
387
|
+
deletedAt: now.columns.deletedAt,
|
|
388
|
+
purgeAfter: due
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
const self = input.actor.type === "user" && input.actor.id === input.userId;
|
|
392
|
+
await audit(deps, hard ? AuthAuditActions.adminUserHardDeleted : self ? AuthAuditActions.userSelfDeleted : AuthAuditActions.adminUserSoftDeleted, input.userId, input.actor, {
|
|
393
|
+
reason,
|
|
394
|
+
purgeAfter: purgeAfter.toISOString()
|
|
395
|
+
});
|
|
396
|
+
const restoreUrl = deps.config.retention.restoreUrl;
|
|
397
|
+
const mailed = hard ? false : await mail(deps, deps.config.lifecycleEmails.deletionScheduled && input.notify !== false, subject.email, subject.locale, "deletionScheduled", {
|
|
398
|
+
...named(subject.name),
|
|
399
|
+
purgeOn: readable(purgeAfter, subject.locale),
|
|
400
|
+
...restoreUrl ? { restoreUrl } : {}
|
|
401
|
+
});
|
|
402
|
+
await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
|
|
403
|
+
userId: input.userId,
|
|
404
|
+
actor: input.actor,
|
|
405
|
+
reason,
|
|
406
|
+
at,
|
|
407
|
+
purgeAfter
|
|
408
|
+
});
|
|
409
|
+
return {
|
|
410
|
+
changed: true,
|
|
411
|
+
mailed,
|
|
412
|
+
outcome: "deleted",
|
|
413
|
+
deletedAt: at,
|
|
414
|
+
purgeAfter
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Restore a deleted account inside its purge window.
|
|
419
|
+
*
|
|
420
|
+
* **Only inside it.** Once `purgeAfter` has passed the purge is due, may already be running, and erases each
|
|
421
|
+
* capability's rows in turn, so restoring then would hand back an account with some of its data gone. That
|
|
422
|
+
* is a conflict naming the date the window closed. After the purge there is no account at all, and that is a
|
|
423
|
+
* 404 whose action says the data is gone — read off the history row the purge leaves behind, so it is told
|
|
424
|
+
* apart from an id that never existed.
|
|
425
|
+
*
|
|
426
|
+
* An account that is not deleted is no transition. A suspension it was under is still in force after.
|
|
427
|
+
*/
|
|
428
|
+
async function restoreUser(deps, input) {
|
|
429
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
430
|
+
const reason = reasonOf(input.reason);
|
|
431
|
+
const subject = await subjectOf(deps.db, input.userId).catch(async (error) => {
|
|
432
|
+
throw await purgedRefusal(deps.db, input.userId) ?? error;
|
|
433
|
+
});
|
|
434
|
+
const suspended = (columns) => accountStanding({
|
|
435
|
+
...columns,
|
|
436
|
+
deletedAt: null,
|
|
437
|
+
purgeAfter: null
|
|
438
|
+
}, at).state === "suspended";
|
|
439
|
+
const state = suspended(subject.columns) ? "suspended" : "active";
|
|
440
|
+
if (!subject.columns.deletedAt) return {
|
|
441
|
+
changed: false,
|
|
442
|
+
mailed: false,
|
|
443
|
+
state
|
|
444
|
+
};
|
|
445
|
+
const closes = subject.columns.purgeAfter;
|
|
446
|
+
if (closes && closes.getTime() <= at.getTime()) throw windowClosed(input.userId, closes);
|
|
447
|
+
if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
|
|
448
|
+
deletedAt: null,
|
|
449
|
+
purgeAfter: null
|
|
450
|
+
}).where("id", "=", input.userId).where("deletedAt", "is not", null).where("purgeAfter", ">", windowClock(deps)), {
|
|
451
|
+
userId: input.userId,
|
|
452
|
+
action: "restored",
|
|
453
|
+
actor: input.actor,
|
|
454
|
+
reason,
|
|
455
|
+
at
|
|
456
|
+
})) {
|
|
457
|
+
const now = await subjectOf(deps.db, input.userId).catch(async (error) => {
|
|
458
|
+
throw await purgedRefusal(deps.db, input.userId) ?? error;
|
|
459
|
+
});
|
|
460
|
+
if (!now.columns.deletedAt) return {
|
|
461
|
+
changed: false,
|
|
462
|
+
mailed: false,
|
|
463
|
+
state: suspended(now.columns) ? "suspended" : "active"
|
|
464
|
+
};
|
|
465
|
+
const closed = now.columns.purgeAfter;
|
|
466
|
+
if (closed && closed.getTime() <= (deps.now ?? (() => /* @__PURE__ */ new Date()))().getTime()) throw windowClosed(input.userId, closed);
|
|
467
|
+
throw raced(input.userId);
|
|
468
|
+
}
|
|
469
|
+
await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
|
|
470
|
+
return {
|
|
471
|
+
changed: true,
|
|
472
|
+
mailed: false,
|
|
473
|
+
state
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* The refusal for an account the purge has erased, or `null` when none was. A 404, because there is no
|
|
478
|
+
* account, with the date in the action so an operator answering a restore request knows it is final.
|
|
479
|
+
*/
|
|
480
|
+
async function purgedRefusal(db, userId) {
|
|
481
|
+
const purged = await db.selectFrom("pithyAuthUserLifecycle").select("createdAt").where("userId", "=", userId).where("action", "=", "purged").orderBy("id", "desc").executeTakeFirst();
|
|
482
|
+
if (!purged) return null;
|
|
483
|
+
const on = SQLiteDate.parse(purged.createdAt).toISOString();
|
|
484
|
+
return new NotFoundError({
|
|
485
|
+
message: "No such account.",
|
|
486
|
+
action: `This account was purged on ${on}. Its data is gone, and there is nothing to restore or export.`,
|
|
487
|
+
detail: `user ${userId} was purged at ${on}`
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* The account's row, or the refusal for one that is not there — the 404 that says the data is gone when the
|
|
492
|
+
* purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
|
|
493
|
+
* export.
|
|
494
|
+
*/
|
|
495
|
+
async function requirePresent(db, userId) {
|
|
496
|
+
if (await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", userId).executeTakeFirst()) return;
|
|
497
|
+
throw await purgedRefusal(db, userId) ?? new NotFoundError({
|
|
498
|
+
message: "No such user.",
|
|
499
|
+
detail: `no pithy_auth_users row for ${userId}`
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
/** The purge's own actor: a scheduled job, with nobody calling. */
|
|
503
|
+
const PURGE = {
|
|
504
|
+
type: "system",
|
|
505
|
+
id: null
|
|
506
|
+
};
|
|
507
|
+
/**
|
|
508
|
+
* Whether one account is due for its purge, who its last mail goes to, and whether it goes (#622).
|
|
509
|
+
*
|
|
510
|
+
* `due` only for an account that is deleted and whose `purgeAfter` has passed — the cron and a hard deletion
|
|
511
|
+
* both start a purge, and this is the one check either passes through, so an account restored in between is
|
|
512
|
+
* `not_due` and nothing is erased. `gone` when there is no row: the purge already erased it, or the id never
|
|
513
|
+
* existed, and either way there is nothing to do. The recipient is read here, before the first step, because
|
|
514
|
+
* the last step erases it.
|
|
515
|
+
*
|
|
516
|
+
* `notify` is what the deletion in force asked of the last mail — its newest `deleted` row's — so a hard
|
|
517
|
+
* deletion's `notify: false` holds for a purge the daily pass started, which was handed no such parameter.
|
|
518
|
+
*/
|
|
519
|
+
async function purgeSubject(deps, userId) {
|
|
520
|
+
const row = await deps.db.selectFrom("pithyAuthUsers").select([
|
|
521
|
+
"email",
|
|
522
|
+
"name",
|
|
523
|
+
"locale",
|
|
524
|
+
"suspendedAt",
|
|
525
|
+
"suspendedUntil",
|
|
526
|
+
"deletedAt",
|
|
527
|
+
"purgeAfter"
|
|
528
|
+
]).select(windowClock(deps).as("checkedAt")).where("id", "=", userId).executeTakeFirst();
|
|
529
|
+
if (!row) return { state: "gone" };
|
|
530
|
+
const columns = LifecycleColumns.parse(row);
|
|
531
|
+
if (!columns.deletedAt || !columns.purgeAfter || columns.purgeAfter.getTime() > Number(row.checkedAt)) return { state: "not_due" };
|
|
532
|
+
const saved = (await deps.db.selectFrom("pithyAuthUserLifecycle").select("notify").where("userId", "=", userId).where("action", "=", "deleted").orderBy("id", "desc").limit(1).executeTakeFirst())?.notify;
|
|
533
|
+
const notify = saved === void 0 || saved === null ? null : SQLiteBoolean.decode(saved);
|
|
534
|
+
return {
|
|
535
|
+
state: "due",
|
|
536
|
+
recipient: {
|
|
537
|
+
email: row.email,
|
|
538
|
+
name: row.name,
|
|
539
|
+
locale: row.locale ?? null
|
|
540
|
+
},
|
|
541
|
+
notify
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
|
|
546
|
+
* What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
|
|
547
|
+
* that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
|
|
548
|
+
*/
|
|
549
|
+
async function duePurges(deps, limit) {
|
|
550
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
551
|
+
return (await deps.db.selectFrom("pithyAuthUsers").select(["id", "deletedAt"]).where("deletedAt", "is not", null).where("purgeAfter", "is not", null).where("purgeAfter", "<=", SQLiteDate.encode(at)).orderBy("purgeAfter", "asc").orderBy("id", "asc").limit(limit).execute()).map((row) => ({
|
|
552
|
+
userId: row.id,
|
|
553
|
+
deletedAt: Number(row.deletedAt)
|
|
554
|
+
}));
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
|
|
558
|
+
* the row's reason, so the history says what the step erased and not only that it ran.
|
|
559
|
+
*/
|
|
560
|
+
async function recordPurgeStep(deps, input) {
|
|
561
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
562
|
+
await record(deps, {
|
|
563
|
+
userId: input.userId,
|
|
564
|
+
action: "purge_step",
|
|
565
|
+
actor: PURGE,
|
|
566
|
+
reason: input.summary?.trim() ? input.summary.trim().slice(0, 500) : null,
|
|
567
|
+
at,
|
|
568
|
+
step: input.step
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
|
|
573
|
+
* other capability's rows are gone and before auth's own, which holds the address, so the last mail is
|
|
574
|
+
* enqueued while there is still an account to have sent it to. The address is handed in, captured before the
|
|
575
|
+
* first step. `notify: false` sends nothing, whatever the config says.
|
|
576
|
+
*/
|
|
577
|
+
async function mailPurgeComplete(deps, input) {
|
|
578
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
579
|
+
const { email, name, locale } = input.recipient;
|
|
580
|
+
return {
|
|
581
|
+
changed: false,
|
|
582
|
+
mailed: await mail(deps, deps.config.lifecycleEmails.deletionComplete && input.notify !== false, email, locale, "deletionComplete", {
|
|
583
|
+
...named(name ?? ""),
|
|
584
|
+
purgedOn: readable(at, locale)
|
|
585
|
+
})
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Finish a purge: the record, the audit event, the hook. The last thing that happens to the account.
|
|
590
|
+
*
|
|
591
|
+
* By the time a purge finishes the user row is gone, so this reads nothing about the account. Finishing a
|
|
592
|
+
* purge that already finished is a no-op, so a retried Workflow step records and fires once — and so do two
|
|
593
|
+
* purges of one account that overlapped. **The insert is the check**: `0005_purge_once` allows one `purged` row
|
|
594
|
+
* per account, the insert ignores a second, and only the call whose row landed audits and fires. A read
|
|
595
|
+
* before the insert would let two concurrent calls both find nothing and both write.
|
|
596
|
+
*/
|
|
597
|
+
async function completePurge(deps, input) {
|
|
598
|
+
const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
599
|
+
const inserted = await deps.db.insertInto("pithyAuthUserLifecycle").values(encoded({
|
|
600
|
+
userId: input.userId,
|
|
601
|
+
action: "purged",
|
|
602
|
+
actor: PURGE,
|
|
603
|
+
reason: null,
|
|
604
|
+
at
|
|
605
|
+
})).onConflict((conflict) => conflict.doNothing()).executeTakeFirst();
|
|
606
|
+
if (Number(inserted.numInsertedOrUpdatedRows ?? 0n) === 0) return {
|
|
607
|
+
changed: false,
|
|
608
|
+
mailed: false
|
|
609
|
+
};
|
|
610
|
+
await audit(deps, AuthAuditActions.adminUserPurged, input.userId, PURGE, {});
|
|
611
|
+
await fire(deps, "onUserPurged", deps.hooks.onUserPurged, {
|
|
612
|
+
userId: input.userId,
|
|
613
|
+
actor: PURGE,
|
|
614
|
+
reason: null,
|
|
615
|
+
at
|
|
616
|
+
});
|
|
617
|
+
return {
|
|
618
|
+
changed: true,
|
|
619
|
+
mailed: false
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
//#endregion
|
|
623
|
+
export { completePurge, deleteUser, duePurges, mailPurgeComplete, purgeSubject, recordPurgeStep, reinstateUser, requirePresent, restoreUser, suspendUser };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { Migration } from "kysely/migration";
|
|
4
|
+
/**
|
|
5
|
+
* The account lifecycle (#620): whether an account is suspended or deleted, and the record of how it got
|
|
6
|
+
* there.
|
|
7
|
+
*
|
|
8
|
+
* **Four columns on `pithy_auth_users`, so a session read already carries the state.** Better Auth loads the
|
|
9
|
+
* user row for every session it resolves, and returns these because `../data/kitFields.ts` declares them —
|
|
10
|
+
* so refusing a suspended account costs no query on the request that is refused, and none on the requests
|
|
11
|
+
* that are not.
|
|
12
|
+
*
|
|
13
|
+
* **One kit-owned table beside them, `pithy_auth_user_lifecycle`**, holding every transition with its
|
|
14
|
+
* actor, its reason and its time. The columns say what is true now; the table says what happened. No
|
|
15
|
+
* foreign key from it to the user: a purge erases the user row, and this table is the record that must
|
|
16
|
+
* outlive it (`../data/userLifecycle.ts`).
|
|
17
|
+
*
|
|
18
|
+
* **`integer`, not `text`, unlike every Better Auth date on the same table.** Better Auth writes those, as
|
|
19
|
+
* ISO-8601. Nothing but the kit writes these — they are `input: false` — so they take the house ms-epoch
|
|
20
|
+
* convention, and `type: "number"` in `kitFields.ts` keeps Better Auth from converting what it reads back.
|
|
21
|
+
*
|
|
22
|
+
* **Nullable, with no backfill.** Every account that exists when this runs is in neither state, and null is
|
|
23
|
+
* exactly that. SQLite would refuse `ADD COLUMN … NOT NULL` without a constant default anyway.
|
|
24
|
+
*
|
|
25
|
+
* **A `0004`, appended, never folded into `0001`.** `@pithy-sh/auth` has shipped, so its chain is history.
|
|
26
|
+
*/
|
|
27
|
+
export declare const auth_0004_user_lifecycle: Migration;
|
|
28
|
+
//# sourceMappingURL=0004_user_lifecycle.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"0004_user_lifecycle.d.ts","sourceRoot":"","sources":["../../src/migrations/0004_user_lifecycle.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAKlD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,wBAAwB,EAAE,SAmCtC,CAAC"}
|