@pithy-sh/auth 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -2
- package/dist/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +58 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +59 -1
- package/dist/audit/emit.d.ts +36 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +48 -2
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +47 -8
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +56 -6
- package/dist/client/api.d.ts +55 -12
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +57 -18
- package/dist/client/bearer.d.ts +110 -0
- package/dist/client/bearer.d.ts.map +1 -0
- package/dist/client/bearer.js +265 -0
- package/dist/client/handoff.d.ts +77 -0
- package/dist/client/handoff.d.ts.map +1 -0
- package/dist/client/handoff.js +119 -0
- package/dist/client/mcp.d.ts +70 -0
- package/dist/client/mcp.d.ts.map +1 -0
- package/dist/client/mcp.js +65 -0
- package/dist/data/betterAuth.d.ts +3 -2
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +5 -3
- package/dist/data/kitFields.d.ts +5 -0
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +5 -0
- package/dist/data/tables.d.ts +26 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +10 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +8 -3
- package/dist/data/verificationOutcome.d.ts +53 -0
- package/dist/data/verificationOutcome.d.ts.map +1 -0
- package/dist/data/verificationOutcome.js +50 -0
- package/dist/email/send.js +6 -2
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +319 -8
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -10
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +76 -10
- package/dist/http/handoff.d.ts +76 -0
- package/dist/http/handoff.d.ts.map +1 -0
- package/dist/http/handoff.js +316 -0
- package/dist/http/middleware.d.ts +37 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +68 -6
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +322 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +202 -5
- package/dist/http/routes.d.ts +3 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +78 -5
- package/dist/http/schemas.d.ts +114 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +94 -1
- package/dist/http/views.d.ts +60 -3
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +143 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/instance/auth.d.ts +148 -10
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +87 -42
- package/dist/instance/plugins.d.ts +6 -0
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +14 -1
- package/dist/ledger/read.d.ts +53 -0
- package/dist/ledger/read.d.ts.map +1 -0
- package/dist/ledger/read.js +85 -0
- package/dist/ledger/record.d.ts +35 -0
- package/dist/ledger/record.d.ts.map +1 -0
- package/dist/ledger/record.js +98 -0
- package/dist/lifecycle/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +37 -2
- package/dist/lifecycle/enforce.d.ts.map +1 -1
- package/dist/lifecycle/enforce.js +46 -5
- package/dist/lifecycle/erasure.d.ts +9 -0
- package/dist/lifecycle/erasure.d.ts.map +1 -0
- package/dist/lifecycle/erasure.js +96 -0
- package/dist/lifecycle/inactivity.d.ts +19 -0
- package/dist/lifecycle/inactivity.d.ts.map +1 -0
- package/dist/lifecycle/inactivity.js +28 -0
- package/dist/lifecycle/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +5 -2
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +6 -2
- package/dist/lifecycle/transitions.d.ts +179 -18
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +391 -70
- package/dist/mcp/argumentClass.d.ts +51 -0
- package/dist/mcp/argumentClass.d.ts.map +1 -0
- package/dist/mcp/argumentClass.js +69 -0
- package/dist/mcp/capability.d.ts +50 -0
- package/dist/mcp/capability.d.ts.map +1 -0
- package/dist/mcp/capability.js +140 -0
- package/dist/mcp/clientMetadata.d.ts +40 -0
- package/dist/mcp/clientMetadata.d.ts.map +1 -0
- package/dist/mcp/clientMetadata.js +68 -0
- package/dist/mcp/consent.d.ts +49 -0
- package/dist/mcp/consent.d.ts.map +1 -0
- package/dist/mcp/consent.js +69 -0
- package/dist/mcp/dispatch.d.ts +35 -0
- package/dist/mcp/dispatch.d.ts.map +1 -0
- package/dist/mcp/dispatch.js +135 -0
- package/dist/mcp/floor.d.ts +37 -0
- package/dist/mcp/floor.d.ts.map +1 -0
- package/dist/mcp/floor.js +41 -0
- package/dist/mcp/host.d.ts +34 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +2 -0
- package/dist/mcp/http/redirectList.d.ts +9 -0
- package/dist/mcp/http/redirectList.d.ts.map +1 -0
- package/dist/mcp/http/redirectList.js +24 -0
- package/dist/mcp/http/responses.d.ts +143 -0
- package/dist/mcp/http/responses.d.ts.map +1 -0
- package/dist/mcp/http/responses.js +83 -0
- package/dist/mcp/http/routes.d.ts +28 -0
- package/dist/mcp/http/routes.d.ts.map +1 -0
- package/dist/mcp/http/routes.js +517 -0
- package/dist/mcp/http/schemas.d.ts +24 -0
- package/dist/mcp/http/schemas.d.ts.map +1 -0
- package/dist/mcp/http/schemas.js +18 -0
- package/dist/mcp/marker.d.ts +15 -0
- package/dist/mcp/marker.d.ts.map +1 -0
- package/dist/mcp/marker.js +15 -0
- package/dist/mcp/provider.d.ts +78 -0
- package/dist/mcp/provider.d.ts.map +1 -0
- package/dist/mcp/provider.js +108 -0
- package/dist/mcp/purge.d.ts +15 -0
- package/dist/mcp/purge.d.ts.map +1 -0
- package/dist/mcp/purge.js +31 -0
- package/dist/mcp/rpc.d.ts +79 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +103 -0
- package/dist/mcp/toolAudit.d.ts +76 -0
- package/dist/mcp/toolAudit.d.ts.map +1 -0
- package/dist/mcp/toolAudit.js +86 -0
- package/dist/migrations/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -0
- package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
- package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
- package/dist/migrations/0006_verification_outcomes.js +35 -0
- package/dist/migrations/0007_erasure_record.d.ts +17 -0
- package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
- package/dist/migrations/0007_erasure_record.js +36 -0
- package/dist/migrations/0008_last_active.d.ts +15 -0
- package/dist/migrations/0008_last_active.d.ts.map +1 -0
- package/dist/migrations/0008_last_active.js +29 -0
- package/dist/migrations/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +5 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +10 -2
- package/dist/peer.d.ts +3 -2
- package/dist/peer.d.ts.map +1 -1
- package/dist/processing/activities.d.ts +6 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +12 -0
- package/dist/purge/contribution.d.ts +62 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +155 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +158 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +205 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +71 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +140 -0
- package/dist/test-utils/accountFootprint.d.ts +13 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +49 -0
- package/dist/test-utils/liveApp.d.ts +6 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +7 -2
- package/dist/token/handoff.d.ts +80 -0
- package/dist/token/handoff.d.ts.map +1 -0
- package/dist/token/handoff.js +136 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +176 -12
- package/docs/apple-signin.md +32 -4
- package/docs/facebook-oauth.md +2 -2
- package/docs/github-oauth.md +2 -2
- package/docs/google-oauth.md +9 -7
- package/docs/microsoft-oauth.md +2 -2
- package/package.json +11 -5
- package/pithy.manifest.json +2 -2
- package/pithy.mcp.manifest.json +36 -0
- package/src/audit/actions.ts +58 -0
- package/src/audit/emit.ts +66 -1
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +122 -18
- package/src/client/api.ts +69 -19
- package/src/client/bearer.ts +388 -0
- package/src/client/handoff.ts +172 -0
- package/src/client/mcp.ts +140 -0
- package/src/data/betterAuth.ts +8 -4
- package/src/data/kitFields.ts +2 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +19 -4
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +465 -4
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +79 -10
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +74 -5
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +374 -3
- package/src/http/routes.ts +116 -5
- package/src/http/schemas.ts +195 -0
- package/src/http/views.ts +192 -3
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +58 -3
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +55 -5
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +10 -2
- package/src/lifecycle/transitions.ts +552 -93
- package/src/mcp/argumentClass.ts +112 -0
- package/src/mcp/capability.ts +194 -0
- package/src/mcp/clientMetadata.ts +81 -0
- package/src/mcp/consent.ts +95 -0
- package/src/mcp/dispatch.ts +154 -0
- package/src/mcp/floor.ts +62 -0
- package/src/mcp/host.ts +36 -0
- package/src/mcp/http/redirectList.ts +26 -0
- package/src/mcp/http/responses.ts +157 -0
- package/src/mcp/http/routes.ts +635 -0
- package/src/mcp/http/schemas.ts +37 -0
- package/src/mcp/marker.ts +18 -0
- package/src/mcp/provider.ts +151 -0
- package/src/mcp/purge.ts +39 -0
- package/src/mcp/rpc.ts +135 -0
- package/src/mcp/toolAudit.ts +132 -0
- package/src/migrations/0005_purge_once.ts +42 -0
- package/src/migrations/0006_verification_outcomes.ts +51 -0
- package/src/migrations/0007_erasure_record.ts +43 -0
- package/src/migrations/0008_last_active.ts +30 -0
- package/src/migrations/pluginTables.ts +19 -1
- package/src/migrations/set.ts +9 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +218 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +348 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +202 -0
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +104 -0
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
import type { D1Database, D1PreparedStatement } from "@cloudflare/workers-types";
|
|
5
5
|
import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
|
|
6
6
|
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
7
|
-
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
7
|
+
import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
8
8
|
import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
9
9
|
import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
|
|
10
10
|
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
11
|
+
import { composedRetention } from "@pithy-sh/core/src/retention/composed";
|
|
12
|
+
import { purgeWindowDays } from "@pithy-sh/core/src/retention/policy";
|
|
11
13
|
import type { EnqueueInput } from "@pithy-sh/email/src/send/enqueue";
|
|
12
14
|
import { type CompiledQuery, sql } from "kysely";
|
|
13
15
|
import { type AuthAuditAction, AuthAuditActions } from "../audit/actions";
|
|
@@ -15,6 +17,7 @@ import type { AuthConfig } from "../capability";
|
|
|
15
17
|
import type { AuthDatabase } from "../data/tables";
|
|
16
18
|
import type { UserLifecycleAction, UserLifecycleActorType } from "../data/userLifecycle";
|
|
17
19
|
import type { UserLifecycleHookEvent, UserLifecycleHooks, UserLifecycleListener } from "./hooks";
|
|
20
|
+
import { MAX_REASON } from "./reason";
|
|
18
21
|
import { accountStanding, LifecycleColumns } from "./state";
|
|
19
22
|
|
|
20
23
|
/**
|
|
@@ -69,16 +72,45 @@ export interface LifecycleDeps {
|
|
|
69
72
|
readonly log?: Logger | undefined;
|
|
70
73
|
/** The clock. Defaults to the system's. */
|
|
71
74
|
readonly now?: (() => Date) | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* The request a transition was asked from, carried onto its audit event: the correlation every admin event
|
|
77
|
+
* carries, and metadata the caller adds — the management connection's id, for a control-plane call.
|
|
78
|
+
*/
|
|
79
|
+
readonly context?: LifecycleAuditContext | undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** What the caller's request adds to a transition's audit event. */
|
|
83
|
+
export interface LifecycleAuditContext {
|
|
84
|
+
/** The caller's address, from `cf-connecting-ip`. */
|
|
85
|
+
readonly ip?: string | undefined;
|
|
86
|
+
/** The caller's user agent. */
|
|
87
|
+
readonly userAgent?: string | undefined;
|
|
88
|
+
/** The request's id, from `cf-ray`. */
|
|
89
|
+
readonly requestId?: string | undefined;
|
|
90
|
+
/** Extra metadata, merged under the transition's own. */
|
|
91
|
+
readonly metadata?: Record<string, unknown> | undefined;
|
|
72
92
|
}
|
|
73
93
|
|
|
74
94
|
/** What a transition did. */
|
|
75
95
|
export interface LifecycleTransition {
|
|
76
96
|
/** Whether the account moved. `false` when it was already where the call asked to put it. */
|
|
77
97
|
readonly changed: boolean;
|
|
98
|
+
/** Whether a lifecycle mail was enqueued for the account. False when the config, the call or a missing email capability sent none. */
|
|
99
|
+
readonly mailed: boolean;
|
|
78
100
|
}
|
|
79
101
|
|
|
80
|
-
/**
|
|
81
|
-
|
|
102
|
+
/** What a suspension did, and the suspension it left in force. */
|
|
103
|
+
export interface SuspendTransition extends LifecycleTransition {
|
|
104
|
+
/**
|
|
105
|
+
* True when the account was already suspended and this call restated the reason and the end instead (#621).
|
|
106
|
+
* That is not a transition — `changed` is false and no hook fires — but it is written, audited and mailed.
|
|
107
|
+
*/
|
|
108
|
+
readonly updated: boolean;
|
|
109
|
+
/** When the suspension in force began. A restatement keeps the original start. */
|
|
110
|
+
readonly suspendedAt: Date;
|
|
111
|
+
/** When it ends by itself, or null for one that lasts until a reinstatement. */
|
|
112
|
+
readonly suspendedUntil: Date | null;
|
|
113
|
+
}
|
|
82
114
|
|
|
83
115
|
/** A reason, trimmed and bounded, or null when none was given. */
|
|
84
116
|
function reasonOf(reason: string | null | undefined): string | null {
|
|
@@ -133,6 +165,12 @@ interface HistoryRow {
|
|
|
133
165
|
readonly at: Date;
|
|
134
166
|
readonly suspendedUntil?: Date | null;
|
|
135
167
|
readonly step?: string | null;
|
|
168
|
+
/** A hard deletion's choice for the purge's last mail; see `UserLifecycleEvent.notify`. */
|
|
169
|
+
readonly notify?: boolean | null;
|
|
170
|
+
/** A deletion's mode, kept for the erasure attestation (#823). */
|
|
171
|
+
readonly mode?: DeletionMode | null;
|
|
172
|
+
/** When a deletion's purge comes due, kept for the erasure attestation (#823). */
|
|
173
|
+
readonly purgeAfter?: Date | null;
|
|
136
174
|
}
|
|
137
175
|
|
|
138
176
|
/** The history row's values, as the table stores them. */
|
|
@@ -145,6 +183,9 @@ function encoded(row: HistoryRow) {
|
|
|
145
183
|
reason: row.reason,
|
|
146
184
|
suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
|
|
147
185
|
step: row.step ?? null,
|
|
186
|
+
notify: row.notify === undefined || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
|
|
187
|
+
mode: row.mode ?? null,
|
|
188
|
+
purgeAfter: row.purgeAfter ? SQLiteDate.encode(row.purgeAfter) : null,
|
|
148
189
|
createdAt: SQLiteDate.encode(row.at),
|
|
149
190
|
};
|
|
150
191
|
}
|
|
@@ -170,7 +211,19 @@ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, r
|
|
|
170
211
|
const v = encoded(row);
|
|
171
212
|
const insert = deps.db
|
|
172
213
|
.insertInto("pithyAuthUserLifecycle")
|
|
173
|
-
.columns([
|
|
214
|
+
.columns([
|
|
215
|
+
"userId",
|
|
216
|
+
"action",
|
|
217
|
+
"actorType",
|
|
218
|
+
"actorId",
|
|
219
|
+
"reason",
|
|
220
|
+
"suspendedUntil",
|
|
221
|
+
"step",
|
|
222
|
+
"notify",
|
|
223
|
+
"mode",
|
|
224
|
+
"purgeAfter",
|
|
225
|
+
"createdAt",
|
|
226
|
+
])
|
|
174
227
|
.expression(
|
|
175
228
|
deps.db
|
|
176
229
|
.selectNoFrom([
|
|
@@ -181,6 +234,9 @@ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, r
|
|
|
181
234
|
sql.val(v.reason).as("reason"),
|
|
182
235
|
sql.val(v.suspendedUntil).as("suspendedUntil"),
|
|
183
236
|
sql.val(v.step).as("step"),
|
|
237
|
+
sql.val(v.notify).as("notify"),
|
|
238
|
+
sql.val(v.mode).as("mode"),
|
|
239
|
+
sql.val(v.purgeAfter).as("purgeAfter"),
|
|
184
240
|
sql.val(v.createdAt).as("createdAt"),
|
|
185
241
|
])
|
|
186
242
|
.where(sql<number>`changes()`, ">", 0),
|
|
@@ -198,6 +254,7 @@ async function audit(
|
|
|
198
254
|
actor: LifecycleActor,
|
|
199
255
|
metadata: Record<string, unknown>,
|
|
200
256
|
): Promise<void> {
|
|
257
|
+
const context = deps.context;
|
|
201
258
|
const event: AuditEventInput = {
|
|
202
259
|
action,
|
|
203
260
|
outcome: "success",
|
|
@@ -205,7 +262,10 @@ async function audit(
|
|
|
205
262
|
actorId: actor.id,
|
|
206
263
|
resourceType: "user",
|
|
207
264
|
resourceId: userId,
|
|
208
|
-
|
|
265
|
+
...(context?.ip ? { ip: context.ip } : {}),
|
|
266
|
+
...(context?.userAgent ? { userAgent: context.userAgent } : {}),
|
|
267
|
+
...(context?.requestId ? { requestId: context.requestId } : {}),
|
|
268
|
+
metadata: { ...context?.metadata, ...metadata },
|
|
209
269
|
};
|
|
210
270
|
try {
|
|
211
271
|
await deps.emit(event);
|
|
@@ -214,7 +274,7 @@ async function audit(
|
|
|
214
274
|
}
|
|
215
275
|
}
|
|
216
276
|
|
|
217
|
-
/** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. */
|
|
277
|
+
/** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. Says whether it was enqueued. */
|
|
218
278
|
async function mail(
|
|
219
279
|
deps: LifecycleDeps,
|
|
220
280
|
enabled: boolean,
|
|
@@ -222,14 +282,16 @@ async function mail(
|
|
|
222
282
|
locale: string | null,
|
|
223
283
|
template: "accountSuspended" | "accountReinstated" | "deletionScheduled" | "deletionComplete",
|
|
224
284
|
payload: Record<string, unknown>,
|
|
225
|
-
): Promise<
|
|
226
|
-
if (!enabled || !deps.enqueueEmail) return;
|
|
285
|
+
): Promise<boolean> {
|
|
286
|
+
if (!enabled || !deps.enqueueEmail) return false;
|
|
227
287
|
try {
|
|
228
288
|
await deps.enqueueEmail({ to, template, payload, ...(locale ? { locale } : {}) });
|
|
289
|
+
return true;
|
|
229
290
|
} catch (error) {
|
|
230
291
|
deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, {
|
|
231
292
|
reason: messageOf(error),
|
|
232
293
|
});
|
|
294
|
+
return false;
|
|
233
295
|
}
|
|
234
296
|
}
|
|
235
297
|
|
|
@@ -257,16 +319,77 @@ function named(name: string): { name?: string } {
|
|
|
257
319
|
return name.trim() ? { name } : {};
|
|
258
320
|
}
|
|
259
321
|
|
|
322
|
+
/** The conflict for a deleted account: deletion outranks a suspension, so restore it first. */
|
|
323
|
+
function deletedConflict(restoreRoute: string | undefined, then: string): ConflictError {
|
|
324
|
+
return new ConflictError({
|
|
325
|
+
message: restoreRoute
|
|
326
|
+
? `This account is deleted. Restore it with ${restoreRoute} first.`
|
|
327
|
+
: "This account is deleted. Restore it first.",
|
|
328
|
+
action: restoreRoute ? `Restore it with ${restoreRoute}. ${then}` : `Restore it first. ${then}`,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** The conflict for a write that found the account moved under it by another request. Retrying is safe. */
|
|
333
|
+
function raced(userId: string): ConflictError {
|
|
334
|
+
return new ConflictError({
|
|
335
|
+
message: "The account changed while this request was being made. Send it again.",
|
|
336
|
+
detail: `lifecycle write for user ${userId} matched no row; another request moved the account first`,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch (#622).
|
|
342
|
+
*
|
|
343
|
+
* A restore and a purge's `due` check race for one account, and each has to see the window the other saw. A
|
|
344
|
+
* timestamp the restore took before its statement went out is stale by the time D1 runs it: the window can
|
|
345
|
+
* close in between, by itself or because a hard deletion brought it forward, and a purge whose `due` check ran
|
|
346
|
+
* in that gap goes on to erase an account the restore reported back. So on the system clock the guard is the
|
|
347
|
+
* database's own time, evaluated inside the statement, and D1 runs statements one at a time: whichever lands
|
|
348
|
+
* first, the other sees it. An injected clock is a test's, and is read afresh here, at the statement.
|
|
349
|
+
*/
|
|
350
|
+
function windowClock(deps: LifecycleDeps) {
|
|
351
|
+
return deps.now
|
|
352
|
+
? sql<number>`${deps.now().getTime()}`
|
|
353
|
+
: sql<number>`cast(round(unixepoch('subsec') * 1000) as integer)`;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The conflict for an account whose purge window has closed: nothing can restore it now. */
|
|
357
|
+
function windowClosed(userId: string, closes: Date): ConflictError {
|
|
358
|
+
return new ConflictError({
|
|
359
|
+
message: `This account's purge window closed on ${closes.toISOString()}. It can no longer be restored.`,
|
|
360
|
+
action: "The purge is due and erases its data once it runs. There is nothing to restore.",
|
|
361
|
+
detail: `restore for user ${userId}, whose purge was due at ${closes.toISOString()}`,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
260
365
|
/**
|
|
261
366
|
* Suspend an account, until `until` or until it is reinstated.
|
|
262
367
|
*
|
|
263
368
|
* A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
|
|
264
|
-
* conflict rather than a no-op
|
|
369
|
+
* conflict rather than a no-op, and names `restoreRoute` when the caller gives one. A suspension whose end has
|
|
370
|
+
* passed is not in force, and a new one replaces it.
|
|
371
|
+
*
|
|
372
|
+
* **An account already suspended has its terms restated (#621).** The reason and the end are replaced, a
|
|
373
|
+
* `suspended` row records the new reason — the newest one is what the person is shown — and the audit event
|
|
374
|
+
* and the mail say so. The start is kept, and no hook fires: the account was suspended and still is, so
|
|
375
|
+
* nothing transitioned. A fresh suspension that loses the race to another suspension finds the account
|
|
376
|
+
* suspended, so it retries once as a restatement rather than failing. A write that finds the account moved
|
|
377
|
+
* under it any other way, by a reinstatement or a deletion that landed first, is a conflict: what the caller
|
|
378
|
+
* asked for no longer describes the account.
|
|
379
|
+
*
|
|
380
|
+
* `notify: false` sends no mail, whatever the config says; the config can only turn mail off, never on.
|
|
265
381
|
*/
|
|
266
382
|
export async function suspendUser(
|
|
267
383
|
deps: LifecycleDeps,
|
|
268
|
-
input: {
|
|
269
|
-
|
|
384
|
+
input: {
|
|
385
|
+
userId: string;
|
|
386
|
+
actor: LifecycleActor;
|
|
387
|
+
reason: string | null;
|
|
388
|
+
until?: Date | null;
|
|
389
|
+
notify?: boolean;
|
|
390
|
+
restoreRoute?: string;
|
|
391
|
+
},
|
|
392
|
+
): Promise<SuspendTransition> {
|
|
270
393
|
const at = (deps.now ?? (() => new Date()))();
|
|
271
394
|
const reason = reasonOf(input.reason);
|
|
272
395
|
const until = input.until ?? null;
|
|
@@ -276,15 +399,21 @@ export async function suspendUser(
|
|
|
276
399
|
const subject = await subjectOf(deps.db, input.userId);
|
|
277
400
|
const standing = accountStanding(subject.columns, at);
|
|
278
401
|
if (standing.state === "deleted") {
|
|
279
|
-
throw
|
|
280
|
-
message: "This account is deleted.",
|
|
281
|
-
action: "Restore it first, if it should be suspended instead.",
|
|
282
|
-
});
|
|
402
|
+
throw deletedConflict(input.restoreRoute, "Then suspend it, if it should be suspended instead.");
|
|
283
403
|
}
|
|
284
|
-
|
|
285
|
-
|
|
404
|
+
const encodedUntil = until ? SQLiteDate.encode(until) : null;
|
|
405
|
+
/** 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. */
|
|
406
|
+
const restatement = (startedAt: Date) =>
|
|
407
|
+
deps.db
|
|
408
|
+
.updateTable("pithyAuthUsers")
|
|
409
|
+
.set({ suspendedUntil: encodedUntil })
|
|
410
|
+
.where("id", "=", input.userId)
|
|
411
|
+
.where("deletedAt", "is", null)
|
|
412
|
+
.where("suspendedAt", "=", SQLiteDate.encode(startedAt))
|
|
413
|
+
.where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
|
|
414
|
+
const fresh = deps.db
|
|
286
415
|
.updateTable("pithyAuthUsers")
|
|
287
|
-
.set({ suspendedAt: SQLiteDate.encode(at), suspendedUntil:
|
|
416
|
+
.set({ suspendedAt: SQLiteDate.encode(at), suspendedUntil: encodedUntil })
|
|
288
417
|
.where("id", "=", input.userId)
|
|
289
418
|
.where("deletedAt", "is", null)
|
|
290
419
|
.where((eb) =>
|
|
@@ -301,25 +430,47 @@ export async function suspendUser(
|
|
|
301
430
|
at,
|
|
302
431
|
suspendedUntil: until,
|
|
303
432
|
};
|
|
304
|
-
|
|
433
|
+
let updated = standing.state === "suspended";
|
|
434
|
+
let startedAt = updated && subject.columns.suspendedAt ? subject.columns.suspendedAt : at;
|
|
435
|
+
if (!(await move(deps, updated ? restatement(startedAt) : fresh, row))) {
|
|
436
|
+
// A fresh suspension that lost to another suspension landing first finds the account suspended, which
|
|
437
|
+
// is the case a restatement answers: retry once as one. Anything else — a deletion, or a restatement
|
|
438
|
+
// that lost to a reinstatement — means what the caller asked for no longer describes the account.
|
|
439
|
+
const now = updated ? null : await subjectOf(deps.db, input.userId);
|
|
440
|
+
const moved = now ? accountStanding(now.columns, at) : null;
|
|
441
|
+
if (!now?.columns.suspendedAt || moved?.state !== "suspended") throw raced(input.userId);
|
|
442
|
+
updated = true;
|
|
443
|
+
startedAt = now.columns.suspendedAt;
|
|
444
|
+
if (!(await move(deps, restatement(startedAt), row))) throw raced(input.userId);
|
|
445
|
+
}
|
|
305
446
|
|
|
306
447
|
await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
|
|
307
448
|
reason,
|
|
308
449
|
suspendedUntil: until?.toISOString() ?? null,
|
|
450
|
+
updated,
|
|
309
451
|
});
|
|
310
|
-
await mail(
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
452
|
+
const mailed = await mail(
|
|
453
|
+
deps,
|
|
454
|
+
deps.config.lifecycleEmails.accountSuspended && input.notify !== false,
|
|
455
|
+
subject.email,
|
|
456
|
+
subject.locale,
|
|
457
|
+
"accountSuspended",
|
|
458
|
+
{
|
|
459
|
+
...named(subject.name),
|
|
460
|
+
...(reason ? { reason } : {}),
|
|
461
|
+
...(until ? { until: readable(until, subject.locale) } : {}),
|
|
462
|
+
},
|
|
463
|
+
);
|
|
464
|
+
if (!updated) {
|
|
465
|
+
await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
|
|
466
|
+
userId: input.userId,
|
|
467
|
+
actor: input.actor,
|
|
468
|
+
reason,
|
|
469
|
+
at,
|
|
470
|
+
suspendedUntil: until,
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
return { changed: !updated, updated, mailed, suspendedAt: startedAt, suspendedUntil: until };
|
|
323
474
|
}
|
|
324
475
|
|
|
325
476
|
/**
|
|
@@ -329,22 +480,24 @@ export async function suspendUser(
|
|
|
329
480
|
* past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
|
|
330
481
|
* for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
|
|
331
482
|
* sign in again" to somebody every sign-in still refuses. Restore it first.
|
|
483
|
+
*
|
|
484
|
+
* `notify: false` sends no mail, on the same rule as `suspendUser`.
|
|
332
485
|
*/
|
|
333
486
|
export async function reinstateUser(
|
|
334
487
|
deps: LifecycleDeps,
|
|
335
|
-
input: { userId: string; actor: LifecycleActor; reason: string | null },
|
|
488
|
+
input: { userId: string; actor: LifecycleActor; reason: string | null; notify?: boolean; restoreRoute?: string },
|
|
336
489
|
): Promise<LifecycleTransition> {
|
|
337
490
|
const at = (deps.now ?? (() => new Date()))();
|
|
338
491
|
const reason = reasonOf(input.reason);
|
|
339
492
|
const subject = await subjectOf(deps.db, input.userId);
|
|
340
493
|
const standing = accountStanding(subject.columns, at);
|
|
341
494
|
if (standing.state === "deleted") {
|
|
342
|
-
throw
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
495
|
+
throw deletedConflict(
|
|
496
|
+
input.restoreRoute,
|
|
497
|
+
"Its suspension stays in place through a restore, and can be lifted after.",
|
|
498
|
+
);
|
|
346
499
|
}
|
|
347
|
-
if (standing.state !== "suspended") return { changed: false };
|
|
500
|
+
if (standing.state !== "suspended") return { changed: false, mailed: false };
|
|
348
501
|
const update = deps.db
|
|
349
502
|
.updateTable("pithyAuthUsers")
|
|
350
503
|
.set({ suspendedAt: null, suspendedUntil: null })
|
|
@@ -353,12 +506,12 @@ export async function reinstateUser(
|
|
|
353
506
|
.where("suspendedAt", "is not", null)
|
|
354
507
|
.where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
|
|
355
508
|
const row: HistoryRow = { userId: input.userId, action: "reinstated", actor: input.actor, reason, at };
|
|
356
|
-
if (!(await move(deps, update, row))) return { changed: false };
|
|
509
|
+
if (!(await move(deps, update, row))) return { changed: false, mailed: false };
|
|
357
510
|
|
|
358
511
|
await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
|
|
359
|
-
await mail(
|
|
512
|
+
const mailed = await mail(
|
|
360
513
|
deps,
|
|
361
|
-
deps.config.lifecycleEmails.accountReinstated,
|
|
514
|
+
deps.config.lifecycleEmails.accountReinstated && input.notify !== false,
|
|
362
515
|
subject.email,
|
|
363
516
|
subject.locale,
|
|
364
517
|
"accountReinstated",
|
|
@@ -370,44 +523,136 @@ export async function reinstateUser(
|
|
|
370
523
|
reason,
|
|
371
524
|
at,
|
|
372
525
|
});
|
|
373
|
-
return { changed: true };
|
|
526
|
+
return { changed: true, mailed };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** How a deletion runs: shut now and purged once the window closes, or purged now. */
|
|
530
|
+
export type DeletionMode = "soft" | "hard";
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* How many days a soft deletion stays restorable: the Worker's `retention.purgeWindows.user` when its block
|
|
534
|
+
* names one, else `retention.purgeAfterDays` from this capability's own config.
|
|
535
|
+
*/
|
|
536
|
+
export function userPurgeWindowDays(config: Pick<LifecycleDeps["config"], "retention">): number {
|
|
537
|
+
const retention = composedRetention();
|
|
538
|
+
return (retention && purgeWindowDays(retention, "user")) ?? config.retention.purgeAfterDays;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** What a deletion did, and the deletion it left in force. */
|
|
542
|
+
export interface DeleteTransition extends LifecycleTransition {
|
|
543
|
+
/**
|
|
544
|
+
* `deleted` when this call deleted an account in good standing; `brought_forward` when the account was
|
|
545
|
+
* already deleted and a hard deletion moved its purge to now; `unchanged` when it was already deleted and
|
|
546
|
+
* this call had nothing to move.
|
|
547
|
+
*/
|
|
548
|
+
readonly outcome: "deleted" | "brought_forward" | "unchanged";
|
|
549
|
+
/** When the account was deleted. A deletion brought forward keeps its original start. */
|
|
550
|
+
readonly deletedAt: Date;
|
|
551
|
+
/** When the purge may erase it — now, for a hard deletion. Restorable until then. */
|
|
552
|
+
readonly purgeAfter: Date;
|
|
374
553
|
}
|
|
375
554
|
|
|
376
555
|
/**
|
|
377
|
-
* Delete an account
|
|
378
|
-
*
|
|
556
|
+
* Delete an account. Audited as the account's own deletion when its holder is the actor.
|
|
557
|
+
*
|
|
558
|
+
* **Soft, the default**: it is shut now, and its data is erased once `retention.purgeAfterDays` have passed.
|
|
559
|
+
* Restorable until then. The deletion-scheduled mail carries the purge date and, when the config names one,
|
|
560
|
+
* the restore path. A deleted account deleted softly again is no transition.
|
|
561
|
+
*
|
|
562
|
+
* **Hard** (#622): `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
|
|
563
|
+
* caller starts the purge. No deletion-scheduled mail, because nothing is scheduled; the purge sends the
|
|
564
|
+
* deletion-complete one. An account already deleted softly has its purge brought forward to now, which is
|
|
565
|
+
* written and audited but fires no hook: the account was deleted and still is. One already due is unchanged.
|
|
379
566
|
*
|
|
380
567
|
* A suspension the account was under is left in place, so restoring the account does not lift it.
|
|
568
|
+
* `notify: false` sends no mail, whatever the config says.
|
|
381
569
|
*/
|
|
382
570
|
export async function deleteUser(
|
|
383
571
|
deps: LifecycleDeps,
|
|
384
|
-
input: { userId: string; actor: LifecycleActor; reason: string | null },
|
|
385
|
-
): Promise<
|
|
572
|
+
input: { userId: string; actor: LifecycleActor; reason: string | null; mode?: DeletionMode; notify?: boolean },
|
|
573
|
+
): Promise<DeleteTransition> {
|
|
386
574
|
const at = (deps.now ?? (() => new Date()))();
|
|
387
575
|
const reason = reasonOf(input.reason);
|
|
388
|
-
const
|
|
576
|
+
const hard = input.mode === "hard";
|
|
577
|
+
const purgeAfter = hard ? at : new Date(at.getTime() + userPurgeWindowDays(deps.config) * 86_400_000);
|
|
389
578
|
const subject = await subjectOf(deps.db, input.userId);
|
|
390
|
-
|
|
579
|
+
// A hard deletion's `notify` is the purge's to read, so it is written on the row: the purge that sends the last
|
|
580
|
+
// mail may be one the daily pass started, with no request to carry it (#622).
|
|
581
|
+
// The mode and the due instant ride on the row too, because the purge erases the account's own column and the
|
|
582
|
+
// erasure attestation still has to say both (#823).
|
|
583
|
+
const row: HistoryRow = {
|
|
584
|
+
userId: input.userId,
|
|
585
|
+
action: "deleted",
|
|
586
|
+
actor: input.actor,
|
|
587
|
+
reason,
|
|
588
|
+
at,
|
|
589
|
+
mode: hard ? "hard" : "soft",
|
|
590
|
+
purgeAfter,
|
|
591
|
+
...(hard && input.notify !== undefined ? { notify: input.notify } : {}),
|
|
592
|
+
};
|
|
593
|
+
const existing = subject.columns.deletedAt;
|
|
594
|
+
if (existing) {
|
|
595
|
+
const due = subject.columns.purgeAfter ?? existing;
|
|
596
|
+
const unchanged = {
|
|
597
|
+
changed: false,
|
|
598
|
+
mailed: false,
|
|
599
|
+
outcome: "unchanged",
|
|
600
|
+
deletedAt: existing,
|
|
601
|
+
purgeAfter: due,
|
|
602
|
+
} as const;
|
|
603
|
+
if (!hard || due.getTime() <= at.getTime()) return unchanged;
|
|
604
|
+
// Brought forward: the same deletion, with its window closed now. Pinned by its start, so a restore and a
|
|
605
|
+
// fresh deletion in between is a different deletion and this write matches nothing.
|
|
606
|
+
const forward = deps.db
|
|
607
|
+
.updateTable("pithyAuthUsers")
|
|
608
|
+
.set({ purgeAfter: SQLiteDate.encode(at) })
|
|
609
|
+
.where("id", "=", input.userId)
|
|
610
|
+
.where("deletedAt", "=", SQLiteDate.encode(existing))
|
|
611
|
+
.where("purgeAfter", ">", SQLiteDate.encode(at));
|
|
612
|
+
if (!(await move(deps, forward, row))) return unchanged;
|
|
613
|
+
await audit(deps, AuthAuditActions.adminUserHardDeleted, input.userId, input.actor, {
|
|
614
|
+
reason,
|
|
615
|
+
purgeAfter: at.toISOString(),
|
|
616
|
+
broughtForward: true,
|
|
617
|
+
});
|
|
618
|
+
return { changed: false, mailed: false, outcome: "brought_forward", deletedAt: existing, purgeAfter: at };
|
|
619
|
+
}
|
|
391
620
|
const update = deps.db
|
|
392
621
|
.updateTable("pithyAuthUsers")
|
|
393
622
|
.set({ deletedAt: SQLiteDate.encode(at), purgeAfter: SQLiteDate.encode(purgeAfter) })
|
|
394
623
|
.where("id", "=", input.userId)
|
|
395
624
|
.where("deletedAt", "is", null);
|
|
396
|
-
|
|
397
|
-
|
|
625
|
+
if (!(await move(deps, update, row))) {
|
|
626
|
+
// Another deletion landed first. The account is where this call asked to put it, so it is no transition;
|
|
627
|
+
// anything else moved it is a conflict, and a retry reads it afresh.
|
|
628
|
+
const now = await subjectOf(deps.db, input.userId);
|
|
629
|
+
if (!now.columns.deletedAt) throw raced(input.userId);
|
|
630
|
+
const due = now.columns.purgeAfter ?? now.columns.deletedAt;
|
|
631
|
+
return { changed: false, mailed: false, outcome: "unchanged", deletedAt: now.columns.deletedAt, purgeAfter: due };
|
|
632
|
+
}
|
|
398
633
|
|
|
399
634
|
const self = input.actor.type === "user" && input.actor.id === input.userId;
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
635
|
+
const action = hard
|
|
636
|
+
? AuthAuditActions.adminUserHardDeleted
|
|
637
|
+
: self
|
|
638
|
+
? AuthAuditActions.userSelfDeleted
|
|
639
|
+
: AuthAuditActions.adminUserSoftDeleted;
|
|
640
|
+
await audit(deps, action, input.userId, input.actor, { reason, purgeAfter: purgeAfter.toISOString() });
|
|
641
|
+
const restoreUrl = deps.config.retention.restoreUrl;
|
|
642
|
+
const mailed = hard
|
|
643
|
+
? false
|
|
644
|
+
: await mail(
|
|
645
|
+
deps,
|
|
646
|
+
deps.config.lifecycleEmails.deletionScheduled && input.notify !== false,
|
|
647
|
+
subject.email,
|
|
648
|
+
subject.locale,
|
|
649
|
+
"deletionScheduled",
|
|
650
|
+
{
|
|
651
|
+
...named(subject.name),
|
|
652
|
+
purgeOn: readable(purgeAfter, subject.locale),
|
|
653
|
+
...(restoreUrl ? { restoreUrl } : {}),
|
|
654
|
+
},
|
|
655
|
+
);
|
|
411
656
|
await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
|
|
412
657
|
userId: input.userId,
|
|
413
658
|
actor: input.actor,
|
|
@@ -415,69 +660,283 @@ export async function deleteUser(
|
|
|
415
660
|
at,
|
|
416
661
|
purgeAfter,
|
|
417
662
|
});
|
|
418
|
-
return { changed: true };
|
|
663
|
+
return { changed: true, mailed, outcome: "deleted", deletedAt: at, purgeAfter };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** What a restoration did, and where it left the account. */
|
|
667
|
+
export interface RestoreTransition extends LifecycleTransition {
|
|
668
|
+
/** Where the account stands now: `active`, or `suspended` when a suspension it was under is still in force. */
|
|
669
|
+
readonly state: "active" | "suspended";
|
|
419
670
|
}
|
|
420
671
|
|
|
421
672
|
/**
|
|
422
|
-
* Restore a deleted account inside its purge window.
|
|
423
|
-
*
|
|
673
|
+
* Restore a deleted account inside its purge window.
|
|
674
|
+
*
|
|
675
|
+
* **Only inside it.** Once `purgeAfter` has passed the purge is due, may already be running, and erases each
|
|
676
|
+
* capability's rows in turn, so restoring then would hand back an account with some of its data gone. That
|
|
677
|
+
* is a conflict naming the date the window closed. After the purge there is no account at all, and that is a
|
|
678
|
+
* 404 whose action says the data is gone — read off the history row the purge leaves behind, so it is told
|
|
679
|
+
* apart from an id that never existed.
|
|
680
|
+
*
|
|
681
|
+
* An account that is not deleted is no transition. A suspension it was under is still in force after.
|
|
424
682
|
*/
|
|
425
683
|
export async function restoreUser(
|
|
426
684
|
deps: LifecycleDeps,
|
|
427
685
|
input: { userId: string; actor: LifecycleActor; reason: string | null },
|
|
428
|
-
): Promise<
|
|
686
|
+
): Promise<RestoreTransition> {
|
|
429
687
|
const at = (deps.now ?? (() => new Date()))();
|
|
430
688
|
const reason = reasonOf(input.reason);
|
|
431
|
-
const subject = await subjectOf(deps.db, input.userId)
|
|
432
|
-
|
|
689
|
+
const subject = await subjectOf(deps.db, input.userId).catch(async (error: unknown) => {
|
|
690
|
+
throw (await purgedRefusal(deps.db, input.userId)) ?? error;
|
|
691
|
+
});
|
|
692
|
+
const suspended = (columns: LifecycleColumns) =>
|
|
693
|
+
accountStanding({ ...columns, deletedAt: null, purgeAfter: null }, at).state === "suspended";
|
|
694
|
+
const state = suspended(subject.columns) ? "suspended" : "active";
|
|
695
|
+
if (!subject.columns.deletedAt) return { changed: false, mailed: false, state };
|
|
696
|
+
// Early, and only ever early: `at` was read before the account was, so a window it finds closed is closed. One
|
|
697
|
+
// it finds open may not be by the time the update runs, which is why the update guards on its own clock.
|
|
698
|
+
const closes = subject.columns.purgeAfter;
|
|
699
|
+
if (closes && closes.getTime() <= at.getTime()) throw windowClosed(input.userId, closes);
|
|
433
700
|
const update = deps.db
|
|
434
701
|
.updateTable("pithyAuthUsers")
|
|
435
702
|
.set({ deletedAt: null, purgeAfter: null })
|
|
436
703
|
.where("id", "=", input.userId)
|
|
437
|
-
.where("deletedAt", "is not", null)
|
|
704
|
+
.where("deletedAt", "is not", null)
|
|
705
|
+
.where("purgeAfter", ">", windowClock(deps));
|
|
438
706
|
const row: HistoryRow = { userId: input.userId, action: "restored", actor: input.actor, reason, at };
|
|
439
|
-
if (!(await move(deps, update, row)))
|
|
707
|
+
if (!(await move(deps, update, row))) {
|
|
708
|
+
// Another restoration landed first: no transition. A window that closed while this one was in flight — by
|
|
709
|
+
// itself, or brought forward by a hard deletion — is the conflict above. Anything else a retry reads afresh.
|
|
710
|
+
const now = await subjectOf(deps.db, input.userId).catch(async (error: unknown) => {
|
|
711
|
+
throw (await purgedRefusal(deps.db, input.userId)) ?? error;
|
|
712
|
+
});
|
|
713
|
+
if (!now.columns.deletedAt) {
|
|
714
|
+
return { changed: false, mailed: false, state: suspended(now.columns) ? "suspended" : "active" };
|
|
715
|
+
}
|
|
716
|
+
// Read afresh: a window still open now means something else moved the account — a restore and a new
|
|
717
|
+
// deletion both landed in between — and that is the retry's to read.
|
|
718
|
+
const closed = now.columns.purgeAfter;
|
|
719
|
+
if (closed && closed.getTime() <= (deps.now ?? (() => new Date()))().getTime()) {
|
|
720
|
+
throw windowClosed(input.userId, closed);
|
|
721
|
+
}
|
|
722
|
+
throw raced(input.userId);
|
|
723
|
+
}
|
|
440
724
|
|
|
441
725
|
await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
|
|
442
|
-
return { changed: true };
|
|
726
|
+
return { changed: true, mailed: false, state };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* The refusal for an account the purge has erased, or `null` when none was. A 404, because there is no
|
|
731
|
+
* account, with the date in the action so an operator answering a restore request knows it is final.
|
|
732
|
+
*/
|
|
733
|
+
async function purgedRefusal(db: AuthDatabase, userId: string): Promise<NotFoundError | null> {
|
|
734
|
+
const purged = await db
|
|
735
|
+
.selectFrom("pithyAuthUserLifecycle")
|
|
736
|
+
.select("createdAt")
|
|
737
|
+
.where("userId", "=", userId)
|
|
738
|
+
.where("action", "=", "purged")
|
|
739
|
+
.orderBy("id", "desc")
|
|
740
|
+
.executeTakeFirst();
|
|
741
|
+
if (!purged) return null;
|
|
742
|
+
const on = SQLiteDate.parse(purged.createdAt).toISOString();
|
|
743
|
+
return new NotFoundError({
|
|
744
|
+
message: "No such account.",
|
|
745
|
+
action: `This account was purged on ${on}. Its data is gone, and there is nothing to restore or export.`,
|
|
746
|
+
detail: `user ${userId} was purged at ${on}`,
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* The account's row, or the refusal for one that is not there — the 404 that says the data is gone when the
|
|
752
|
+
* purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
|
|
753
|
+
* export.
|
|
754
|
+
*/
|
|
755
|
+
export async function requirePresent(db: AuthDatabase, userId: string): Promise<void> {
|
|
756
|
+
const row = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", userId).executeTakeFirst();
|
|
757
|
+
if (row) return;
|
|
758
|
+
throw (
|
|
759
|
+
(await purgedRefusal(db, userId)) ??
|
|
760
|
+
new NotFoundError({ message: "No such user.", detail: `no pithy_auth_users row for ${userId}` })
|
|
761
|
+
);
|
|
443
762
|
}
|
|
444
763
|
|
|
445
764
|
/** The purge's own actor: a scheduled job, with nobody calling. */
|
|
446
765
|
const PURGE: LifecycleActor = { type: "system", id: null };
|
|
447
766
|
|
|
448
|
-
/**
|
|
449
|
-
export
|
|
450
|
-
|
|
451
|
-
|
|
767
|
+
/** Who the purge's last mail goes to, captured before any step erases the address. */
|
|
768
|
+
export interface PurgeRecipient {
|
|
769
|
+
readonly email: string;
|
|
770
|
+
readonly name: string | null;
|
|
771
|
+
readonly locale: string | null;
|
|
452
772
|
}
|
|
453
773
|
|
|
454
774
|
/**
|
|
455
|
-
*
|
|
775
|
+
* Whether one account is due for its purge, who its last mail goes to, and whether it goes (#622).
|
|
456
776
|
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
459
|
-
*
|
|
777
|
+
* `due` only for an account that is deleted and whose `purgeAfter` has passed — the cron and a hard deletion
|
|
778
|
+
* both start a purge, and this is the one check either passes through, so an account restored in between is
|
|
779
|
+
* `not_due` and nothing is erased. `gone` when there is no row: the purge already erased it, or the id never
|
|
780
|
+
* existed, and either way there is nothing to do. The recipient is read here, before the first step, because
|
|
781
|
+
* the last step erases it.
|
|
782
|
+
*
|
|
783
|
+
* `notify` is what the deletion in force asked of the last mail — its newest `deleted` row's — so a hard
|
|
784
|
+
* deletion's `notify: false` holds for a purge the daily pass started, which was handed no such parameter.
|
|
460
785
|
*/
|
|
461
|
-
export async function
|
|
786
|
+
export async function purgeSubject(
|
|
462
787
|
deps: LifecycleDeps,
|
|
463
|
-
|
|
788
|
+
userId: string,
|
|
789
|
+
): Promise<
|
|
790
|
+
{ state: "due"; recipient: PurgeRecipient; notify: boolean | null } | { state: "not_due" } | { state: "gone" }
|
|
791
|
+
> {
|
|
792
|
+
// The instant is the database's, read in the same statement as the row — the clock `restoreUser` guards on, so
|
|
793
|
+
// a restore and this check agree on whether the window has closed, whichever runs first (#622).
|
|
794
|
+
const row = await deps.db
|
|
795
|
+
.selectFrom("pithyAuthUsers")
|
|
796
|
+
.select(["email", "name", "locale", "suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
|
|
797
|
+
.select(windowClock(deps).as("checkedAt"))
|
|
798
|
+
.where("id", "=", userId)
|
|
799
|
+
.executeTakeFirst();
|
|
800
|
+
if (!row) return { state: "gone" };
|
|
801
|
+
const columns = LifecycleColumns.parse(row);
|
|
802
|
+
if (!columns.deletedAt || !columns.purgeAfter || columns.purgeAfter.getTime() > Number(row.checkedAt)) {
|
|
803
|
+
return { state: "not_due" };
|
|
804
|
+
}
|
|
805
|
+
const deletion = await deps.db
|
|
806
|
+
.selectFrom("pithyAuthUserLifecycle")
|
|
807
|
+
.select("notify")
|
|
808
|
+
.where("userId", "=", userId)
|
|
809
|
+
.where("action", "=", "deleted")
|
|
810
|
+
.orderBy("id", "desc")
|
|
811
|
+
.limit(1)
|
|
812
|
+
.executeTakeFirst();
|
|
813
|
+
const saved = deletion?.notify;
|
|
814
|
+
const notify = saved === undefined || saved === null ? null : SQLiteBoolean.decode(saved);
|
|
815
|
+
return { state: "due", recipient: { email: row.email, name: row.name, locale: row.locale ?? null }, notify };
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* The account's address, as a purge step reads it (#814) — `null` when there is no account, or no address. Read
|
|
820
|
+
* inside the step that asks, so it is never carried in a Workflow's journal.
|
|
821
|
+
*/
|
|
822
|
+
export async function purgeAddress(db: AuthDatabase, userId: string): Promise<string | null> {
|
|
823
|
+
const row = await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst();
|
|
824
|
+
return row?.email ?? null;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** One account whose purge is due: which, and the deletion it is due under — ms-epoch, so a Workflow journal holds it. */
|
|
828
|
+
export interface DuePurge {
|
|
829
|
+
readonly userId: string;
|
|
830
|
+
readonly deletedAt: number;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
|
|
835
|
+
* What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
|
|
836
|
+
* that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
|
|
837
|
+
*/
|
|
838
|
+
export async function duePurges(deps: LifecycleDeps, limit: number): Promise<DuePurge[]> {
|
|
839
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
840
|
+
const rows = await deps.db
|
|
841
|
+
.selectFrom("pithyAuthUsers")
|
|
842
|
+
.select(["id", "deletedAt"])
|
|
843
|
+
.where("deletedAt", "is not", null)
|
|
844
|
+
.where("purgeAfter", "is not", null)
|
|
845
|
+
.where("purgeAfter", "<=", SQLiteDate.encode(at))
|
|
846
|
+
.orderBy("purgeAfter", "asc")
|
|
847
|
+
.orderBy("id", "asc")
|
|
848
|
+
.limit(limit)
|
|
849
|
+
.execute();
|
|
850
|
+
return rows.map((row) => ({ userId: row.id, deletedAt: Number(row.deletedAt) }));
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
|
|
855
|
+
* the row's reason, so the history says what the step erased and not only that it ran. With `retained`, the step
|
|
856
|
+
* kept its rows instead (#814): the row is `purge_retained`, and its reason is the basis the capability gave.
|
|
857
|
+
*/
|
|
858
|
+
export async function recordPurgeStep(
|
|
859
|
+
deps: LifecycleDeps,
|
|
860
|
+
input: { userId: string; step: string; summary?: string | null; retained?: boolean },
|
|
861
|
+
): Promise<void> {
|
|
862
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
863
|
+
await record(deps, {
|
|
864
|
+
userId: input.userId,
|
|
865
|
+
// A retained step kept its rows (#814): its own action, so the trail never reads a kept step as an erased one.
|
|
866
|
+
action: input.retained ? "purge_retained" : "purge_step",
|
|
867
|
+
actor: PURGE,
|
|
868
|
+
reason: input.summary?.trim() ? input.summary.trim().slice(0, MAX_REASON) : null,
|
|
869
|
+
at,
|
|
870
|
+
step: input.step,
|
|
871
|
+
});
|
|
872
|
+
// The trail's record of the step, which the erasure attestation cites by id and chain position (#823). The step's
|
|
873
|
+
// name and disposition only: the summary is the row's, and the trail never holds anything about the person.
|
|
874
|
+
await audit(deps, AuthAuditActions.adminUserPurgeStep, input.userId, PURGE, {
|
|
875
|
+
step: input.step,
|
|
876
|
+
disposition: input.retained ? "retained" : "erased",
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* Record that a purge gave up (#823): the step it stopped at, in the history and in the trail. The daily pass starts
|
|
882
|
+
* the purge again tomorrow, so this is where it stands until then, not an end. The failure's message is never
|
|
883
|
+
* written: it is code the kit did not write, and it may name the person.
|
|
884
|
+
*/
|
|
885
|
+
export async function recordPurgeFailure(deps: LifecycleDeps, input: { userId: string; step: string }): Promise<void> {
|
|
886
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
887
|
+
await record(deps, {
|
|
888
|
+
userId: input.userId,
|
|
889
|
+
action: "purge_failed",
|
|
890
|
+
actor: PURGE,
|
|
891
|
+
reason: null,
|
|
892
|
+
at,
|
|
893
|
+
step: input.step,
|
|
894
|
+
});
|
|
895
|
+
await audit(deps, AuthAuditActions.adminUserPurgeFailed, input.userId, PURGE, { step: input.step });
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
|
|
900
|
+
* other capability's rows are gone and before auth's own, which holds the address, so the last mail is
|
|
901
|
+
* enqueued while there is still an account to have sent it to. The address is handed in, captured before the
|
|
902
|
+
* first step. `notify: false` sends nothing, whatever the config says.
|
|
903
|
+
*/
|
|
904
|
+
export async function mailPurgeComplete(
|
|
905
|
+
deps: LifecycleDeps,
|
|
906
|
+
input: { recipient: PurgeRecipient; notify?: boolean },
|
|
464
907
|
): Promise<LifecycleTransition> {
|
|
465
908
|
const at = (deps.now ?? (() => new Date()))();
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
.
|
|
470
|
-
|
|
909
|
+
const { email, name, locale } = input.recipient;
|
|
910
|
+
const mailed = await mail(
|
|
911
|
+
deps,
|
|
912
|
+
deps.config.lifecycleEmails.deletionComplete && input.notify !== false,
|
|
913
|
+
email,
|
|
914
|
+
locale,
|
|
915
|
+
"deletionComplete",
|
|
916
|
+
{ ...named(name ?? ""), purgedOn: readable(at, locale) },
|
|
917
|
+
);
|
|
918
|
+
return { changed: false, mailed };
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* Finish a purge: the record, the audit event, the hook. The last thing that happens to the account.
|
|
923
|
+
*
|
|
924
|
+
* By the time a purge finishes the user row is gone, so this reads nothing about the account. Finishing a
|
|
925
|
+
* purge that already finished is a no-op, so a retried Workflow step records and fires once — and so do two
|
|
926
|
+
* purges of one account that overlapped. **The insert is the check**: `0005_purge_once` allows one `purged` row
|
|
927
|
+
* per account, the insert ignores a second, and only the call whose row landed audits and fires. A read
|
|
928
|
+
* before the insert would let two concurrent calls both find nothing and both write.
|
|
929
|
+
*/
|
|
930
|
+
export async function completePurge(deps: LifecycleDeps, input: { userId: string }): Promise<LifecycleTransition> {
|
|
931
|
+
const at = (deps.now ?? (() => new Date()))();
|
|
932
|
+
const inserted = await deps.db
|
|
933
|
+
.insertInto("pithyAuthUserLifecycle")
|
|
934
|
+
.values(encoded({ userId: input.userId, action: "purged", actor: PURGE, reason: null, at }))
|
|
935
|
+
.onConflict((conflict) => conflict.doNothing())
|
|
471
936
|
.executeTakeFirst();
|
|
472
|
-
if (
|
|
937
|
+
if (Number(inserted.numInsertedOrUpdatedRows ?? 0n) === 0) return { changed: false, mailed: false };
|
|
473
938
|
|
|
474
|
-
await record(deps, { userId: input.userId, action: "purged", actor: PURGE, reason: null, at });
|
|
475
939
|
await audit(deps, AuthAuditActions.adminUserPurged, input.userId, PURGE, {});
|
|
476
|
-
const { email, name, locale } = input.recipient;
|
|
477
|
-
await mail(deps, deps.config.lifecycleEmails.deletionComplete, email, locale, "deletionComplete", {
|
|
478
|
-
...named(name ?? ""),
|
|
479
|
-
purgedOn: readable(at, locale),
|
|
480
|
-
});
|
|
481
940
|
await fire(deps, "onUserPurged", deps.hooks.onUserPurged, { userId: input.userId, actor: PURGE, reason: null, at });
|
|
482
|
-
return { changed: true };
|
|
941
|
+
return { changed: true, mailed: false };
|
|
483
942
|
}
|