@powerhousedao/reactor-privacy 6.2.3-dev.35
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/LICENSE +661 -0
- package/README.md +87 -0
- package/dist/index.d.ts +483 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1573 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1573 @@
|
|
|
1
|
+
import { BaseReadModel, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, DEFAULT_MAX_PURGE_OPERATIONS, DocumentNotDeletedError, DriveCollectionId, JobStatus, KyselyDocumentPurger, PURGE_LOCK_BUCKETS, PURGE_NS, REACTOR_SCHEMA, ReactorEventTypes, appliedDelete, defaultReadModelIndexingConfig, findPurged, isPurgeMarker, supportsDeliveryTracking, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
|
|
2
|
+
import { Migrator, sql } from "kysely";
|
|
3
|
+
import { createHmac } from "node:crypto";
|
|
4
|
+
import { groupDocumentType, groupMembershipActionTypes, isDocumentCreator } from "@powerhousedao/shared/document-model";
|
|
5
|
+
import { gql } from "graphql-tag";
|
|
6
|
+
import { GraphQLError } from "graphql";
|
|
7
|
+
//#region src/schema/migrations/0001_erasure_requests.ts
|
|
8
|
+
async function up$1(db, schema) {
|
|
9
|
+
await db.schema.createTable("erasure_requests").ifNotExists().addColumn("requestId", "text", (col) => col.primaryKey()).addColumn("subjectHash", "text").addColumn("requestedBy", "text", (col) => col.notNull()).addColumn("requestedAt", "timestamptz", (col) => col.notNull()).addColumn("deadline", "timestamptz", (col) => col.notNull()).addColumn("status", "text", (col) => col.notNull()).execute();
|
|
10
|
+
await db.schema.createTable("erasure_items").ifNotExists().addColumn("requestId", "text", (col) => col.notNull().references("erasure_requests.requestId")).addColumn("documentId", "text", (col) => col.notNull()).addColumn("status", "text", (col) => col.notNull()).addColumn("allowLarge", "boolean", (col) => col.notNull().defaultTo(false)).addColumn("markerOrdinal", "bigint").addColumn("lastError", "text").addColumn("updatedAt", "timestamptz", (col) => col.notNull()).addPrimaryKeyConstraint("erasure_items_pkey", ["requestId", "documentId"]).execute();
|
|
11
|
+
await db.schema.createTable("erasure_audit").ifNotExists().addColumn("ordinal", "bigserial", (col) => col.primaryKey()).addColumn("requestId", "text", (col) => col.notNull()).addColumn("documentId", "text").addColumn("event", "text", (col) => col.notNull()).addColumn("detail", "jsonb").addColumn("atUtc", "timestamptz", (col) => col.notNull()).execute();
|
|
12
|
+
await db.schema.createIndex("idx_erasure_audit_request").ifNotExists().on("erasure_audit").column("requestId").execute();
|
|
13
|
+
await sql`
|
|
14
|
+
create or replace function ${sql.id(schema, "erasure_audit_append_only")}()
|
|
15
|
+
returns trigger
|
|
16
|
+
language plpgsql as $$
|
|
17
|
+
begin
|
|
18
|
+
raise exception 'erasure_audit is append-only';
|
|
19
|
+
end $$
|
|
20
|
+
`.execute(db);
|
|
21
|
+
await sql`
|
|
22
|
+
create trigger erasure_audit_no_update
|
|
23
|
+
before update on ${sql.id(schema, "erasure_audit")}
|
|
24
|
+
for each row execute function ${sql.id(schema, "erasure_audit_append_only")}()
|
|
25
|
+
`.execute(db);
|
|
26
|
+
}
|
|
27
|
+
async function down$1(db, schema) {
|
|
28
|
+
await db.schema.dropTable("erasure_audit").execute();
|
|
29
|
+
await sql`drop function if exists ${sql.id(schema, "erasure_audit_append_only")}()`.execute(db);
|
|
30
|
+
await db.schema.dropTable("erasure_items").execute();
|
|
31
|
+
await db.schema.dropTable("erasure_requests").execute();
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/schema/migrations/0002_subject_documents.ts
|
|
35
|
+
async function up(db) {
|
|
36
|
+
await db.schema.createTable("subject_documents").ifNotExists().addColumn("subjectHash", "text", (col) => col.notNull()).addColumn("documentId", "text", (col) => col.notNull()).addColumn("role", "text", (col) => col.notNull()).addColumn("firstOrdinal", "bigint", (col) => col.notNull()).addColumn("lastOrdinal", "bigint", (col) => col.notNull()).addPrimaryKeyConstraint("subject_documents_pkey", [
|
|
37
|
+
"subjectHash",
|
|
38
|
+
"documentId",
|
|
39
|
+
"role"
|
|
40
|
+
]).execute();
|
|
41
|
+
await db.schema.createIndex("idx_subject_documents_document").ifNotExists().on("subject_documents").column("documentId").execute();
|
|
42
|
+
}
|
|
43
|
+
async function down(db) {
|
|
44
|
+
await db.schema.dropTable("subject_documents").execute();
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/schema/migrations/migrator.ts
|
|
48
|
+
const REACTOR_PRIVACY_MIGRATION_TABLE = "kysely_migration_reactor_privacy";
|
|
49
|
+
const REACTOR_PRIVACY_MIGRATION_LOCK_TABLE = "kysely_migration_reactor_privacy_lock";
|
|
50
|
+
/** Raw statements (the audit trigger) need the schema named. */
|
|
51
|
+
function migrationsFor(schema) {
|
|
52
|
+
return {
|
|
53
|
+
"0001_erasure_requests": {
|
|
54
|
+
up: (db) => up$1(db, schema),
|
|
55
|
+
down: (db) => down$1(db, schema)
|
|
56
|
+
},
|
|
57
|
+
"0002_subject_documents": {
|
|
58
|
+
up: (db) => up(db),
|
|
59
|
+
down: (db) => down(db)
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
var ProgrammaticMigrationProvider = class {
|
|
64
|
+
schema;
|
|
65
|
+
constructor(schema) {
|
|
66
|
+
this.schema = schema;
|
|
67
|
+
}
|
|
68
|
+
getMigrations() {
|
|
69
|
+
return Promise.resolve(migrationsFor(this.schema));
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
function migratorFor(db, schema) {
|
|
73
|
+
return new Migrator({
|
|
74
|
+
db: db.withSchema(schema),
|
|
75
|
+
provider: new ProgrammaticMigrationProvider(schema),
|
|
76
|
+
migrationTableSchema: schema,
|
|
77
|
+
migrationTableName: REACTOR_PRIVACY_MIGRATION_TABLE,
|
|
78
|
+
migrationLockTableName: REACTOR_PRIVACY_MIGRATION_LOCK_TABLE
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async function runReactorPrivacyMigrations(db, schema = REACTOR_SCHEMA) {
|
|
82
|
+
try {
|
|
83
|
+
await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
return {
|
|
86
|
+
success: false,
|
|
87
|
+
migrationsExecuted: [],
|
|
88
|
+
error: error instanceof Error ? error : /* @__PURE__ */ new Error("Failed to create schema")
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
let error;
|
|
92
|
+
let results;
|
|
93
|
+
try {
|
|
94
|
+
const result = await migratorFor(db, schema).migrateToLatest();
|
|
95
|
+
error = result.error;
|
|
96
|
+
results = result.results;
|
|
97
|
+
} catch (e) {
|
|
98
|
+
error = e;
|
|
99
|
+
results = [];
|
|
100
|
+
}
|
|
101
|
+
const migrationsExecuted = results?.map((result) => result.migrationName) ?? [];
|
|
102
|
+
if (error) return {
|
|
103
|
+
success: false,
|
|
104
|
+
migrationsExecuted,
|
|
105
|
+
error: error instanceof Error ? error : /* @__PURE__ */ new Error("Unknown migration error")
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
success: true,
|
|
109
|
+
migrationsExecuted
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
async function getReactorPrivacyMigrationStatus(db, schema = REACTOR_SCHEMA) {
|
|
113
|
+
return await migratorFor(db, schema).getMigrations();
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/subject-hash.ts
|
|
117
|
+
/** Shorter keys make the HMAC guessable along with the address. */
|
|
118
|
+
const MIN_DEPLOYMENT_SECRET_BYTES = 32;
|
|
119
|
+
var DeploymentSecretError = class extends Error {
|
|
120
|
+
constructor() {
|
|
121
|
+
super(`The privacy deployment secret must be at least 32 bytes`);
|
|
122
|
+
this.name = "DeploymentSecretError";
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
function assertDeploymentSecret(secret) {
|
|
126
|
+
if ((typeof secret === "string" ? Buffer.byteLength(secret, "utf8") : secret.byteLength) < 32) throw new DeploymentSecretError();
|
|
127
|
+
}
|
|
128
|
+
/** HMAC-SHA256(secret, lower(identifier)), hex. */
|
|
129
|
+
function subjectHash(secret, identifier) {
|
|
130
|
+
return createHmac("sha256", secret).update(identifier.toLowerCase(), "utf8").digest("hex");
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/read-model/subjects.ts
|
|
134
|
+
const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
135
|
+
const ETH_ADDRESS = /^0x[0-9a-f]{40}$/i;
|
|
136
|
+
const DID_KEY = /^did:key:z[1-9A-HJ-NP-Za-km-z]+$/;
|
|
137
|
+
/** A condition literal counts as an identifier only in these two shapes. */
|
|
138
|
+
function isAddressLiteral(value) {
|
|
139
|
+
return typeof value === "string" && (ETH_ADDRESS.test(value) || DID_KEY.test(value));
|
|
140
|
+
}
|
|
141
|
+
function base58Encode(bytes) {
|
|
142
|
+
const digits = [0];
|
|
143
|
+
for (const byte of bytes) {
|
|
144
|
+
let carry = byte;
|
|
145
|
+
for (let i = 0; i < digits.length; i++) {
|
|
146
|
+
carry += digits[i] << 8;
|
|
147
|
+
digits[i] = carry % 58;
|
|
148
|
+
carry = Math.floor(carry / 58);
|
|
149
|
+
}
|
|
150
|
+
while (carry > 0) {
|
|
151
|
+
digits.push(carry % 58);
|
|
152
|
+
carry = Math.floor(carry / 58);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
let out = "";
|
|
156
|
+
for (let k = 0; k < bytes.length && bytes[k] === 0; k++) out += "1";
|
|
157
|
+
for (let i = digits.length - 1; i >= 0; i--) out += BASE58[digits[i]];
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
function base64UrlDecode(value) {
|
|
161
|
+
try {
|
|
162
|
+
return new Uint8Array(Buffer.from(value, "base64url"));
|
|
163
|
+
} catch {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** The did:key of a P-256 JWK, the form an app key takes; else undefined. */
|
|
168
|
+
function jwkToDidKey(jwk) {
|
|
169
|
+
if (typeof jwk !== "object" || jwk === null) return void 0;
|
|
170
|
+
const { kty, crv, x, y } = jwk;
|
|
171
|
+
if (kty !== "EC" || crv !== "P-256") return void 0;
|
|
172
|
+
if (typeof x !== "string" || typeof y !== "string") return void 0;
|
|
173
|
+
const xBytes = base64UrlDecode(x);
|
|
174
|
+
const yBytes = base64UrlDecode(y);
|
|
175
|
+
if (xBytes?.length !== 32 || yBytes?.length !== 32) return void 0;
|
|
176
|
+
const compressed = /* @__PURE__ */ new Uint8Array(35);
|
|
177
|
+
compressed[0] = 128;
|
|
178
|
+
compressed[1] = 36;
|
|
179
|
+
compressed[2] = (yBytes[31] & 1) === 1 ? 3 : 2;
|
|
180
|
+
compressed.set(xBytes, 3);
|
|
181
|
+
return `did:key:z${base58Encode(compressed)}`;
|
|
182
|
+
}
|
|
183
|
+
function operandLiterals(operand, out) {
|
|
184
|
+
if (operand === void 0 || typeof operand !== "object") return;
|
|
185
|
+
if ("lit" in operand && isAddressLiteral(operand.lit)) out.push(operand.lit);
|
|
186
|
+
}
|
|
187
|
+
function conditionLiterals(condition, out) {
|
|
188
|
+
if (typeof condition !== "object" || condition === null) return;
|
|
189
|
+
const c = condition;
|
|
190
|
+
for (const key of [
|
|
191
|
+
"eq",
|
|
192
|
+
"ne",
|
|
193
|
+
"lt",
|
|
194
|
+
"lte",
|
|
195
|
+
"gt",
|
|
196
|
+
"gte"
|
|
197
|
+
]) {
|
|
198
|
+
const pair = c[key];
|
|
199
|
+
if (Array.isArray(pair)) for (const operand of pair) operandLiterals(operand, out);
|
|
200
|
+
}
|
|
201
|
+
for (const key of ["in", "notIn"]) {
|
|
202
|
+
const pair = c[key];
|
|
203
|
+
if (!Array.isArray(pair)) continue;
|
|
204
|
+
operandLiterals(pair[0], out);
|
|
205
|
+
if (Array.isArray(pair[1])) for (const operand of pair[1]) operandLiterals(operand, out);
|
|
206
|
+
}
|
|
207
|
+
if ("exists" in c) operandLiterals(c.exists, out);
|
|
208
|
+
for (const key of ["and", "or"]) {
|
|
209
|
+
const list = c[key];
|
|
210
|
+
if (Array.isArray(list)) for (const inner of list) conditionLiterals(inner, out);
|
|
211
|
+
}
|
|
212
|
+
if ("not" in c) conditionLiterals(c.not, out);
|
|
213
|
+
}
|
|
214
|
+
function grantMentions(grant, out) {
|
|
215
|
+
if (typeof grant !== "object" || grant === null) return;
|
|
216
|
+
const { principal, where } = grant;
|
|
217
|
+
if (typeof principal === "object" && principal !== null) {
|
|
218
|
+
const { address, match } = principal;
|
|
219
|
+
if (typeof address === "string" && address !== "") out.push(address);
|
|
220
|
+
conditionLiterals(match, out);
|
|
221
|
+
}
|
|
222
|
+
conditionLiterals(where, out);
|
|
223
|
+
}
|
|
224
|
+
/** Identifiers named in an action's input, by the spec's three sources. */
|
|
225
|
+
function namedIn({ operation, context }) {
|
|
226
|
+
const { type, input } = operation.action;
|
|
227
|
+
const out = [];
|
|
228
|
+
if (typeof input !== "object" || input === null) return out;
|
|
229
|
+
const record = input;
|
|
230
|
+
if (type === "INITIALIZE_AUTH" && Array.isArray(record.grants)) for (const grant of record.grants) grantMentions(grant, out);
|
|
231
|
+
else if (type === "SET_GRANT") grantMentions(record.grant, out);
|
|
232
|
+
else if (context.documentType === groupDocumentType && groupMembershipActionTypes.includes(type) && typeof record.address === "string" && record.address !== "") out.push(record.address);
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
/** Every mention an operation carries, except `creator` (needs the header). */
|
|
236
|
+
function mentionsOf(item) {
|
|
237
|
+
const mentions = [];
|
|
238
|
+
const signer = item.operation.action.context?.signer;
|
|
239
|
+
const address = signer?.user?.address;
|
|
240
|
+
if (typeof address === "string" && address !== "") mentions.push({
|
|
241
|
+
identifier: address,
|
|
242
|
+
role: "signer"
|
|
243
|
+
});
|
|
244
|
+
const appKey = signer?.app?.key;
|
|
245
|
+
if (typeof appKey === "string" && appKey !== "") mentions.push({
|
|
246
|
+
identifier: appKey,
|
|
247
|
+
role: "app-key"
|
|
248
|
+
});
|
|
249
|
+
if (item.operation.action.type === "CREATE_DOCUMENT") {
|
|
250
|
+
const signing = item.operation.action.input?.signing;
|
|
251
|
+
const headerKey = jwkToDidKey(signing?.publicKey);
|
|
252
|
+
if (headerKey !== void 0) mentions.push({
|
|
253
|
+
identifier: headerKey,
|
|
254
|
+
role: "header-key"
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
for (const identifier of namedIn(item)) mentions.push({
|
|
258
|
+
identifier,
|
|
259
|
+
role: "named"
|
|
260
|
+
});
|
|
261
|
+
return mentions;
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
264
|
+
//#region src/read-model/subject-documents-read-model.ts
|
|
265
|
+
const SUBJECT_DOCUMENTS_READ_MODEL_ID = "subject-documents-read-model";
|
|
266
|
+
function hasHeaderKey(jwk) {
|
|
267
|
+
return Boolean(jwk && (jwk.kty || jwk.x || jwk.y));
|
|
268
|
+
}
|
|
269
|
+
/** Keyed hash of each identifier an operation carries, to its document. */
|
|
270
|
+
var SubjectDocumentsReadModel = class extends BaseReadModel {
|
|
271
|
+
deploymentSecret;
|
|
272
|
+
static commitsInFenceTransaction = true;
|
|
273
|
+
constructor(db, operationIndex, writeCache, consistencyTracker, deploymentSecret) {
|
|
274
|
+
assertDeploymentSecret(deploymentSecret);
|
|
275
|
+
super(db, operationIndex, writeCache, consistencyTracker, {
|
|
276
|
+
readModelId: SUBJECT_DOCUMENTS_READ_MODEL_ID,
|
|
277
|
+
rebuildStateOnInit: false,
|
|
278
|
+
indexing: defaultReadModelIndexingConfig,
|
|
279
|
+
replayStreamSuffix: false,
|
|
280
|
+
purgeFence: "locked"
|
|
281
|
+
});
|
|
282
|
+
this.deploymentSecret = deploymentSecret;
|
|
283
|
+
}
|
|
284
|
+
async commitOperations(items, trx) {
|
|
285
|
+
if (items.length === 0) return;
|
|
286
|
+
const db = trx ?? this.db;
|
|
287
|
+
const purged = /* @__PURE__ */ new Set();
|
|
288
|
+
for (const item of items) if (isPurgeMarker(item.operation)) purged.add(item.context.documentId);
|
|
289
|
+
const rows = /* @__PURE__ */ new Map();
|
|
290
|
+
const add = (item, identifier, role) => {
|
|
291
|
+
const hash = subjectHash(this.deploymentSecret, identifier);
|
|
292
|
+
const { documentId, ordinal } = item.context;
|
|
293
|
+
const key = `${hash}\u0000${documentId}\u0000${role}`;
|
|
294
|
+
const row = rows.get(key);
|
|
295
|
+
if (row === void 0) {
|
|
296
|
+
rows.set(key, {
|
|
297
|
+
subjectHash: hash,
|
|
298
|
+
documentId,
|
|
299
|
+
role,
|
|
300
|
+
firstOrdinal: ordinal,
|
|
301
|
+
lastOrdinal: ordinal
|
|
302
|
+
});
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
row.firstOrdinal = Math.min(row.firstOrdinal, ordinal);
|
|
306
|
+
row.lastOrdinal = Math.max(row.lastOrdinal, ordinal);
|
|
307
|
+
};
|
|
308
|
+
for (const item of items) {
|
|
309
|
+
const { documentId } = item.context;
|
|
310
|
+
if (isPurgeMarker(item.operation) || purged.has(documentId)) continue;
|
|
311
|
+
for (const { identifier, role } of mentionsOf(item)) add(item, identifier, role);
|
|
312
|
+
const creator = await this.creatorOf(db, item);
|
|
313
|
+
if (creator !== void 0) add(item, creator, "creator");
|
|
314
|
+
}
|
|
315
|
+
if (purged.size > 0) await db.deleteFrom("subject_documents").where("documentId", "in", [...purged]).execute();
|
|
316
|
+
if (rows.size === 0) return;
|
|
317
|
+
await db.insertInto("subject_documents").values([...rows.values()]).onConflict((oc) => oc.columns([
|
|
318
|
+
"subjectHash",
|
|
319
|
+
"documentId",
|
|
320
|
+
"role"
|
|
321
|
+
]).doUpdateSet({
|
|
322
|
+
firstOrdinal: sql`least(subject_documents."firstOrdinal", excluded."firstOrdinal")`,
|
|
323
|
+
lastOrdinal: sql`greatest(subject_documents."lastOrdinal", excluded."lastOrdinal")`
|
|
324
|
+
})).execute();
|
|
325
|
+
}
|
|
326
|
+
/** The auth scope's creator, as the INITIALIZE_AUTH reducer derives it. */
|
|
327
|
+
async creatorOf(db, { operation, context }) {
|
|
328
|
+
if (operation.action.type !== "INITIALIZE_AUTH") return void 0;
|
|
329
|
+
if (operation.error !== void 0) return void 0;
|
|
330
|
+
const appKey = (operation.action.context?.signer)?.app?.key;
|
|
331
|
+
if (typeof appKey !== "string" || appKey === "") return void 0;
|
|
332
|
+
const headerKey = (((await db.selectFrom("Operation").select("action").where("documentId", "=", context.documentId).where("scope", "=", "document").where("branch", "=", context.branch).where("index", "=", 0).executeTakeFirst())?.action)?.input)?.signing?.publicKey;
|
|
333
|
+
if (!hasHeaderKey(headerKey)) return void 0;
|
|
334
|
+
return isDocumentCreator(headerKey, appKey) ? appKey : void 0;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
//#endregion
|
|
338
|
+
//#region src/read-model/register.ts
|
|
339
|
+
var LiveReadModelRegistrationError = class extends Error {
|
|
340
|
+
constructor() {
|
|
341
|
+
super("The reactor's read model coordinator cannot add a read model after build");
|
|
342
|
+
this.name = "LiveReadModelRegistrationError";
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
/** Post-build registration on the host thread, as switchboard's add-ons do. */
|
|
346
|
+
async function registerSubjectDocumentsReadModel(reactorModule, options) {
|
|
347
|
+
const coordinator = reactorModule.readModelCoordinator;
|
|
348
|
+
if (!supportsLiveReadModelRegistration(coordinator)) throw new LiveReadModelRegistrationError();
|
|
349
|
+
const base = reactorModule.database;
|
|
350
|
+
const migrated = await runReactorPrivacyMigrations(base, REACTOR_SCHEMA);
|
|
351
|
+
if (!migrated.success) throw migrated.error ?? /* @__PURE__ */ new Error("reactor-privacy migrations failed");
|
|
352
|
+
const readModel = new SubjectDocumentsReadModel(base.withSchema(REACTOR_SCHEMA), reactorModule.operationIndex, reactorModule.writeCache, new ConsistencyTracker(), options.deploymentSecret);
|
|
353
|
+
await readModel.init();
|
|
354
|
+
coordinator.addReadModel(readModel, "pre_ready");
|
|
355
|
+
await readModel.init();
|
|
356
|
+
return readModel;
|
|
357
|
+
}
|
|
358
|
+
//#endregion
|
|
359
|
+
//#region src/erasure/documents.ts
|
|
360
|
+
async function documentFacts(db, ids) {
|
|
361
|
+
const facts = /* @__PURE__ */ new Map();
|
|
362
|
+
if (ids.length === 0) return facts;
|
|
363
|
+
const purged = await findPurged(db, ids);
|
|
364
|
+
const streams = await db.selectFrom("Operation").select([
|
|
365
|
+
"documentId",
|
|
366
|
+
"branch",
|
|
367
|
+
"documentType"
|
|
368
|
+
]).select(sql`bool_or(${appliedDelete})`.as("deleted")).where(sql`"documentId" = any(${ids}::text[])`).where("scope", "=", "document").groupBy([
|
|
369
|
+
"documentId",
|
|
370
|
+
"branch",
|
|
371
|
+
"documentType"
|
|
372
|
+
]).execute();
|
|
373
|
+
for (const id of ids) {
|
|
374
|
+
const own = streams.filter((row) => row.documentId === id);
|
|
375
|
+
facts.set(id, {
|
|
376
|
+
documentId: id,
|
|
377
|
+
documentType: own[0]?.documentType ?? null,
|
|
378
|
+
purged: purged.has(id),
|
|
379
|
+
deleted: own.length > 0 && own.every((row) => Boolean(row.deleted)),
|
|
380
|
+
branches: [...new Set(own.map((row) => row.branch))]
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
return facts;
|
|
384
|
+
}
|
|
385
|
+
/** A drive's members its purge needs gone, less those already tombstoned. */
|
|
386
|
+
async function driveMembers(db, driveId, branches) {
|
|
387
|
+
const purger = new KyselyDocumentPurger(db);
|
|
388
|
+
const members = /* @__PURE__ */ new Set();
|
|
389
|
+
for (const branch of branches.length > 0 ? branches : ["main"]) {
|
|
390
|
+
const collectionId = DriveCollectionId.forDrive(driveId, branch).key;
|
|
391
|
+
for (const member of await purger.collectionMembers(collectionId, driveId, branch)) if (member.required) members.add(member.documentId);
|
|
392
|
+
}
|
|
393
|
+
const purged = await findPurged(db, members);
|
|
394
|
+
return [...members].filter((id) => !purged.has(id)).sort();
|
|
395
|
+
}
|
|
396
|
+
/** The requested ids, then each drive's members; first mention wins. */
|
|
397
|
+
async function expandIds(db, ids, driveTypes) {
|
|
398
|
+
const requested = [...new Set(ids)];
|
|
399
|
+
const facts = await documentFacts(db, requested);
|
|
400
|
+
const expanded = requested.map((documentId) => ({
|
|
401
|
+
documentId,
|
|
402
|
+
expandedFrom: null
|
|
403
|
+
}));
|
|
404
|
+
const seen = new Set(requested);
|
|
405
|
+
for (const id of requested) {
|
|
406
|
+
const fact = facts.get(id);
|
|
407
|
+
if (fact.purged || !driveTypes.has(fact.documentType ?? "")) continue;
|
|
408
|
+
for (const member of await driveMembers(db, id, fact.branches)) {
|
|
409
|
+
if (seen.has(member)) continue;
|
|
410
|
+
seen.add(member);
|
|
411
|
+
expanded.push({
|
|
412
|
+
documentId: member,
|
|
413
|
+
expandedFrom: id
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const missing = expanded.map((item) => item.documentId).filter((id) => !facts.has(id));
|
|
418
|
+
for (const [id, fact] of await documentFacts(db, missing)) facts.set(id, fact);
|
|
419
|
+
return {
|
|
420
|
+
expanded,
|
|
421
|
+
facts
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
async function operationCount(db, documentId) {
|
|
425
|
+
return new KyselyDocumentPurger(db).operationCount(documentId);
|
|
426
|
+
}
|
|
427
|
+
async function groupReferencers(db, groupId) {
|
|
428
|
+
return new KyselyDocumentPurger(db).groupReferencersInHistory(groupId);
|
|
429
|
+
}
|
|
430
|
+
//#endregion
|
|
431
|
+
//#region src/erasure/redact.ts
|
|
432
|
+
const IDENTIFIERS = /0x[0-9a-fA-F]{40}|did:key:z[1-9A-HJ-NP-Za-km-z]+/g;
|
|
433
|
+
/** Names of errors whose message embeds a caller identity of any shape. */
|
|
434
|
+
const IDENTITY_ERRORS = /* @__PURE__ */ new Set(["AuthorizationDeniedError"]);
|
|
435
|
+
/** The keyed-hash form an identifier takes in the audit and item rows. */
|
|
436
|
+
function hashedIdentifier(secret, identifier) {
|
|
437
|
+
return `hmac:${subjectHash(secret, identifier)}`;
|
|
438
|
+
}
|
|
439
|
+
/** Stored form of requestedBy: hashed when it is an address. */
|
|
440
|
+
function storedRequester(secret, requestedBy) {
|
|
441
|
+
return isAddressLiteral(requestedBy) ? hashedIdentifier(secret, requestedBy) : redactText(secret, requestedBy);
|
|
442
|
+
}
|
|
443
|
+
function redactText(secret, text) {
|
|
444
|
+
return text.replace(IDENTIFIERS, (match) => hashedIdentifier(secret, match));
|
|
445
|
+
}
|
|
446
|
+
/** An error as the audit may hold it: its name, and a message with no address. */
|
|
447
|
+
function redactError(secret, error) {
|
|
448
|
+
const name = error.name ?? "Error";
|
|
449
|
+
const message = error.message ?? "";
|
|
450
|
+
if (IDENTITY_ERRORS.has(name)) return {
|
|
451
|
+
name,
|
|
452
|
+
message: hashedIdentifier(secret, message)
|
|
453
|
+
};
|
|
454
|
+
return {
|
|
455
|
+
name,
|
|
456
|
+
message: redactText(secret, message)
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
/** Every string in `value`, keys included, with identifiers hashed. */
|
|
460
|
+
function redactDetail(secret, value) {
|
|
461
|
+
if (typeof value === "string") return redactText(secret, value);
|
|
462
|
+
if (Array.isArray(value)) return value.map((v) => redactDetail(secret, v));
|
|
463
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, v]) => [redactText(secret, key), redactDetail(secret, v)]));
|
|
464
|
+
return value;
|
|
465
|
+
}
|
|
466
|
+
//#endregion
|
|
467
|
+
//#region src/erasure/ledger.ts
|
|
468
|
+
/** Appends one audit row; every string in `detail` is redacted first. */
|
|
469
|
+
async function appendAudit(db, secret, entry) {
|
|
470
|
+
const detail = entry.detail === void 0 ? null : JSON.stringify(redactDetail(secret, entry.detail));
|
|
471
|
+
await db.insertInto("erasure_audit").values({
|
|
472
|
+
requestId: entry.requestId,
|
|
473
|
+
documentId: entry.documentId,
|
|
474
|
+
event: entry.event,
|
|
475
|
+
detail: detail === null ? null : sql`${detail}::jsonb`,
|
|
476
|
+
atUtc: entry.at
|
|
477
|
+
}).execute();
|
|
478
|
+
}
|
|
479
|
+
async function auditOf(db, requestId, documentId, events) {
|
|
480
|
+
let query = db.selectFrom("erasure_audit").select([
|
|
481
|
+
"event",
|
|
482
|
+
"detail",
|
|
483
|
+
"atUtc"
|
|
484
|
+
]).where("requestId", "=", requestId).where("event", "in", events).orderBy("ordinal");
|
|
485
|
+
query = documentId === null ? query.where("documentId", "is", null) : query.where("documentId", "=", documentId);
|
|
486
|
+
return query.execute();
|
|
487
|
+
}
|
|
488
|
+
//#endregion
|
|
489
|
+
//#region src/erasure/erasure-service.ts
|
|
490
|
+
const DEFAULT_ERASURE_DEADLINE_MS = 2592e6;
|
|
491
|
+
var ErasureRequestNotFoundError = class extends Error {
|
|
492
|
+
requestId;
|
|
493
|
+
constructor(requestId) {
|
|
494
|
+
super(`No erasure request ${requestId}`);
|
|
495
|
+
this.requestId = requestId;
|
|
496
|
+
this.name = "ErasureRequestNotFoundError";
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
function isLive(fact) {
|
|
500
|
+
return !fact || !fact.purged && !fact.deleted;
|
|
501
|
+
}
|
|
502
|
+
var ErasureService = class {
|
|
503
|
+
db;
|
|
504
|
+
secret;
|
|
505
|
+
maxPurgeOperations;
|
|
506
|
+
driveTypes;
|
|
507
|
+
deadlineMs;
|
|
508
|
+
now;
|
|
509
|
+
newRequestId;
|
|
510
|
+
constructor(options) {
|
|
511
|
+
assertDeploymentSecret(options.deploymentSecret);
|
|
512
|
+
this.db = options.db;
|
|
513
|
+
this.secret = options.deploymentSecret;
|
|
514
|
+
this.maxPurgeOperations = options.maxPurgeOperations ?? DEFAULT_MAX_PURGE_OPERATIONS;
|
|
515
|
+
this.driveTypes = new Set(options.driveContainerTypes ?? DEFAULT_DRIVE_CONTAINER_TYPES);
|
|
516
|
+
this.deadlineMs = options.deadlineMs ?? 2592e6;
|
|
517
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
518
|
+
this.newRequestId = options.newRequestId ?? (() => crypto.randomUUID());
|
|
519
|
+
}
|
|
520
|
+
async plan(ids) {
|
|
521
|
+
const { expanded, facts } = await expandIds(this.db, ids, this.driveTypes);
|
|
522
|
+
const items = [];
|
|
523
|
+
for (const { documentId, expandedFrom } of expanded) {
|
|
524
|
+
const fact = facts.get(documentId);
|
|
525
|
+
items.push({
|
|
526
|
+
documentId,
|
|
527
|
+
expandedFrom,
|
|
528
|
+
live: isLive(fact),
|
|
529
|
+
operationCount: await operationCount(this.db, documentId),
|
|
530
|
+
groupReferencers: fact?.purged ? [] : await groupReferencers(this.db, documentId)
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
return {
|
|
534
|
+
maxPurgeOperations: this.maxPurgeOperations,
|
|
535
|
+
items
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
async request(ids, opts) {
|
|
539
|
+
if (ids.length === 0) throw new Error("An erasure request names no ids");
|
|
540
|
+
const { expanded, facts } = await expandIds(this.db, ids, this.driveTypes);
|
|
541
|
+
const live = expanded.map((item) => item.documentId).filter((id) => isLive(facts.get(id)));
|
|
542
|
+
if (live.length > 0) throw new DocumentNotDeletedError(live[0], `Delete these documents before requesting their erasure: ${live.join(", ")}`);
|
|
543
|
+
const requestId = this.newRequestId();
|
|
544
|
+
const requestedAt = this.now();
|
|
545
|
+
const deadline = opts.deadline ?? new Date(requestedAt.getTime() + this.deadlineMs);
|
|
546
|
+
const allowLarge = new Set(opts.allowLarge ?? []);
|
|
547
|
+
const drives = /* @__PURE__ */ new Map();
|
|
548
|
+
for (const { documentId, expandedFrom } of expanded) {
|
|
549
|
+
if (expandedFrom === null) continue;
|
|
550
|
+
drives.set(expandedFrom, [...drives.get(expandedFrom) ?? [], documentId]);
|
|
551
|
+
}
|
|
552
|
+
await this.db.transaction().execute(async (trx) => {
|
|
553
|
+
await trx.insertInto("erasure_requests").values({
|
|
554
|
+
requestId,
|
|
555
|
+
subjectHash: null,
|
|
556
|
+
requestedBy: storedRequester(this.secret, opts.requestedBy),
|
|
557
|
+
requestedAt,
|
|
558
|
+
deadline,
|
|
559
|
+
status: "open"
|
|
560
|
+
}).execute();
|
|
561
|
+
await trx.insertInto("erasure_items").values(expanded.map(({ documentId }) => ({
|
|
562
|
+
requestId,
|
|
563
|
+
documentId,
|
|
564
|
+
status: "waiting",
|
|
565
|
+
allowLarge: allowLarge.has(documentId),
|
|
566
|
+
markerOrdinal: null,
|
|
567
|
+
lastError: null,
|
|
568
|
+
updatedAt: requestedAt
|
|
569
|
+
}))).execute();
|
|
570
|
+
await appendAudit(trx, this.secret, {
|
|
571
|
+
requestId,
|
|
572
|
+
documentId: null,
|
|
573
|
+
event: "requested",
|
|
574
|
+
detail: {
|
|
575
|
+
ids: [...new Set(ids)],
|
|
576
|
+
allowLarge: [...allowLarge],
|
|
577
|
+
deadline: deadline.toISOString()
|
|
578
|
+
},
|
|
579
|
+
at: requestedAt
|
|
580
|
+
});
|
|
581
|
+
for (const [driveId, members] of drives) await appendAudit(trx, this.secret, {
|
|
582
|
+
requestId,
|
|
583
|
+
documentId: driveId,
|
|
584
|
+
event: "expanded",
|
|
585
|
+
detail: { members },
|
|
586
|
+
at: requestedAt
|
|
587
|
+
});
|
|
588
|
+
});
|
|
589
|
+
return this.status(requestId);
|
|
590
|
+
}
|
|
591
|
+
async status(requestId) {
|
|
592
|
+
const request = await this.db.selectFrom("erasure_requests").selectAll().where("requestId", "=", requestId).executeTakeFirst();
|
|
593
|
+
if (!request) throw new ErasureRequestNotFoundError(requestId);
|
|
594
|
+
const items = await this.db.selectFrom("erasure_items").selectAll().where("requestId", "=", requestId).orderBy("documentId").execute();
|
|
595
|
+
return {
|
|
596
|
+
requestId: request.requestId,
|
|
597
|
+
subjectHash: request.subjectHash,
|
|
598
|
+
requestedBy: request.requestedBy,
|
|
599
|
+
requestedAt: new Date(request.requestedAt),
|
|
600
|
+
deadline: new Date(request.deadline),
|
|
601
|
+
status: request.status,
|
|
602
|
+
items: items.map((item) => ({
|
|
603
|
+
documentId: item.documentId,
|
|
604
|
+
status: item.status,
|
|
605
|
+
allowLarge: item.allowLarge,
|
|
606
|
+
markerOrdinal: item.markerOrdinal === null ? null : Number(item.markerOrdinal),
|
|
607
|
+
lastError: item.lastError,
|
|
608
|
+
updatedAt: new Date(item.updatedAt)
|
|
609
|
+
}))
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
//#endregion
|
|
614
|
+
//#region src/erasure/scheduler.ts
|
|
615
|
+
const DEFAULT_ERASURE_INTERVAL_MS = 6e4;
|
|
616
|
+
const DEFAULT_MARKER_GRACE_MS = 6048e5;
|
|
617
|
+
const DEFAULT_PURGE_TIMEOUT_MS = 9e5;
|
|
618
|
+
/** An unsigned marker is refused by every receiver. */
|
|
619
|
+
var ErasureSignerMissingError = class extends Error {
|
|
620
|
+
constructor() {
|
|
621
|
+
super("The erasure scheduler needs the reactor's signer: without one every receiver refuses its purge markers");
|
|
622
|
+
this.name = "ErasureSignerMissingError";
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
const SILENT = {
|
|
626
|
+
info() {},
|
|
627
|
+
warn() {},
|
|
628
|
+
error() {}
|
|
629
|
+
};
|
|
630
|
+
function keyOf(item) {
|
|
631
|
+
return `${item.requestId}\u0000${item.documentId}`;
|
|
632
|
+
}
|
|
633
|
+
function canonical(value) {
|
|
634
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
635
|
+
if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
636
|
+
return JSON.stringify(value);
|
|
637
|
+
}
|
|
638
|
+
function kindOf(detail) {
|
|
639
|
+
return detail?.kind;
|
|
640
|
+
}
|
|
641
|
+
function messageOf(error) {
|
|
642
|
+
return error instanceof Error ? error.message : String(error);
|
|
643
|
+
}
|
|
644
|
+
function byName(a, b) {
|
|
645
|
+
return a.remote < b.remote ? -1 : a.remote > b.remote ? 1 : 0;
|
|
646
|
+
}
|
|
647
|
+
function tombstoneOf(row) {
|
|
648
|
+
return {
|
|
649
|
+
ordinal: Number(row.ordinal),
|
|
650
|
+
removedRows: row.removedRows,
|
|
651
|
+
purgedAtUtc: new Date(row.purgedAtUtc)
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
/** One purge at a time across all requests; document_purges is the truth. */
|
|
655
|
+
var ErasureScheduler = class {
|
|
656
|
+
db;
|
|
657
|
+
secret;
|
|
658
|
+
options;
|
|
659
|
+
driveTypes;
|
|
660
|
+
intervalMs;
|
|
661
|
+
markerGraceMs;
|
|
662
|
+
purgeTimeoutMs;
|
|
663
|
+
now;
|
|
664
|
+
logger;
|
|
665
|
+
/** Purge job per item; lost on restart like the job tracker's own entries. */
|
|
666
|
+
jobIds = /* @__PURE__ */ new Map();
|
|
667
|
+
/** Failed or abandoned purges whose transaction may still be open. */
|
|
668
|
+
unsettled = /* @__PURE__ */ new Set();
|
|
669
|
+
documentTypes = /* @__PURE__ */ new Map();
|
|
670
|
+
timer;
|
|
671
|
+
unsubscribes = [];
|
|
672
|
+
running;
|
|
673
|
+
runningPass;
|
|
674
|
+
queued;
|
|
675
|
+
/** Items the last full pass found ready, in purge order, not yet enqueued. */
|
|
676
|
+
ready = [];
|
|
677
|
+
constructor(options) {
|
|
678
|
+
if (!options.signer?.app?.key) throw new ErasureSignerMissingError();
|
|
679
|
+
assertDeploymentSecret(options.deploymentSecret);
|
|
680
|
+
this.options = options;
|
|
681
|
+
this.db = options.db;
|
|
682
|
+
this.secret = options.deploymentSecret;
|
|
683
|
+
this.driveTypes = new Set(options.driveContainerTypes ?? DEFAULT_DRIVE_CONTAINER_TYPES);
|
|
684
|
+
this.intervalMs = options.intervalMs ?? 6e4;
|
|
685
|
+
this.markerGraceMs = options.markerGraceMs ?? 6048e5;
|
|
686
|
+
this.purgeTimeoutMs = options.purgeTimeoutMs ?? 9e5;
|
|
687
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
688
|
+
this.logger = options.logger ?? SILENT;
|
|
689
|
+
}
|
|
690
|
+
start() {
|
|
691
|
+
if (this.timer) return;
|
|
692
|
+
const bus = this.options.eventBus;
|
|
693
|
+
if (bus) {
|
|
694
|
+
const onJob = (_type, event) => {
|
|
695
|
+
if ([...this.jobIds.values()].includes(event.jobId)) this.trigger("dispatch");
|
|
696
|
+
};
|
|
697
|
+
this.unsubscribes = [bus.subscribe(ReactorEventTypes.JOB_WRITE_READY, onJob), bus.subscribe(ReactorEventTypes.JOB_FAILED, onJob)];
|
|
698
|
+
}
|
|
699
|
+
this.timer = setInterval(() => this.trigger("full"), this.intervalMs);
|
|
700
|
+
this.timer.unref();
|
|
701
|
+
this.logger.info(`Erasure scheduler started (tick ${this.intervalMs}ms)`);
|
|
702
|
+
}
|
|
703
|
+
/** Stops the interval and the triggers, and waits for the tick in flight. */
|
|
704
|
+
async stop() {
|
|
705
|
+
if (this.timer) clearInterval(this.timer);
|
|
706
|
+
this.timer = void 0;
|
|
707
|
+
for (const unsubscribe of this.unsubscribes) unsubscribe();
|
|
708
|
+
this.unsubscribes = [];
|
|
709
|
+
this.queued = void 0;
|
|
710
|
+
await this.running;
|
|
711
|
+
}
|
|
712
|
+
/** One full pass; joins a full pass in flight, follows a dispatch pass. */
|
|
713
|
+
tick() {
|
|
714
|
+
if (this.running && this.runningPass === "dispatch") {
|
|
715
|
+
const next = () => this.tick();
|
|
716
|
+
return this.running.then(next, next);
|
|
717
|
+
}
|
|
718
|
+
return this.pass("full");
|
|
719
|
+
}
|
|
720
|
+
pass(kind) {
|
|
721
|
+
if (this.running) return this.running;
|
|
722
|
+
this.runningPass = kind;
|
|
723
|
+
const run = kind === "full" ? this.runTick() : this.runDispatch();
|
|
724
|
+
this.running = run.finally(() => {
|
|
725
|
+
this.running = void 0;
|
|
726
|
+
this.runningPass = void 0;
|
|
727
|
+
const next = this.queued;
|
|
728
|
+
this.queued = void 0;
|
|
729
|
+
if (next) this.trigger(next);
|
|
730
|
+
});
|
|
731
|
+
return this.running;
|
|
732
|
+
}
|
|
733
|
+
/** A pass now, or right after the one running; inert unless started. */
|
|
734
|
+
trigger(kind) {
|
|
735
|
+
if (!this.timer) return;
|
|
736
|
+
if (this.running) {
|
|
737
|
+
if (this.queued !== "full") this.queued = kind;
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
this.pass(kind).catch((error) => {
|
|
741
|
+
this.logger.error("Erasure tick failed: @error", redactText(this.secret, messageOf(error)));
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
async runTick() {
|
|
745
|
+
await this.recoverFailed();
|
|
746
|
+
await this.reopenRequests();
|
|
747
|
+
const items = await this.activeItems();
|
|
748
|
+
const reads = await this.tickReads(items);
|
|
749
|
+
for (const item of items.filter((i) => i.status === "purging")) await this.guarded(item, () => this.advancePurging(item, reads));
|
|
750
|
+
for (const item of items.filter((i) => i.status === "purged")) await this.guarded(item, () => this.advancePurged(item, reads));
|
|
751
|
+
await this.advanceWaiting(items, reads);
|
|
752
|
+
await this.settleRequests();
|
|
753
|
+
}
|
|
754
|
+
/** After a purge settles: that item, then the next ready one; no backlog scan. */
|
|
755
|
+
async runDispatch() {
|
|
756
|
+
const purging = await this.activeItems({ statuses: ["purging"] });
|
|
757
|
+
const reads = await this.tickReads(purging);
|
|
758
|
+
for (const item of purging) await this.guarded(item, () => this.advancePurging(item, reads));
|
|
759
|
+
for (const item of purging.filter((i) => i.status === "purged")) await this.guarded(item, () => this.advancePurged(item, reads));
|
|
760
|
+
if (!purging.some((i) => i.status === "purging")) await this.dispatchReady();
|
|
761
|
+
const requests = [...new Set(purging.map((i) => i.requestId))];
|
|
762
|
+
if (requests.length > 0) await this.settleRequests(requests);
|
|
763
|
+
}
|
|
764
|
+
/** The head of the last full pass's ready list, checked again on its own. */
|
|
765
|
+
async dispatchReady() {
|
|
766
|
+
while (this.ready.length > 0) {
|
|
767
|
+
const item = (await this.activeItems({
|
|
768
|
+
statuses: ["waiting"],
|
|
769
|
+
...this.ready[0]
|
|
770
|
+
})).at(0);
|
|
771
|
+
if (!item) {
|
|
772
|
+
this.ready.shift();
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
const reads = await this.tickReads([item]);
|
|
776
|
+
const tombstone = reads.tombstones.get(item.documentId);
|
|
777
|
+
if (tombstone) {
|
|
778
|
+
this.ready.shift();
|
|
779
|
+
await this.guarded(item, () => this.markPurged(item, tombstone, "waiting"));
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
let convergence;
|
|
783
|
+
try {
|
|
784
|
+
convergence = await this.deleteConvergence(item.documentId, reads);
|
|
785
|
+
} catch (error) {
|
|
786
|
+
this.ready.shift();
|
|
787
|
+
await this.stepFailed(item, error);
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
const converged = convergence.pending.length === 0 && !convergence.unknown;
|
|
791
|
+
if (!converged && this.now() < item.deadline) {
|
|
792
|
+
this.ready.shift();
|
|
793
|
+
continue;
|
|
794
|
+
}
|
|
795
|
+
if (!await this.previousPurgesEnded(item)) return;
|
|
796
|
+
this.ready.shift();
|
|
797
|
+
await this.loadDocumentTypes([item.documentId]);
|
|
798
|
+
const others = await this.activeItems({
|
|
799
|
+
statuses: ["waiting", "purging"],
|
|
800
|
+
requestId: item.requestId
|
|
801
|
+
});
|
|
802
|
+
if (!await this.eligible(item, others)) continue;
|
|
803
|
+
await this.enqueue(item, converged, convergence);
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
async guarded(item, step) {
|
|
808
|
+
try {
|
|
809
|
+
await step();
|
|
810
|
+
} catch (error) {
|
|
811
|
+
await this.stepFailed(item, error);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
async stepFailed(item, error) {
|
|
815
|
+
const message = redactText(this.secret, messageOf(error));
|
|
816
|
+
this.logger.warn(`Erasure of ${item.documentId} (request ${item.requestId}) failed a step; retried next tick: ${message}`);
|
|
817
|
+
await this.setLastError(item, message);
|
|
818
|
+
}
|
|
819
|
+
async activeItems(filter = {}) {
|
|
820
|
+
const { requestId, documentId } = filter;
|
|
821
|
+
return (await this.db.selectFrom("erasure_items as i").innerJoin("erasure_requests as r", "r.requestId", "i.requestId").select([
|
|
822
|
+
"i.requestId",
|
|
823
|
+
"i.documentId",
|
|
824
|
+
"i.status",
|
|
825
|
+
"i.allowLarge",
|
|
826
|
+
"i.markerOrdinal",
|
|
827
|
+
"i.updatedAt",
|
|
828
|
+
"r.deadline"
|
|
829
|
+
]).where("i.status", "in", filter.statuses ?? [
|
|
830
|
+
"waiting",
|
|
831
|
+
"purging",
|
|
832
|
+
"purged"
|
|
833
|
+
]).$if(requestId !== void 0, (qb) => qb.where("i.requestId", "=", requestId)).$if(documentId !== void 0, (qb) => qb.where("i.documentId", "=", documentId)).orderBy("r.requestedAt").orderBy("i.requestId").orderBy("i.documentId").execute()).map((row) => ({
|
|
834
|
+
requestId: row.requestId,
|
|
835
|
+
documentId: row.documentId,
|
|
836
|
+
status: row.status,
|
|
837
|
+
allowLarge: row.allowLarge,
|
|
838
|
+
markerOrdinal: row.markerOrdinal === null ? null : Number(row.markerOrdinal),
|
|
839
|
+
deadline: new Date(row.deadline),
|
|
840
|
+
updatedAt: new Date(row.updatedAt)
|
|
841
|
+
}));
|
|
842
|
+
}
|
|
843
|
+
async tickReads(items) {
|
|
844
|
+
const ids = [...new Set(items.map((item) => item.documentId))];
|
|
845
|
+
const tombstones = /* @__PURE__ */ new Map();
|
|
846
|
+
if (ids.length > 0) {
|
|
847
|
+
const rows = await this.db.selectFrom("document_purges").select([
|
|
848
|
+
"documentId",
|
|
849
|
+
"ordinal",
|
|
850
|
+
"removedRows",
|
|
851
|
+
"purgedAtUtc"
|
|
852
|
+
]).where(sql`"documentId" = any(${ids}::text[])`).execute();
|
|
853
|
+
for (const row of rows) tombstones.set(row.documentId, tombstoneOf(row));
|
|
854
|
+
}
|
|
855
|
+
let remotes;
|
|
856
|
+
return {
|
|
857
|
+
tombstones,
|
|
858
|
+
remotes: () => remotes ??= this.storedRemotes(),
|
|
859
|
+
forgetRemotes: () => {
|
|
860
|
+
remotes = void 0;
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
async storedRemotes() {
|
|
865
|
+
return (await this.db.selectFrom("sync_remotes").select(["name", "collection_id"]).orderBy("name").execute()).map((row) => ({
|
|
866
|
+
name: row.name,
|
|
867
|
+
collectionId: row.collection_id
|
|
868
|
+
}));
|
|
869
|
+
}
|
|
870
|
+
/** A failed item whose purge committed after all, e.g. after a timeout. */
|
|
871
|
+
async recoverFailed() {
|
|
872
|
+
const rows = await this.db.selectFrom("erasure_items as i").innerJoin("document_purges as p", "p.documentId", "i.documentId").innerJoin("erasure_requests as r", "r.requestId", "i.requestId").select([
|
|
873
|
+
"i.requestId",
|
|
874
|
+
"i.documentId",
|
|
875
|
+
"i.allowLarge",
|
|
876
|
+
"i.updatedAt",
|
|
877
|
+
"r.deadline",
|
|
878
|
+
"p.ordinal",
|
|
879
|
+
"p.removedRows",
|
|
880
|
+
"p.purgedAtUtc"
|
|
881
|
+
]).where("i.status", "=", "failed").execute();
|
|
882
|
+
for (const row of rows) {
|
|
883
|
+
const item = {
|
|
884
|
+
requestId: row.requestId,
|
|
885
|
+
documentId: row.documentId,
|
|
886
|
+
status: "failed",
|
|
887
|
+
allowLarge: row.allowLarge,
|
|
888
|
+
markerOrdinal: null,
|
|
889
|
+
deadline: new Date(row.deadline),
|
|
890
|
+
updatedAt: new Date(row.updatedAt)
|
|
891
|
+
};
|
|
892
|
+
await this.guarded(item, () => this.markPurged(item, tombstoneOf(row), "failed"));
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
/** Every failed request with no failed item left is open again. */
|
|
896
|
+
async reopenRequests() {
|
|
897
|
+
try {
|
|
898
|
+
await this.db.transaction().execute(async (trx) => {
|
|
899
|
+
const reopened = await trx.updateTable("erasure_requests as r").set({ status: "open" }).where("r.status", "=", "failed").where((eb) => eb.not(eb.exists(eb.selectFrom("erasure_items as i").select("i.documentId").whereRef("i.requestId", "=", "r.requestId").where("i.status", "=", "failed")))).returning("r.requestId").execute();
|
|
900
|
+
for (const { requestId } of reopened) await appendAudit(trx, this.secret, {
|
|
901
|
+
requestId,
|
|
902
|
+
documentId: null,
|
|
903
|
+
event: "reopened",
|
|
904
|
+
at: this.now()
|
|
905
|
+
});
|
|
906
|
+
});
|
|
907
|
+
} catch (error) {
|
|
908
|
+
this.logger.warn(`Reopening failed erasure requests failed; retried next tick: ${redactText(this.secret, messageOf(error))}`);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async advanceWaiting(items, reads) {
|
|
912
|
+
const waiting = items.filter((i) => i.status === "waiting");
|
|
913
|
+
this.ready = [];
|
|
914
|
+
if (waiting.length === 0) return;
|
|
915
|
+
await this.loadDocumentTypes(waiting.map((i) => i.documentId));
|
|
916
|
+
const ready = [];
|
|
917
|
+
for (const item of this.inPurgeOrder(waiting)) try {
|
|
918
|
+
const tombstone = reads.tombstones.get(item.documentId);
|
|
919
|
+
if (tombstone) {
|
|
920
|
+
await this.markPurged(item, tombstone, "waiting");
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const convergence = await this.deleteConvergence(item.documentId, reads);
|
|
924
|
+
const converged = convergence.pending.length === 0 && !convergence.unknown;
|
|
925
|
+
if (!converged) await this.recordWaiting(item, "delete", convergence);
|
|
926
|
+
if (converged || this.now() >= item.deadline) ready.push({
|
|
927
|
+
item,
|
|
928
|
+
converged,
|
|
929
|
+
convergence
|
|
930
|
+
});
|
|
931
|
+
} catch (error) {
|
|
932
|
+
await this.stepFailed(item, error);
|
|
933
|
+
}
|
|
934
|
+
this.ready = ready.map(({ item }) => ({
|
|
935
|
+
requestId: item.requestId,
|
|
936
|
+
documentId: item.documentId
|
|
937
|
+
}));
|
|
938
|
+
if (items.some((i) => i.status === "purging")) return;
|
|
939
|
+
if (ready.length === 0) return;
|
|
940
|
+
if (!await this.previousPurgesEnded(ready[0].item)) return;
|
|
941
|
+
for (const next of ready) {
|
|
942
|
+
if (!await this.eligible(next.item, items)) continue;
|
|
943
|
+
const key = keyOf(next.item);
|
|
944
|
+
this.ready = this.ready.filter((queued) => keyOf(queued) !== key);
|
|
945
|
+
await this.enqueue(next.item, next.converged, next.convergence);
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
/** Members before their drive: a drive purge needs its members gone. */
|
|
950
|
+
inPurgeOrder(items) {
|
|
951
|
+
const requestOrder = /* @__PURE__ */ new Map();
|
|
952
|
+
for (const item of items) if (!requestOrder.has(item.requestId)) requestOrder.set(item.requestId, requestOrder.size);
|
|
953
|
+
return [...items].sort((a, b) => requestOrder.get(a.requestId) - requestOrder.get(b.requestId) || Number(this.isDrive(a.documentId)) - Number(this.isDrive(b.documentId)));
|
|
954
|
+
}
|
|
955
|
+
/** A drive waits for every member of its request still to be purged. */
|
|
956
|
+
async eligible(item, items) {
|
|
957
|
+
if (!this.isDrive(item.documentId)) return true;
|
|
958
|
+
const others = items.filter((other) => other.requestId === item.requestId && other.documentId !== item.documentId && (other.status === "waiting" || other.status === "purging")).map((other) => other.documentId);
|
|
959
|
+
if (others.length === 0) return true;
|
|
960
|
+
return !(await this.db.selectFrom("document_collections").select("collectionId").where(sql`"documentId" = any(${others}::text[])`).execute()).some((row) => driveOf(row.collectionId) === item.documentId);
|
|
961
|
+
}
|
|
962
|
+
isDrive(documentId) {
|
|
963
|
+
return this.driveTypes.has(this.documentTypes.get(documentId) ?? "");
|
|
964
|
+
}
|
|
965
|
+
async loadDocumentTypes(ids) {
|
|
966
|
+
const missing = ids.filter((id) => !this.documentTypes.has(id));
|
|
967
|
+
if (missing.length === 0) return;
|
|
968
|
+
const rows = await this.db.selectFrom("Operation").select(["documentId", "documentType"]).distinct().where(sql`"documentId" = any(${missing}::text[])`).execute();
|
|
969
|
+
for (const id of missing) {
|
|
970
|
+
const row = rows.find((r) => r.documentId === id);
|
|
971
|
+
if (row) this.documentTypes.set(id, row.documentType);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
/** A timed-out purge's transaction can outlive its job: wait for its lock. */
|
|
975
|
+
async previousPurgesEnded(blocked) {
|
|
976
|
+
if (this.unsettled.size === 0) return true;
|
|
977
|
+
const ids = [...this.unsettled];
|
|
978
|
+
if (await this.purgeLockTaken(ids)) {
|
|
979
|
+
const message = "Waiting for an earlier purge transaction to end before the next purge";
|
|
980
|
+
this.logger.warn(`${message}; it holds the purge lock of ${ids.join(", ")}`);
|
|
981
|
+
await this.setLastError(blocked, message);
|
|
982
|
+
return false;
|
|
983
|
+
}
|
|
984
|
+
for (const id of ids) this.unsettled.delete(id);
|
|
985
|
+
return true;
|
|
986
|
+
}
|
|
987
|
+
/** An exclusive purge lock on one of the ids' buckets, held or awaited. */
|
|
988
|
+
async purgeLockTaken(ids) {
|
|
989
|
+
return (await sql`
|
|
990
|
+
select exists (
|
|
991
|
+
select 1 from pg_catalog.pg_locks
|
|
992
|
+
where locktype = 'advisory'
|
|
993
|
+
and objsubid = 2
|
|
994
|
+
and mode = 'ExclusiveLock'
|
|
995
|
+
and database = (
|
|
996
|
+
select oid from pg_catalog.pg_database
|
|
997
|
+
where datname = current_database()
|
|
998
|
+
)
|
|
999
|
+
and classid::bigint = ${sql.lit(PURGE_NS)}
|
|
1000
|
+
and objid::bigint in (
|
|
1001
|
+
select hashtext(id) & ${sql.lit(PURGE_LOCK_BUCKETS - 1)}
|
|
1002
|
+
from unnest(${ids}::text[]) as t(id)
|
|
1003
|
+
)
|
|
1004
|
+
) as taken
|
|
1005
|
+
`.execute(this.db)).rows[0]?.taken === true;
|
|
1006
|
+
}
|
|
1007
|
+
async enqueue(item, converged, convergence) {
|
|
1008
|
+
if (!await this.transition(item, "waiting", "purging")) return;
|
|
1009
|
+
item.status = "purging";
|
|
1010
|
+
if (!converged) await this.audit(item, "deadline-passed", {
|
|
1011
|
+
deadline: item.deadline.toISOString(),
|
|
1012
|
+
pending: convergence.pending,
|
|
1013
|
+
...convergence.unknown ? { unknown: convergence.unknown } : {}
|
|
1014
|
+
});
|
|
1015
|
+
await this.dispatch(item);
|
|
1016
|
+
}
|
|
1017
|
+
async dispatch(item) {
|
|
1018
|
+
const [job] = await this.options.purges.enqueuePurge([item.documentId], item.requestId, { allowLarge: item.allowLarge });
|
|
1019
|
+
this.jobIds.set(keyOf(item), job.id);
|
|
1020
|
+
}
|
|
1021
|
+
/** Enqueued again with the dispatch time reset; the purge lock gates it. */
|
|
1022
|
+
async redispatch(item, reason) {
|
|
1023
|
+
if (await this.purgeLockTaken([item.documentId])) return;
|
|
1024
|
+
this.logger.warn(`${reason} for ${item.documentId} (request ${item.requestId}); enqueued again`);
|
|
1025
|
+
if (!await this.transition(item, "purging", "purging")) return;
|
|
1026
|
+
item.updatedAt = this.now();
|
|
1027
|
+
await this.dispatch(item);
|
|
1028
|
+
}
|
|
1029
|
+
async advancePurging(item, reads) {
|
|
1030
|
+
const tombstone = reads.tombstones.get(item.documentId);
|
|
1031
|
+
if (tombstone) {
|
|
1032
|
+
await this.markPurged(item, tombstone, "purging");
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
const jobId = this.jobIds.get(keyOf(item));
|
|
1036
|
+
const info = jobId ? this.options.jobs.getJobStatus(jobId) : null;
|
|
1037
|
+
if (!info) {
|
|
1038
|
+
await this.redispatch(item, "No purge job known");
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
if (info.status === JobStatus.FAILED) {
|
|
1042
|
+
this.unsettled.add(item.documentId);
|
|
1043
|
+
await this.markFailed(item, info.error ?? {
|
|
1044
|
+
name: "Error",
|
|
1045
|
+
message: ""
|
|
1046
|
+
});
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
const age = this.now().getTime() - item.updatedAt.getTime();
|
|
1050
|
+
if (age >= this.purgeTimeoutMs) {
|
|
1051
|
+
this.unsettled.add(item.documentId);
|
|
1052
|
+
await this.redispatch(item, `No tombstone after ${age}ms`);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
async markPurged(item, tombstone, from) {
|
|
1056
|
+
if (!await this.transition(item, from, "purged", {
|
|
1057
|
+
markerOrdinal: tombstone.ordinal,
|
|
1058
|
+
lastError: null
|
|
1059
|
+
})) return;
|
|
1060
|
+
this.jobIds.delete(keyOf(item));
|
|
1061
|
+
this.unsettled.delete(item.documentId);
|
|
1062
|
+
item.status = "purged";
|
|
1063
|
+
item.markerOrdinal = tombstone.ordinal;
|
|
1064
|
+
await this.audit(item, "purged", {
|
|
1065
|
+
ordinal: tombstone.ordinal,
|
|
1066
|
+
removedRows: tombstone.removedRows
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
async markFailed(item, error) {
|
|
1070
|
+
const redacted = redactError(this.secret, error);
|
|
1071
|
+
if (!await this.transition(item, "purging", "failed", { lastError: `${redacted.name}: ${redacted.message}` })) return;
|
|
1072
|
+
this.jobIds.delete(keyOf(item));
|
|
1073
|
+
item.status = "failed";
|
|
1074
|
+
await this.audit(item, "failed", { error: redacted });
|
|
1075
|
+
}
|
|
1076
|
+
async advancePurged(item, reads) {
|
|
1077
|
+
const tombstone = reads.tombstones.get(item.documentId);
|
|
1078
|
+
if (!tombstone) throw new Error(`Purged document ${item.documentId} has no tombstone`);
|
|
1079
|
+
const graceOver = this.now().getTime() - tombstone.purgedAtUtc.getTime() >= this.markerGraceMs;
|
|
1080
|
+
if (!await this.markerSettled(item)) {
|
|
1081
|
+
const ordinal = item.markerOrdinal ?? tombstone.ordinal;
|
|
1082
|
+
const convergence = await this.convergence(item.documentId, [ordinal], reads);
|
|
1083
|
+
const refused = await this.refusedRemotes(item);
|
|
1084
|
+
const delivered = convergence.pending.length === 0 && !convergence.unknown;
|
|
1085
|
+
if (delivered && refused.length === 0) await this.audit(item, "marker-converged", {
|
|
1086
|
+
kind: "outcome",
|
|
1087
|
+
ordinal
|
|
1088
|
+
});
|
|
1089
|
+
else if (delivered || graceOver) await this.audit(item, "marker-undelivered", {
|
|
1090
|
+
kind: "outcome",
|
|
1091
|
+
ordinal,
|
|
1092
|
+
pending: convergence.pending,
|
|
1093
|
+
refused,
|
|
1094
|
+
...convergence.unknown ? { unknown: convergence.unknown } : {},
|
|
1095
|
+
...delivered ? {} : { markerGraceExpired: true }
|
|
1096
|
+
});
|
|
1097
|
+
else {
|
|
1098
|
+
await this.recordWaiting(item, "marker", convergence);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
let failed;
|
|
1103
|
+
try {
|
|
1104
|
+
await this.removeRemotes(item, graceOver, reads);
|
|
1105
|
+
} catch (error) {
|
|
1106
|
+
failed = error;
|
|
1107
|
+
}
|
|
1108
|
+
try {
|
|
1109
|
+
await this.erasePermissions(item);
|
|
1110
|
+
} catch (error) {
|
|
1111
|
+
failed ??= error;
|
|
1112
|
+
}
|
|
1113
|
+
if (failed !== void 0) throw failed instanceof Error ? failed : new Error(messageOf(failed));
|
|
1114
|
+
if (await this.transition(item, "purged", "erased", { lastError: null })) item.status = "erased";
|
|
1115
|
+
}
|
|
1116
|
+
async markerSettled(item) {
|
|
1117
|
+
return (await auditOf(this.db, item.requestId, item.documentId, ["marker-converged", "marker-undelivered"])).some((row) => kindOf(row.detail) === "outcome");
|
|
1118
|
+
}
|
|
1119
|
+
/** Refusals by remotes bound to the document, each audited once when read. */
|
|
1120
|
+
async refusedRemotes(item) {
|
|
1121
|
+
const refusals = await this.db.selectFrom("sync_purge_refusals as f").innerJoin("sync_remotes as s", "s.name", "f.remote_name").innerJoin("document_collections as c", (join) => join.onRef("c.collectionId", "=", "s.collection_id").onRef("c.documentId", "=", "f.document_id")).select(["f.remote_name", "f.branch"]).where("f.document_id", "=", item.documentId).where("c.leftOrdinal", "is", null).orderBy("f.refused_at_utc_ms").orderBy("f.remote_name").execute();
|
|
1122
|
+
if (refusals.length === 0) return [];
|
|
1123
|
+
const rows = await auditOf(this.db, item.requestId, item.documentId, ["marker-undelivered"]);
|
|
1124
|
+
const recorded = new Set(rows.filter((row) => kindOf(row.detail) === "refusal").map((row) => {
|
|
1125
|
+
const detail = row.detail;
|
|
1126
|
+
return `${detail.remote}\u0000${detail.branch}`;
|
|
1127
|
+
}));
|
|
1128
|
+
for (const refusal of refusals) {
|
|
1129
|
+
const key = `${refusal.remote_name}\u0000${refusal.branch}`;
|
|
1130
|
+
if (recorded.has(key)) continue;
|
|
1131
|
+
recorded.add(key);
|
|
1132
|
+
await this.audit(item, "marker-undelivered", {
|
|
1133
|
+
kind: "refusal",
|
|
1134
|
+
remote: refusal.remote_name,
|
|
1135
|
+
branch: refusal.branch
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
return [...new Set(refusals.map((r) => r.remote_name))].sort();
|
|
1139
|
+
}
|
|
1140
|
+
/** Stored rows bound to the drive; one not loaded is deleted at markerGrace. */
|
|
1141
|
+
async removeRemotes(item, graceOver, reads) {
|
|
1142
|
+
const bound = (await this.storedRemotes()).filter((row) => driveOf(row.collectionId) === item.documentId);
|
|
1143
|
+
const sync = this.options.syncManager;
|
|
1144
|
+
const loaded = new Set(sync?.list().map((remote) => remote.meta.name));
|
|
1145
|
+
const removed = [];
|
|
1146
|
+
const unloaded = [];
|
|
1147
|
+
if (bound.length > 0) reads.forgetRemotes();
|
|
1148
|
+
for (const row of bound) if (sync && loaded.has(row.name)) {
|
|
1149
|
+
await sync.remove(row.name);
|
|
1150
|
+
removed.push(row.name);
|
|
1151
|
+
} else unloaded.push(row.name);
|
|
1152
|
+
if (unloaded.length > 0 && !graceOver) throw new Error(`Remotes bound to drive ${item.documentId} are stored but not loaded: ${unloaded.join(", ")}`);
|
|
1153
|
+
if (unloaded.length > 0) await this.deleteStoredRemotes(unloaded);
|
|
1154
|
+
if ((await auditOf(this.db, item.requestId, item.documentId, ["remotes-removed"])).length === 0 || bound.length > 0) await this.audit(item, "remotes-removed", {
|
|
1155
|
+
remotes: removed,
|
|
1156
|
+
...unloaded.length > 0 ? { deletedFromStorage: unloaded } : {}
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
/** What SyncManager.remove deletes; cursors, holds, dead letters cascade. */
|
|
1160
|
+
async deleteStoredRemotes(names) {
|
|
1161
|
+
await this.db.transaction().execute(async (trx) => {
|
|
1162
|
+
await trx.deleteFrom("sync_received_markers").where("remote_name", "in", names).execute();
|
|
1163
|
+
await trx.deleteFrom("sync_remotes").where("name", "in", names).execute();
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
async erasePermissions(item) {
|
|
1167
|
+
const recorded = await auditOf(this.db, item.requestId, item.documentId, ["permissions-erased"]);
|
|
1168
|
+
const eraser = this.options.permissions;
|
|
1169
|
+
if (!eraser) {
|
|
1170
|
+
if (recorded.length === 0) await this.audit(item, "permissions-erased", { configured: false });
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
const rows = await eraser.erasePermissions(item.documentId);
|
|
1174
|
+
const any = Object.values(rows).some((count) => count > 0);
|
|
1175
|
+
if (recorded.length === 0 || any) await this.audit(item, "permissions-erased", { rows });
|
|
1176
|
+
}
|
|
1177
|
+
async deleteConvergence(documentId, reads) {
|
|
1178
|
+
const rows = await this.db.selectFrom("operation_index_operations").select(["branch", (eb) => eb.fn.max("ordinal").as("ordinal")]).where("documentId", "=", documentId).where(sql`action->>'type' = 'DELETE_DOCUMENT'`).groupBy("branch").execute();
|
|
1179
|
+
if (rows.length === 0) return {
|
|
1180
|
+
pending: [],
|
|
1181
|
+
unknown: "no DELETE_DOCUMENT in the operation index"
|
|
1182
|
+
};
|
|
1183
|
+
return this.convergence(documentId, rows.map((row) => Number(row.ordinal)), reads);
|
|
1184
|
+
}
|
|
1185
|
+
/** Fails closed: a stored remote owed the ordinal but not loaded is unknown. */
|
|
1186
|
+
async convergence(documentId, ordinals, reads) {
|
|
1187
|
+
const stored = await reads.remotes();
|
|
1188
|
+
const sync = this.options.syncManager;
|
|
1189
|
+
if (!sync || !supportsDeliveryTracking(sync)) {
|
|
1190
|
+
if (stored.length === 0) return { pending: [] };
|
|
1191
|
+
return {
|
|
1192
|
+
pending: stored.map((row) => ({
|
|
1193
|
+
remote: row.name,
|
|
1194
|
+
state: "unknown"
|
|
1195
|
+
})),
|
|
1196
|
+
unknown: "no delivery tracking while sync_remotes has rows"
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
const byRemote = /* @__PURE__ */ new Map();
|
|
1200
|
+
for (const ordinal of ordinals) for (const entry of await sync.pendingDelivery(documentId, ordinal)) if (!byRemote.get(entry.remote) || entry.state === "held") byRemote.set(entry.remote, entry);
|
|
1201
|
+
const loaded = new Set(sync.list().map((remote) => remote.meta.name));
|
|
1202
|
+
const unloaded = stored.filter((row) => !loaded.has(row.name));
|
|
1203
|
+
if (unloaded.length > 0) {
|
|
1204
|
+
const memberships = await this.db.selectFrom("document_collections").select(["collectionId", "leftOrdinal"]).where("documentId", "=", documentId).execute();
|
|
1205
|
+
for (const row of unloaded) if (ordinals.some((ordinal) => memberships.some((m) => m.collectionId === row.collectionId && (m.leftOrdinal === null || ordinal < Number(m.leftOrdinal))))) byRemote.set(row.name, {
|
|
1206
|
+
remote: row.name,
|
|
1207
|
+
state: "unknown"
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
return { pending: [...byRemote.values()].sort(byName) };
|
|
1211
|
+
}
|
|
1212
|
+
/** A waiting row each tick the pending list changes. */
|
|
1213
|
+
async recordWaiting(item, stage, convergence) {
|
|
1214
|
+
const detail = redactDetail(this.secret, {
|
|
1215
|
+
stage,
|
|
1216
|
+
pending: convergence.pending,
|
|
1217
|
+
...convergence.unknown ? { unknown: convergence.unknown } : {}
|
|
1218
|
+
});
|
|
1219
|
+
const last = (await auditOf(this.db, item.requestId, item.documentId, ["waiting"])).at(-1);
|
|
1220
|
+
if (last && canonical(last.detail) === canonical(detail)) return;
|
|
1221
|
+
await this.audit(item, "waiting", detail);
|
|
1222
|
+
}
|
|
1223
|
+
async settleRequests(requestIds) {
|
|
1224
|
+
const rows = await this.db.selectFrom("erasure_items as i").innerJoin("erasure_requests as r", "r.requestId", "i.requestId").select([
|
|
1225
|
+
"i.requestId",
|
|
1226
|
+
"i.documentId",
|
|
1227
|
+
"i.status"
|
|
1228
|
+
]).where("r.status", "=", "open").$if(requestIds !== void 0, (qb) => qb.where("i.requestId", "in", requestIds)).execute();
|
|
1229
|
+
const byRequest = /* @__PURE__ */ new Map();
|
|
1230
|
+
for (const row of rows) byRequest.set(row.requestId, [...byRequest.get(row.requestId) ?? [], row]);
|
|
1231
|
+
for (const [requestId, items] of byRequest) {
|
|
1232
|
+
const failed = items.filter((i) => i.status === "failed");
|
|
1233
|
+
const status = failed.length > 0 ? "failed" : items.every((i) => i.status === "erased") ? "complete" : void 0;
|
|
1234
|
+
if (!status) continue;
|
|
1235
|
+
const result = await this.db.updateTable("erasure_requests").set({ status }).where("requestId", "=", requestId).where("status", "=", "open").executeTakeFirst();
|
|
1236
|
+
if (Number(result.numUpdatedRows) === 0) continue;
|
|
1237
|
+
await appendAudit(this.db, this.secret, {
|
|
1238
|
+
requestId,
|
|
1239
|
+
documentId: null,
|
|
1240
|
+
event: status,
|
|
1241
|
+
detail: status === "failed" ? { failed: failed.map((i) => i.documentId) } : { erased: items.length },
|
|
1242
|
+
at: this.now()
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
async transition(item, from, to, set = {}) {
|
|
1247
|
+
const result = await this.db.updateTable("erasure_items").set({
|
|
1248
|
+
...set,
|
|
1249
|
+
status: to,
|
|
1250
|
+
updatedAt: this.now()
|
|
1251
|
+
}).where("requestId", "=", item.requestId).where("documentId", "=", item.documentId).where("status", "=", from).executeTakeFirst();
|
|
1252
|
+
return Number(result.numUpdatedRows) > 0;
|
|
1253
|
+
}
|
|
1254
|
+
async setLastError(item, message) {
|
|
1255
|
+
try {
|
|
1256
|
+
await this.db.updateTable("erasure_items").set({
|
|
1257
|
+
lastError: message,
|
|
1258
|
+
updatedAt: this.now()
|
|
1259
|
+
}).where("requestId", "=", item.requestId).where("documentId", "=", item.documentId).execute();
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
this.logger.error("Recording an erasure error failed: @error", redactText(this.secret, messageOf(error)));
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
audit(item, event, detail) {
|
|
1265
|
+
return appendAudit(this.db, this.secret, {
|
|
1266
|
+
requestId: item.requestId,
|
|
1267
|
+
documentId: item.documentId,
|
|
1268
|
+
event,
|
|
1269
|
+
detail,
|
|
1270
|
+
at: this.now()
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
};
|
|
1274
|
+
function driveOf(collectionId) {
|
|
1275
|
+
try {
|
|
1276
|
+
return DriveCollectionId.fromKey(collectionId).driveId;
|
|
1277
|
+
} catch {
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
//#endregion
|
|
1282
|
+
//#region src/erasure/module.ts
|
|
1283
|
+
/** The service and scheduler over one reactor module; start the scheduler. */
|
|
1284
|
+
function createModuleErasure(reactorModule, options) {
|
|
1285
|
+
const db = reactorModule.database.withSchema(REACTOR_SCHEMA);
|
|
1286
|
+
const scheduler = new ErasureScheduler({
|
|
1287
|
+
db,
|
|
1288
|
+
deploymentSecret: options.deploymentSecret,
|
|
1289
|
+
signer: options.signer,
|
|
1290
|
+
purges: reactorModule.documentPurgeService,
|
|
1291
|
+
jobs: reactorModule.jobTracker,
|
|
1292
|
+
eventBus: reactorModule.eventBus,
|
|
1293
|
+
syncManager: reactorModule.syncModule?.syncManager,
|
|
1294
|
+
permissions: options.permissions,
|
|
1295
|
+
intervalMs: options.intervalMs,
|
|
1296
|
+
markerGraceMs: options.markerGraceMs,
|
|
1297
|
+
purgeTimeoutMs: options.purgeTimeoutMs,
|
|
1298
|
+
now: options.now,
|
|
1299
|
+
logger: options.logger
|
|
1300
|
+
});
|
|
1301
|
+
return {
|
|
1302
|
+
service: new ErasureService({
|
|
1303
|
+
db,
|
|
1304
|
+
deploymentSecret: options.deploymentSecret,
|
|
1305
|
+
maxPurgeOperations: options.maxPurgeOperations,
|
|
1306
|
+
deadlineMs: options.deadlineMs,
|
|
1307
|
+
now: options.now
|
|
1308
|
+
}),
|
|
1309
|
+
scheduler
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
//#endregion
|
|
1313
|
+
//#region src/disclosure/disclosure-service.ts
|
|
1314
|
+
const DISCLOSURE_NOT_COVERED = [
|
|
1315
|
+
"personal data inside document-model state and action inputs beyond signer, app key, header key, auth creator, grant principals, grant condition literals and reactor-group members",
|
|
1316
|
+
"PHDocumentState.deletedBy, a type that is never written",
|
|
1317
|
+
"header keys that are not P-256 JWKs",
|
|
1318
|
+
"processor, relational, analytics and other add-on read model tables",
|
|
1319
|
+
"attachment bytes, which are content-addressed with no owner",
|
|
1320
|
+
"erasure audit rows, which hold only keyed hashes",
|
|
1321
|
+
"copies held by peers, and Connect's IndexedDB and browser backups",
|
|
1322
|
+
"database backups, WAL and point-in-time recovery"
|
|
1323
|
+
];
|
|
1324
|
+
const NO_PERMISSION_LOOKUP = "reactor-api permission rows: no permission lookup is configured";
|
|
1325
|
+
/** Lists what is held about one identifier. Read-only. */
|
|
1326
|
+
var DisclosureService = class {
|
|
1327
|
+
deploymentSecret;
|
|
1328
|
+
permissions;
|
|
1329
|
+
db;
|
|
1330
|
+
constructor(reactorDb, deploymentSecret, permissions, schema = REACTOR_SCHEMA) {
|
|
1331
|
+
this.deploymentSecret = deploymentSecret;
|
|
1332
|
+
this.permissions = permissions;
|
|
1333
|
+
assertDeploymentSecret(deploymentSecret);
|
|
1334
|
+
this.db = reactorDb.withSchema(schema);
|
|
1335
|
+
}
|
|
1336
|
+
async disclose(identifier) {
|
|
1337
|
+
const hash = subjectHash(this.deploymentSecret, identifier);
|
|
1338
|
+
const lowered = identifier.toLowerCase();
|
|
1339
|
+
const documents = await this.db.selectFrom("subject_documents").select([
|
|
1340
|
+
"documentId",
|
|
1341
|
+
"role",
|
|
1342
|
+
"firstOrdinal",
|
|
1343
|
+
"lastOrdinal"
|
|
1344
|
+
]).where("subjectHash", "=", hash).orderBy("documentId").orderBy("role").execute();
|
|
1345
|
+
const bound = await this.db.selectFrom("sync_remotes").select([
|
|
1346
|
+
"name",
|
|
1347
|
+
"collection_id",
|
|
1348
|
+
"channel_type"
|
|
1349
|
+
]).where(sql`lower(bound_address)`, "=", lowered).orderBy("name").execute();
|
|
1350
|
+
const manifests = await this.db.selectFrom("sync_remotes").select([
|
|
1351
|
+
"name",
|
|
1352
|
+
"peer_manifest",
|
|
1353
|
+
"peer_manifest_at_utc_ms"
|
|
1354
|
+
]).where("peer_manifest", "is not", null).orderBy("name").execute();
|
|
1355
|
+
const notCovered = [...DISCLOSURE_NOT_COVERED];
|
|
1356
|
+
let permissions = [];
|
|
1357
|
+
if (this.permissions === void 0) notCovered.push(NO_PERMISSION_LOOKUP);
|
|
1358
|
+
else permissions = await this.permissions.rowsForAddress(identifier);
|
|
1359
|
+
return {
|
|
1360
|
+
subjectHash: hash,
|
|
1361
|
+
documents: documents.map((row) => ({
|
|
1362
|
+
documentId: row.documentId,
|
|
1363
|
+
role: row.role,
|
|
1364
|
+
firstOrdinal: Number(row.firstOrdinal),
|
|
1365
|
+
lastOrdinal: Number(row.lastOrdinal)
|
|
1366
|
+
})),
|
|
1367
|
+
boundSyncRemotes: bound.map((row) => ({
|
|
1368
|
+
name: row.name,
|
|
1369
|
+
collectionId: row.collection_id,
|
|
1370
|
+
channelType: row.channel_type
|
|
1371
|
+
})),
|
|
1372
|
+
peerManifests: manifests.flatMap((row) => {
|
|
1373
|
+
const appKey = appKeyOf(row.peer_manifest);
|
|
1374
|
+
if (appKey === void 0 || appKey.toLowerCase() !== lowered) return [];
|
|
1375
|
+
const at = row.peer_manifest_at_utc_ms;
|
|
1376
|
+
return [{
|
|
1377
|
+
remoteName: row.name,
|
|
1378
|
+
appKey,
|
|
1379
|
+
heardAtUtcMs: at === null ? null : Number(at)
|
|
1380
|
+
}];
|
|
1381
|
+
}),
|
|
1382
|
+
permissions,
|
|
1383
|
+
notCovered
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
};
|
|
1387
|
+
/** A malformed manifest names no one; it must not fail the disclosure. */
|
|
1388
|
+
function appKeyOf(manifest) {
|
|
1389
|
+
if (manifest === null) return void 0;
|
|
1390
|
+
let parsed;
|
|
1391
|
+
try {
|
|
1392
|
+
parsed = JSON.parse(manifest);
|
|
1393
|
+
} catch {
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
const appKey = parsed?.appKey;
|
|
1397
|
+
return typeof appKey === "string" ? appKey : void 0;
|
|
1398
|
+
}
|
|
1399
|
+
//#endregion
|
|
1400
|
+
//#region src/subgraph/schema.ts
|
|
1401
|
+
const typeDefs = gql`
|
|
1402
|
+
type PrivacySubjectDocument {
|
|
1403
|
+
documentId: ID!
|
|
1404
|
+
role: String!
|
|
1405
|
+
firstOrdinal: Int!
|
|
1406
|
+
lastOrdinal: Int!
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
type PrivacyBoundSyncRemote {
|
|
1410
|
+
name: String!
|
|
1411
|
+
collectionId: String!
|
|
1412
|
+
channelType: String!
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
type PrivacyPeerManifestAppKey {
|
|
1416
|
+
remoteName: String!
|
|
1417
|
+
appKey: String!
|
|
1418
|
+
heardAtUtcMs: Float
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
type PrivacyPermissionRow {
|
|
1422
|
+
table: String!
|
|
1423
|
+
column: String!
|
|
1424
|
+
documentId: ID
|
|
1425
|
+
"JSON-encoded"
|
|
1426
|
+
detail: String
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
type PrivacyDisclosure {
|
|
1430
|
+
subjectHash: String!
|
|
1431
|
+
documents: [PrivacySubjectDocument!]!
|
|
1432
|
+
boundSyncRemotes: [PrivacyBoundSyncRemote!]!
|
|
1433
|
+
peerManifests: [PrivacyPeerManifestAppKey!]!
|
|
1434
|
+
permissions: [PrivacyPermissionRow!]!
|
|
1435
|
+
notCovered: [String!]!
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
type PrivacyErasurePlanItem {
|
|
1439
|
+
documentId: ID!
|
|
1440
|
+
expandedFrom: ID
|
|
1441
|
+
live: Boolean!
|
|
1442
|
+
operationCount: Int!
|
|
1443
|
+
groupReferencers: [ID!]!
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
type PrivacyErasurePlan {
|
|
1447
|
+
maxPurgeOperations: Int!
|
|
1448
|
+
items: [PrivacyErasurePlanItem!]!
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
type PrivacyErasureItem {
|
|
1452
|
+
documentId: ID!
|
|
1453
|
+
status: String!
|
|
1454
|
+
allowLarge: Boolean!
|
|
1455
|
+
markerOrdinal: Int
|
|
1456
|
+
lastError: String
|
|
1457
|
+
updatedAt: String!
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
type PrivacyErasureRequest {
|
|
1461
|
+
requestId: ID!
|
|
1462
|
+
subjectHash: String
|
|
1463
|
+
requestedBy: String!
|
|
1464
|
+
requestedAt: String!
|
|
1465
|
+
deadline: String!
|
|
1466
|
+
status: String!
|
|
1467
|
+
items: [PrivacyErasureItem!]!
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
type Query {
|
|
1471
|
+
disclose(identifier: String!): PrivacyDisclosure!
|
|
1472
|
+
erasurePlan(ids: [ID!]!): PrivacyErasurePlan!
|
|
1473
|
+
erasureRequest(requestId: ID!): PrivacyErasureRequest!
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
type Mutation {
|
|
1477
|
+
"deadline is an ISO 8601 timestamp"
|
|
1478
|
+
requestErasure(
|
|
1479
|
+
ids: [ID!]!
|
|
1480
|
+
deadline: String
|
|
1481
|
+
allowLarge: [ID!]
|
|
1482
|
+
): PrivacyErasureRequest!
|
|
1483
|
+
}
|
|
1484
|
+
`;
|
|
1485
|
+
//#endregion
|
|
1486
|
+
//#region src/subgraph/resolvers.ts
|
|
1487
|
+
function requireAdmin(authorizationService, ctx) {
|
|
1488
|
+
const address = ctx.user?.address;
|
|
1489
|
+
if (!address || !authorizationService.isSupremeAdmin(address)) throw new GraphQLError("Admin access required", { extensions: { code: "FORBIDDEN" } });
|
|
1490
|
+
return address;
|
|
1491
|
+
}
|
|
1492
|
+
function parseDeadline(deadline) {
|
|
1493
|
+
if (deadline === null || deadline === void 0) return void 0;
|
|
1494
|
+
const parsed = new Date(deadline);
|
|
1495
|
+
if (Number.isNaN(parsed.getTime())) throw new GraphQLError("deadline is not an ISO 8601 timestamp", { extensions: { code: "BAD_USER_INPUT" } });
|
|
1496
|
+
return parsed;
|
|
1497
|
+
}
|
|
1498
|
+
function shapeDisclosure(disclosure) {
|
|
1499
|
+
return {
|
|
1500
|
+
...disclosure,
|
|
1501
|
+
permissions: disclosure.permissions.map((row) => ({
|
|
1502
|
+
...row,
|
|
1503
|
+
detail: row.detail === void 0 ? null : JSON.stringify(row.detail)
|
|
1504
|
+
}))
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
function shapeRequest(request) {
|
|
1508
|
+
return {
|
|
1509
|
+
...request,
|
|
1510
|
+
requestedAt: request.requestedAt.toISOString(),
|
|
1511
|
+
deadline: request.deadline.toISOString(),
|
|
1512
|
+
items: request.items.map((item) => ({
|
|
1513
|
+
...item,
|
|
1514
|
+
updatedAt: item.updatedAt.toISOString()
|
|
1515
|
+
}))
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
/** Every field refuses a caller that is not a supreme admin, before any work. */
|
|
1519
|
+
function createPrivacyResolvers(deps) {
|
|
1520
|
+
const { authorizationService, erasure, disclosure } = deps;
|
|
1521
|
+
return {
|
|
1522
|
+
Query: {
|
|
1523
|
+
async disclose(_root, args, ctx) {
|
|
1524
|
+
requireAdmin(authorizationService, ctx);
|
|
1525
|
+
return shapeDisclosure(await disclosure.disclose(args.identifier));
|
|
1526
|
+
},
|
|
1527
|
+
async erasurePlan(_root, args, ctx) {
|
|
1528
|
+
requireAdmin(authorizationService, ctx);
|
|
1529
|
+
return erasure.plan(args.ids);
|
|
1530
|
+
},
|
|
1531
|
+
async erasureRequest(_root, args, ctx) {
|
|
1532
|
+
requireAdmin(authorizationService, ctx);
|
|
1533
|
+
return shapeRequest(await erasure.status(args.requestId));
|
|
1534
|
+
}
|
|
1535
|
+
},
|
|
1536
|
+
Mutation: { async requestErasure(_root, args, ctx) {
|
|
1537
|
+
const requestedBy = requireAdmin(authorizationService, ctx);
|
|
1538
|
+
return shapeRequest(await erasure.request(args.ids, {
|
|
1539
|
+
requestedBy,
|
|
1540
|
+
deadline: parseDeadline(args.deadline),
|
|
1541
|
+
allowLarge: args.allowLarge ?? void 0
|
|
1542
|
+
}));
|
|
1543
|
+
} }
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
//#endregion
|
|
1547
|
+
//#region src/subgraph/subgraph.ts
|
|
1548
|
+
const PRIVACY_SUBGRAPH_NAME = "privacy";
|
|
1549
|
+
/** Under OPEN every caller, anonymous included, is a supreme admin. */
|
|
1550
|
+
var PrivacySubgraphOpenPolicyError = class extends Error {
|
|
1551
|
+
policy;
|
|
1552
|
+
constructor(policy) {
|
|
1553
|
+
super(`The privacy subgraph is not mounted under policy ${policy}: it admits anonymous callers as admins`);
|
|
1554
|
+
this.policy = policy;
|
|
1555
|
+
this.name = "PrivacySubgraphOpenPolicyError";
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
function admitsAnonymous(authorizationService) {
|
|
1559
|
+
return authorizationService.config.policy === "OPEN" || authorizationService.isSupremeAdmin(void 0) || authorizationService.isSupremeAdmin("");
|
|
1560
|
+
}
|
|
1561
|
+
/** Throws PrivacySubgraphOpenPolicyError when anonymous callers are admins. */
|
|
1562
|
+
function createPrivacySubgraph(deps) {
|
|
1563
|
+
if (admitsAnonymous(deps.authorizationService)) throw new PrivacySubgraphOpenPolicyError(deps.authorizationService.config.policy);
|
|
1564
|
+
return {
|
|
1565
|
+
name: PRIVACY_SUBGRAPH_NAME,
|
|
1566
|
+
typeDefs,
|
|
1567
|
+
resolvers: createPrivacyResolvers(deps)
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
//#endregion
|
|
1571
|
+
export { DEFAULT_ERASURE_DEADLINE_MS, DEFAULT_ERASURE_INTERVAL_MS, DEFAULT_MARKER_GRACE_MS, DEFAULT_PURGE_TIMEOUT_MS, DISCLOSURE_NOT_COVERED, DeploymentSecretError, DisclosureService, ErasureRequestNotFoundError, ErasureScheduler, ErasureService, ErasureSignerMissingError, LiveReadModelRegistrationError, MIN_DEPLOYMENT_SECRET_BYTES, PRIVACY_SUBGRAPH_NAME, PrivacySubgraphOpenPolicyError, SUBJECT_DOCUMENTS_READ_MODEL_ID, SubjectDocumentsReadModel, createModuleErasure, createPrivacyResolvers, createPrivacySubgraph, getReactorPrivacyMigrationStatus, isAddressLiteral, jwkToDidKey, mentionsOf, typeDefs as privacySubgraphTypeDefs, registerSubjectDocumentsReadModel, runReactorPrivacyMigrations, subjectHash };
|
|
1572
|
+
|
|
1573
|
+
//# sourceMappingURL=index.js.map
|