@powerhousedao/reactor-api 6.2.3-dev.79 → 6.2.3-dev.80
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/dist/adapter-gateway-apollo-D-EdZ4e-.mjs +2 -2
- package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -1
- package/dist/{base-document-models-ux7TZ9X3.mjs → base-document-models-D-cmBBYJ.mjs} +116 -27
- package/dist/base-document-models-D-cmBBYJ.mjs.map +1 -0
- package/dist/{create-schema-BUk-IQCT.d.mts → create-schema-Dio_7akA.d.mts} +22 -7
- package/dist/create-schema-Dio_7akA.d.mts.map +1 -0
- package/dist/error-info-BaEL50f5.mjs +2 -2
- package/dist/error-info-BaEL50f5.mjs.map +1 -1
- package/dist/index.d.mts +297 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +607 -138
- package/dist/index.mjs.map +1 -1
- package/dist/{package-subgraph-check-BGfeyfnc.mjs → package-subgraph-check-C0PD_Tj9.mjs} +4 -4
- package/dist/{package-subgraph-check-BGfeyfnc.mjs.map → package-subgraph-check-C0PD_Tj9.mjs.map} +1 -1
- package/dist/src/graphql/subgraph-types.d.mts +1 -1
- package/dist/src/graphql/subgraph-types.mjs +1 -1
- package/dist/src/packages/vite-loader.d.mts +4 -1
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +31 -13
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/{subgraph-extraction-BYKOycxo.mjs → subgraph-extraction-BA9WKjn1.mjs} +470 -10
- package/dist/subgraph-extraction-BA9WKjn1.mjs.map +1 -0
- package/dist/{types-BEpxtyKW.d.mts → types-PXB1ctpi.d.mts} +19 -2
- package/dist/types-PXB1ctpi.d.mts.map +1 -0
- package/package.json +13 -14
- package/dist/base-document-models-ux7TZ9X3.mjs.map +0 -1
- package/dist/create-schema-BUk-IQCT.d.mts.map +0 -1
- package/dist/subgraph-extraction-BYKOycxo.mjs.map +0 -1
- package/dist/types-BEpxtyKW.d.mts.map +0 -1
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5ecb0ccc-1657-5ac5-9ea4-6a09c1e416e2")}catch(e){}}();
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { childLogger } from "document-model";
|
|
5
5
|
import { gql } from "graphql-tag";
|
|
6
6
|
import { GraphQLError } from "graphql";
|
|
7
|
-
import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
|
|
7
|
+
import { DRIVE_AUTH_ERROR_MESSAGES, DocumentChangeType, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
|
|
8
8
|
import { PURGE_DOCUMENT } from "@powerhousedao/shared/document-model";
|
|
9
|
+
import { hashNamespace } from "@powerhousedao/shared/processors";
|
|
10
|
+
import { sql } from "kysely";
|
|
9
11
|
import { verifyAuthBearerToken } from "@renown/sdk";
|
|
10
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
13
|
import path, { dirname, isAbsolute, join } from "node:path";
|
|
12
14
|
import { existsSync, readFileSync } from "node:fs";
|
|
13
15
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
+
import { isScalarDefinition, scalarDefinitionVersion } from "document-model/scalars";
|
|
14
17
|
import { packageJsonExports } from "@powerhousedao/shared/clis/constants";
|
|
15
18
|
//#region src/graphql/errors.ts
|
|
16
19
|
/** Caller (authenticated or anonymous) lacks permission for the document. */
|
|
@@ -299,6 +302,395 @@ function createCanonicalDocumentIdResolver(clients, operationType = "query") {
|
|
|
299
302
|
};
|
|
300
303
|
}
|
|
301
304
|
//#endregion
|
|
305
|
+
//#region src/services/readable-documents.ts
|
|
306
|
+
/**
|
|
307
|
+
* The read-permission closure as a read model: `readable_documents(user_id,
|
|
308
|
+
* document_id)` in the processors' relational database, so an index subgraph
|
|
309
|
+
* decides "may the caller see this row" with one join instead of one
|
|
310
|
+
* authorization call per row.
|
|
311
|
+
*
|
|
312
|
+
* It is a projection of the host's own permission data, never an authority:
|
|
313
|
+
* the write path keeps deciding from the permission tables in the reactor
|
|
314
|
+
* store (`IAuthorizationService`), and nothing here is consulted for a
|
|
315
|
+
* write. The projection mirrors four small facts into its own namespace,
|
|
316
|
+
* documents, `child` edges, protection and grants, and recomputes the
|
|
317
|
+
* closure from them in one SQL statement whenever one of them changes:
|
|
318
|
+
*
|
|
319
|
+
* - `'*'` for a document that is unprotected along its whole ancestor chain
|
|
320
|
+
* (everyone may read it; `DEFAULT_PROTECTION` fills a missing row),
|
|
321
|
+
* - the owner of a protected document,
|
|
322
|
+
* - every holder of a grant on the document or any ancestor (READ is the
|
|
323
|
+
* floor, so any level counts).
|
|
324
|
+
*
|
|
325
|
+
* Listed admins are a bypass, never rows. Under OPEN everyone reads
|
|
326
|
+
* everything and under ADMIN_ONLY only admins read, so the projection keeps
|
|
327
|
+
* no rows for those policies; `filterFor` answers from the policy alone.
|
|
328
|
+
*
|
|
329
|
+
* Kept current by the permission service's change notifications and the
|
|
330
|
+
* reactor's document and relationship change events; rebuilt from the
|
|
331
|
+
* reactor and the permission service at start. Eventually consistent, no
|
|
332
|
+
* worse than the permission cache's TTL. The document's own `state.auth`
|
|
333
|
+
* policy (the reactor's read gate under `authEnforcement`) is not projected
|
|
334
|
+
* here; a subgraph that must honour it keeps the per-document reactor check.
|
|
335
|
+
*/
|
|
336
|
+
const READABLE_DOCUMENTS_NAMESPACE = "ph_readable_documents";
|
|
337
|
+
/** The `user_id` that stands for every caller, anonymous included. */
|
|
338
|
+
const EVERYONE = "*";
|
|
339
|
+
/** Document types that root the `child` hierarchy: drives. */
|
|
340
|
+
const DEFAULT_ROOT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
|
|
341
|
+
/**
|
|
342
|
+
* `select document_id from <schema>.readable_documents where user_id in
|
|
343
|
+
* (:user, '*')`, for a `where document_id in (...)` on an index table.
|
|
344
|
+
*/
|
|
345
|
+
function readableDocumentsSubquery(filter) {
|
|
346
|
+
return sql`(select document_id from ${sql.table(`${filter.schema}.readable_documents`)} where user_id in (${filter.userId}, ${"*"}))`;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Applies a caller's filter to a query over a document-keyed index table:
|
|
350
|
+
* unchanged for `all`, no row for `none`, `where <column> in (readable ids)`
|
|
351
|
+
* for `ids`. `column` is the table's document id column, qualified when the
|
|
352
|
+
* query joins.
|
|
353
|
+
*/
|
|
354
|
+
function applyReadableFilter(query, column, filter, options = {}) {
|
|
355
|
+
const pass = options.passWhen ? sql`${sql.ref(options.passWhen.column)} = ${options.passWhen.equals}` : void 0;
|
|
356
|
+
switch (filter.kind) {
|
|
357
|
+
case "all": return query;
|
|
358
|
+
case "none": return query.where(pass ?? sql`false`);
|
|
359
|
+
case "ids": {
|
|
360
|
+
const listed = sql`${sql.ref(column)} in ${readableDocumentsSubquery(filter)}`;
|
|
361
|
+
return query.where(pass ? sql`(${listed} or ${pass})` : listed);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Whether `filter` lists one document: the scope gate of an index query (its
|
|
367
|
+
* drive or folder), asked of the same rows the row filter joins on.
|
|
368
|
+
*/
|
|
369
|
+
async function isDocumentListed(db, filter, documentId) {
|
|
370
|
+
switch (filter.kind) {
|
|
371
|
+
case "all": return true;
|
|
372
|
+
case "none": return false;
|
|
373
|
+
case "ids": return (await sql`select 1 as listed from ${sql.table(`${filter.schema}.readable_documents`)} where document_id = ${documentId} and user_id in (${filter.userId}, ${"*"}) limit 1`.execute(db)).rows.length > 0;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
var ReadableDocumentsProjection = class {
|
|
377
|
+
schema;
|
|
378
|
+
ready;
|
|
379
|
+
#deps;
|
|
380
|
+
#maintained;
|
|
381
|
+
#db;
|
|
382
|
+
#resolveReady;
|
|
383
|
+
#rejectReady;
|
|
384
|
+
#unsubscribe;
|
|
385
|
+
#timer;
|
|
386
|
+
#chain = Promise.resolve();
|
|
387
|
+
#pending = false;
|
|
388
|
+
#stopped = false;
|
|
389
|
+
constructor(deps) {
|
|
390
|
+
this.#deps = deps;
|
|
391
|
+
this.schema = hashNamespace(READABLE_DOCUMENTS_NAMESPACE);
|
|
392
|
+
this.#maintained = deps.config.policy === AuthorizationPolicy.DOCUMENT_PERMISSIONS && deps.permissions !== void 0;
|
|
393
|
+
this.ready = new Promise((resolve, reject) => {
|
|
394
|
+
this.#resolveReady = resolve;
|
|
395
|
+
this.#rejectReady = reject;
|
|
396
|
+
});
|
|
397
|
+
this.ready.catch(() => void 0);
|
|
398
|
+
}
|
|
399
|
+
/** Creates the tables, rebuilds the closure, and follows changes. */
|
|
400
|
+
async start() {
|
|
401
|
+
if (!this.#maintained) {
|
|
402
|
+
this.#resolveReady();
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
try {
|
|
406
|
+
const db = await this.#deps.relationalDb.createNamespace(READABLE_DOCUMENTS_NAMESPACE);
|
|
407
|
+
this.#db = db;
|
|
408
|
+
await this.#ensureTables(db);
|
|
409
|
+
this.#unsubscribe = this.#deps.read.subscribe({}, (event) => {
|
|
410
|
+
this.#onDocumentChange(event).catch((error) => {
|
|
411
|
+
this.#deps.logger?.warn("readable-documents: a change could not be applied: @error", error);
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
this.#unsubscribePermissions = this.#deps.permissions.onChange((documentId) => {
|
|
415
|
+
this.#onPermissionChange(documentId).catch((error) => {
|
|
416
|
+
this.#deps.logger?.warn("readable-documents: a permission change could not be applied: @error", error);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
await this.rebuild();
|
|
420
|
+
this.#resolveReady();
|
|
421
|
+
} catch (error) {
|
|
422
|
+
this.#rejectReady(error);
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
#unsubscribePermissions;
|
|
427
|
+
async stop() {
|
|
428
|
+
this.#stopped = true;
|
|
429
|
+
this.#unsubscribe?.();
|
|
430
|
+
this.#unsubscribePermissions?.();
|
|
431
|
+
if (this.#timer) clearTimeout(this.#timer);
|
|
432
|
+
await this.#chain;
|
|
433
|
+
}
|
|
434
|
+
filterFor(userAddress) {
|
|
435
|
+
const address = userAddress?.toLowerCase();
|
|
436
|
+
const { policy, admins } = this.#deps.config;
|
|
437
|
+
if (policy === AuthorizationPolicy.OPEN) return { kind: "all" };
|
|
438
|
+
const admin = address !== void 0 && admins.includes(address);
|
|
439
|
+
if (policy === AuthorizationPolicy.ADMIN_ONLY) return admin ? { kind: "all" } : { kind: "none" };
|
|
440
|
+
if (admin) return { kind: "all" };
|
|
441
|
+
if (!this.#db || !this.#isReady) return { kind: "none" };
|
|
442
|
+
return {
|
|
443
|
+
kind: "ids",
|
|
444
|
+
schema: this.schema,
|
|
445
|
+
userId: address ?? "*"
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
#isReady = false;
|
|
449
|
+
/**
|
|
450
|
+
* Rebuilds the mirrors from the reactor and the permission service, then
|
|
451
|
+
* recomputes the closure. Serialised with the incremental updates.
|
|
452
|
+
*/
|
|
453
|
+
rebuild() {
|
|
454
|
+
return this.#enqueue(async () => {
|
|
455
|
+
const db = this.#db;
|
|
456
|
+
const pageSize = this.#deps.pageSize ?? 500;
|
|
457
|
+
const ids = await this.#allDocumentIds(pageSize);
|
|
458
|
+
const edges = await this.#allEdges(pageSize);
|
|
459
|
+
const snapshots = await this.#snapshotsOf(ids, pageSize);
|
|
460
|
+
await db.transaction().execute(async (trx) => {
|
|
461
|
+
await trx.deleteFrom("documents").execute();
|
|
462
|
+
await trx.deleteFrom("edges").execute();
|
|
463
|
+
await trx.deleteFrom("protection").execute();
|
|
464
|
+
await trx.deleteFrom("grants").execute();
|
|
465
|
+
for (const chunk of chunks(ids, pageSize)) await trx.insertInto("documents").values(chunk.map((document_id) => ({ document_id }))).execute();
|
|
466
|
+
for (const chunk of chunks(edges, pageSize)) await trx.insertInto("edges").values(chunk).execute();
|
|
467
|
+
const protection = [...snapshots.values()].map((s) => ({
|
|
468
|
+
document_id: s.documentId,
|
|
469
|
+
protected: s.isProtected,
|
|
470
|
+
owner_id: s.ownerAddress
|
|
471
|
+
}));
|
|
472
|
+
for (const chunk of chunks(protection, pageSize)) await trx.insertInto("protection").values(chunk).execute();
|
|
473
|
+
const grants = [...snapshots.values()].flatMap((s) => [...s.grants.keys()].map((user_id) => ({
|
|
474
|
+
document_id: s.documentId,
|
|
475
|
+
user_id
|
|
476
|
+
})));
|
|
477
|
+
for (const chunk of chunks(grants, pageSize)) await trx.insertInto("grants").values(chunk).execute();
|
|
478
|
+
await this.#recompute(trx);
|
|
479
|
+
});
|
|
480
|
+
this.#isReady = true;
|
|
481
|
+
this.#deps.logger?.info(`readable-documents: rebuilt (${ids.length} documents, ${edges.length} edges, ${snapshots.size} protected or granted)`);
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
async #onDocumentChange(event) {
|
|
485
|
+
const db = this.#db;
|
|
486
|
+
if (!db || this.#stopped) return;
|
|
487
|
+
const ids = event.documents.map((d) => d.header.id);
|
|
488
|
+
switch (event.type) {
|
|
489
|
+
case DocumentChangeType.Created: {
|
|
490
|
+
const snapshots = await this.#snapshotsOf(ids, ids.length || 1);
|
|
491
|
+
await this.#enqueue(async () => {
|
|
492
|
+
for (const document_id of ids) await db.insertInto("documents").values({ document_id }).onConflict((oc) => oc.column("document_id").doNothing()).execute();
|
|
493
|
+
await this.#applySnapshots(db, snapshots);
|
|
494
|
+
});
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
case DocumentChangeType.Deleted:
|
|
498
|
+
await this.#enqueue(async () => {
|
|
499
|
+
for (const id of ids) {
|
|
500
|
+
await db.deleteFrom("documents").where("document_id", "=", id).execute();
|
|
501
|
+
await db.deleteFrom("edges").where((eb) => eb.or([eb("parent_id", "=", id), eb("child_id", "=", id)])).execute();
|
|
502
|
+
await db.deleteFrom("protection").where("document_id", "=", id).execute();
|
|
503
|
+
await db.deleteFrom("grants").where("document_id", "=", id).execute();
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
break;
|
|
507
|
+
case DocumentChangeType.ChildAdded:
|
|
508
|
+
case DocumentChangeType.ParentAdded: {
|
|
509
|
+
const edge = edgeOf(event);
|
|
510
|
+
if (!edge) return;
|
|
511
|
+
await this.#enqueue(async () => {
|
|
512
|
+
await db.insertInto("edges").values(edge).onConflict((oc) => oc.columns(["parent_id", "child_id"]).doNothing()).execute();
|
|
513
|
+
});
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
case DocumentChangeType.ChildRemoved:
|
|
517
|
+
case DocumentChangeType.ParentRemoved: {
|
|
518
|
+
const edge = edgeOf(event);
|
|
519
|
+
if (!edge) return;
|
|
520
|
+
await this.#enqueue(async () => {
|
|
521
|
+
await db.deleteFrom("edges").where("parent_id", "=", edge.parent_id).where("child_id", "=", edge.child_id).execute();
|
|
522
|
+
});
|
|
523
|
+
break;
|
|
524
|
+
}
|
|
525
|
+
default: return;
|
|
526
|
+
}
|
|
527
|
+
this.#scheduleRecompute();
|
|
528
|
+
}
|
|
529
|
+
async #onPermissionChange(documentId) {
|
|
530
|
+
const db = this.#db;
|
|
531
|
+
if (!db || this.#stopped) return;
|
|
532
|
+
const snapshots = await this.#snapshotsOf([documentId], 1);
|
|
533
|
+
await this.#enqueue(async () => {
|
|
534
|
+
await this.#applySnapshots(db, snapshots);
|
|
535
|
+
});
|
|
536
|
+
this.#scheduleRecompute();
|
|
537
|
+
}
|
|
538
|
+
async #applySnapshots(db, snapshots) {
|
|
539
|
+
for (const s of snapshots.values()) {
|
|
540
|
+
await db.insertInto("protection").values({
|
|
541
|
+
document_id: s.documentId,
|
|
542
|
+
protected: s.isProtected,
|
|
543
|
+
owner_id: s.ownerAddress
|
|
544
|
+
}).onConflict((oc) => oc.column("document_id").doUpdateSet({
|
|
545
|
+
protected: s.isProtected,
|
|
546
|
+
owner_id: s.ownerAddress
|
|
547
|
+
})).execute();
|
|
548
|
+
await db.deleteFrom("grants").where("document_id", "=", s.documentId).execute();
|
|
549
|
+
const users = [...s.grants.keys()];
|
|
550
|
+
if (users.length > 0) await db.insertInto("grants").values(users.map((user_id) => ({
|
|
551
|
+
document_id: s.documentId,
|
|
552
|
+
user_id
|
|
553
|
+
}))).execute();
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
#scheduleRecompute() {
|
|
557
|
+
if (this.#stopped) return;
|
|
558
|
+
this.#pending = true;
|
|
559
|
+
if (this.#timer) return;
|
|
560
|
+
this.#timer = setTimeout(() => {
|
|
561
|
+
this.#timer = void 0;
|
|
562
|
+
if (!this.#pending) return;
|
|
563
|
+
this.#pending = false;
|
|
564
|
+
this.#enqueue(async () => {
|
|
565
|
+
const db = this.#db;
|
|
566
|
+
if (!db) return;
|
|
567
|
+
await db.transaction().execute((trx) => this.#recompute(trx));
|
|
568
|
+
}).catch((error) => {
|
|
569
|
+
this.#deps.logger?.warn("readable-documents: recompute failed: @error", error);
|
|
570
|
+
});
|
|
571
|
+
}, this.#deps.debounceMs ?? 100);
|
|
572
|
+
}
|
|
573
|
+
/** The closure, in one statement (UNION dedups, so a cycle terminates). */
|
|
574
|
+
async #recompute(db) {
|
|
575
|
+
const t = (name) => sql.table(`${this.schema}.${name}`);
|
|
576
|
+
const defaultProtection = this.#deps.config.defaultProtection;
|
|
577
|
+
await sql`delete from ${t("readable_documents")}`.execute(db);
|
|
578
|
+
await sql`
|
|
579
|
+
insert into ${t("readable_documents")} (user_id, document_id)
|
|
580
|
+
with recursive anc(document_id, ancestor_id) as (
|
|
581
|
+
select document_id, document_id from ${t("documents")}
|
|
582
|
+
union
|
|
583
|
+
select a.document_id, e.parent_id
|
|
584
|
+
from anc a join ${t("edges")} e on e.child_id = a.ancestor_id
|
|
585
|
+
),
|
|
586
|
+
prot as (
|
|
587
|
+
select d.document_id,
|
|
588
|
+
coalesce(p.protected, ${defaultProtection}) as protected,
|
|
589
|
+
p.owner_id
|
|
590
|
+
from ${t("documents")} d
|
|
591
|
+
left join ${t("protection")} p on p.document_id = d.document_id
|
|
592
|
+
)
|
|
593
|
+
select ${"*"}, a.document_id
|
|
594
|
+
from anc a join prot p on p.document_id = a.ancestor_id
|
|
595
|
+
group by a.document_id
|
|
596
|
+
having bool_and(not p.protected)
|
|
597
|
+
union
|
|
598
|
+
select p.owner_id, p.document_id from prot p where p.owner_id is not null
|
|
599
|
+
union
|
|
600
|
+
select g.user_id, a.document_id
|
|
601
|
+
from anc a join ${t("grants")} g on g.document_id = a.ancestor_id
|
|
602
|
+
`.execute(db);
|
|
603
|
+
}
|
|
604
|
+
async #ensureTables(db) {
|
|
605
|
+
await db.schema.createTable("documents").ifNotExists().addColumn("document_id", "text", (c) => c.primaryKey()).execute();
|
|
606
|
+
await db.schema.createTable("edges").ifNotExists().addColumn("parent_id", "text", (c) => c.notNull()).addColumn("child_id", "text", (c) => c.notNull()).addPrimaryKeyConstraint("edges_pkey", ["parent_id", "child_id"]).execute();
|
|
607
|
+
await db.schema.createIndex("edges_child_idx").ifNotExists().on("edges").column("child_id").execute();
|
|
608
|
+
await db.schema.createTable("protection").ifNotExists().addColumn("document_id", "text", (c) => c.primaryKey()).addColumn("protected", "boolean", (c) => c.notNull()).addColumn("owner_id", "text").execute();
|
|
609
|
+
await db.schema.createTable("grants").ifNotExists().addColumn("document_id", "text", (c) => c.notNull()).addColumn("user_id", "text", (c) => c.notNull()).addPrimaryKeyConstraint("grants_pkey", ["document_id", "user_id"]).execute();
|
|
610
|
+
await db.schema.createTable("readable_documents").ifNotExists().addColumn("user_id", "text", (c) => c.notNull()).addColumn("document_id", "text", (c) => c.notNull()).addPrimaryKeyConstraint("readable_documents_pkey", ["user_id", "document_id"]).execute();
|
|
611
|
+
await db.schema.createIndex("readable_documents_document_idx").ifNotExists().on("readable_documents").column("document_id").execute();
|
|
612
|
+
}
|
|
613
|
+
async #allDocumentIds(pageSize) {
|
|
614
|
+
const ids = [];
|
|
615
|
+
await eachPage(() => this.#deps.read.find({}, { scopes: ["header"] }, {
|
|
616
|
+
cursor: "0",
|
|
617
|
+
limit: pageSize
|
|
618
|
+
}), (page) => {
|
|
619
|
+
for (const doc of page) ids.push(doc.header.id);
|
|
620
|
+
});
|
|
621
|
+
return ids;
|
|
622
|
+
}
|
|
623
|
+
/** `child` edges, found by walking down from every drive. */
|
|
624
|
+
async #allEdges(pageSize) {
|
|
625
|
+
const roots = [];
|
|
626
|
+
for (const type of this.#deps.rootTypes ?? DEFAULT_ROOT_TYPES) await eachPage(() => this.#deps.read.find({ type }, { scopes: ["header"] }, {
|
|
627
|
+
cursor: "0",
|
|
628
|
+
limit: pageSize
|
|
629
|
+
}), (page) => {
|
|
630
|
+
for (const doc of page) roots.push(doc.header.id);
|
|
631
|
+
});
|
|
632
|
+
const edges = [];
|
|
633
|
+
const seen = /* @__PURE__ */ new Set();
|
|
634
|
+
const queue = [...roots];
|
|
635
|
+
while (queue.length > 0) {
|
|
636
|
+
const parent = queue.shift();
|
|
637
|
+
if (seen.has(parent)) continue;
|
|
638
|
+
seen.add(parent);
|
|
639
|
+
await eachPage(() => this.#deps.read.getOutgoingRelationshipEdges(parent, "child", void 0, {
|
|
640
|
+
cursor: "0",
|
|
641
|
+
limit: pageSize
|
|
642
|
+
}), (page) => {
|
|
643
|
+
for (const edge of page) {
|
|
644
|
+
edges.push({
|
|
645
|
+
parent_id: parent,
|
|
646
|
+
child_id: edge.targetId
|
|
647
|
+
});
|
|
648
|
+
if (!seen.has(edge.targetId)) queue.push(edge.targetId);
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
return edges;
|
|
653
|
+
}
|
|
654
|
+
async #snapshotsOf(ids, pageSize) {
|
|
655
|
+
const out = /* @__PURE__ */ new Map();
|
|
656
|
+
const permissions = this.#deps.permissions;
|
|
657
|
+
for (const chunk of chunks(ids, pageSize)) {
|
|
658
|
+
const loaded = await permissions.loadPermissionSnapshots(chunk);
|
|
659
|
+
for (const [id, snapshot] of loaded) {
|
|
660
|
+
if (snapshot.ownerAddress === null && snapshot.grants.size === 0 && snapshot.isProtected === this.#deps.config.defaultProtection) continue;
|
|
661
|
+
out.set(id, snapshot);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
return out;
|
|
665
|
+
}
|
|
666
|
+
#enqueue(task) {
|
|
667
|
+
const run = this.#chain.then(task, task);
|
|
668
|
+
this.#chain = run.catch(() => void 0);
|
|
669
|
+
return run;
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
function edgeOf(event) {
|
|
673
|
+
const parent = event.context?.parentId;
|
|
674
|
+
const child = event.context?.childId;
|
|
675
|
+
return parent && child ? {
|
|
676
|
+
parent_id: parent,
|
|
677
|
+
child_id: child
|
|
678
|
+
} : void 0;
|
|
679
|
+
}
|
|
680
|
+
async function eachPage(first, consume) {
|
|
681
|
+
let page = await first();
|
|
682
|
+
for (;;) {
|
|
683
|
+
consume(page.results);
|
|
684
|
+
if (page.results.length === 0 || !page.next) return;
|
|
685
|
+
page = await page.next();
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
function chunks(items, size) {
|
|
689
|
+
const out = [];
|
|
690
|
+
for (let at = 0; at < items.length; at += size) out.push(items.slice(at, at + size));
|
|
691
|
+
return out;
|
|
692
|
+
}
|
|
693
|
+
//#endregion
|
|
302
694
|
//#region src/services/auth.service.ts
|
|
303
695
|
const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
|
|
304
696
|
const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
|
|
@@ -728,6 +1120,13 @@ var BaseSubgraph = class {
|
|
|
728
1120
|
authorizationService;
|
|
729
1121
|
syncServingGate;
|
|
730
1122
|
/**
|
|
1123
|
+
* The readable-documents read model (`services/readable-documents.ts`):
|
|
1124
|
+
* the host ACL's read closure as rows an index table joins on. Absent on
|
|
1125
|
+
* a host that does not serve it; `readableFilter` then fails closed for
|
|
1126
|
+
* every caller but a listed admin.
|
|
1127
|
+
*/
|
|
1128
|
+
readableDocuments;
|
|
1129
|
+
/**
|
|
731
1130
|
* The host's credential cache, for a package that revokes credentials:
|
|
732
1131
|
* call `this.credentials.invalidateCredential(address, chainId?, appDid?)`
|
|
733
1132
|
* right after the revocation is stored, so this host refuses the credential
|
|
@@ -756,6 +1155,7 @@ var BaseSubgraph = class {
|
|
|
756
1155
|
this.documentPermissionService = args.documentPermissionService;
|
|
757
1156
|
this.authorizationService = args.authorizationService;
|
|
758
1157
|
this.syncServingGate = args.syncServingGate;
|
|
1158
|
+
this.readableDocuments = args.readableDocuments;
|
|
759
1159
|
this.path = args.path ?? "";
|
|
760
1160
|
this.#attachments = args.attachments;
|
|
761
1161
|
this.credentials = args.credentials ?? createCredentialInvalidator(void 0);
|
|
@@ -866,6 +1266,35 @@ var BaseSubgraph = class {
|
|
|
866
1266
|
return readable;
|
|
867
1267
|
}
|
|
868
1268
|
/**
|
|
1269
|
+
* Whether the caller is in the ADMINS list. Not `isSupremeAdmin`: under
|
|
1270
|
+
* OPEN that admits every caller, anonymous included.
|
|
1271
|
+
*/
|
|
1272
|
+
isListedAdmin(ctx) {
|
|
1273
|
+
const address = ctx.user?.address.toLowerCase();
|
|
1274
|
+
return address !== void 0 && this.authorizationService.config.admins.includes(address);
|
|
1275
|
+
}
|
|
1276
|
+
/**
|
|
1277
|
+
* The readable-documents filter for this request's caller, for a query
|
|
1278
|
+
* over an index table keyed by document (`applyReadableFilter`). Without
|
|
1279
|
+
* the read model only a listed admin reads anything: an index must never
|
|
1280
|
+
* serve more than the host would.
|
|
1281
|
+
*/
|
|
1282
|
+
readableFilter(ctx) {
|
|
1283
|
+
if (this.readableDocuments) return this.readableDocuments.filterFor(ctx.user?.address);
|
|
1284
|
+
return this.isListedAdmin(ctx) ? { kind: "all" } : { kind: "none" };
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* The row filter for an index query scoped to one document (its drive or
|
|
1288
|
+
* folder): `none` when the caller may not read the scope itself, the
|
|
1289
|
+
* caller's `readableFilter` otherwise. One call per resolver, then
|
|
1290
|
+
* `applyReadableFilter` on every query it runs.
|
|
1291
|
+
*/
|
|
1292
|
+
async indexAccess(ctx, scopeDocumentId) {
|
|
1293
|
+
const filter = this.readableFilter(ctx);
|
|
1294
|
+
if (filter.kind !== "ids") return filter;
|
|
1295
|
+
return await isDocumentListed(this.relationalDb, filter, scopeDocumentId) ? filter : { kind: "none" };
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
869
1298
|
* The principal a request decides as: the authenticated caller's address, and
|
|
870
1299
|
* the did:key of the app instance whose token authenticated it.
|
|
871
1300
|
*
|
|
@@ -976,9 +1405,13 @@ async function tryNodeSuggestedPaths(packageName, subPath) {
|
|
|
976
1405
|
*/
|
|
977
1406
|
async function tryImportMetaResolve(packageName, subPath) {
|
|
978
1407
|
try {
|
|
979
|
-
|
|
980
|
-
if (
|
|
981
|
-
|
|
1408
|
+
let packageRoot;
|
|
1409
|
+
if (path.isAbsolute(packageName)) packageRoot = packageName;
|
|
1410
|
+
else {
|
|
1411
|
+
const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);
|
|
1412
|
+
if (!resolvedUrl) return null;
|
|
1413
|
+
packageRoot = path.dirname(fileURLToPath(resolvedUrl));
|
|
1414
|
+
}
|
|
982
1415
|
const pathsToTry = [
|
|
983
1416
|
path.join(packageRoot, "dist", "node", subPath, "index.mjs"),
|
|
984
1417
|
path.join(packageRoot, "dist", "node", `${subPath}.mjs`),
|
|
@@ -1058,6 +1491,13 @@ async function loadDocumentModels(packageName) {
|
|
|
1058
1491
|
async function loadSubgraphs(packageName) {
|
|
1059
1492
|
return loadDependency(packageName, "subgraphs");
|
|
1060
1493
|
}
|
|
1494
|
+
/** The header every failed load of a package entry logs, whatever the kind. */
|
|
1495
|
+
function failedLoadHeader(kind) {
|
|
1496
|
+
return `Failed to load ${kind} from @pkg:`;
|
|
1497
|
+
}
|
|
1498
|
+
async function loadScalars(packageName) {
|
|
1499
|
+
return loadDependency(packageName, "scalars");
|
|
1500
|
+
}
|
|
1061
1501
|
/**
|
|
1062
1502
|
* Tries to import processors from a package. This function cannot throw.
|
|
1063
1503
|
*/
|
|
@@ -1373,6 +1813,21 @@ function piecesFromListModule(module, context) {
|
|
|
1373
1813
|
});
|
|
1374
1814
|
}
|
|
1375
1815
|
//#endregion
|
|
1816
|
+
//#region src/packages/scalar-exports.ts
|
|
1817
|
+
function scalarExportsOf(namespace) {
|
|
1818
|
+
return Object.entries(namespace).flatMap(([exportName, value]) => {
|
|
1819
|
+
if (isScalarDefinition(value)) return [{
|
|
1820
|
+
exportName,
|
|
1821
|
+
definition: value
|
|
1822
|
+
}];
|
|
1823
|
+
const version = scalarDefinitionVersion(value);
|
|
1824
|
+
return version === void 0 ? [] : [{
|
|
1825
|
+
exportName,
|
|
1826
|
+
unsupportedVersion: version
|
|
1827
|
+
}];
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
//#endregion
|
|
1376
1831
|
//#region src/packages/subgraph-extraction.ts
|
|
1377
1832
|
/**
|
|
1378
1833
|
* The one acceptance rule for a package's `subgraphs` module.
|
|
@@ -1404,14 +1859,19 @@ function extractSubgraphs(namespace) {
|
|
|
1404
1859
|
const add = (candidate) => {
|
|
1405
1860
|
if (isSubgraphClass(candidate) && !found.includes(candidate)) found.push(candidate);
|
|
1406
1861
|
};
|
|
1407
|
-
for (const value of
|
|
1862
|
+
for (const value of valuesByName(namespace)) {
|
|
1408
1863
|
add(value);
|
|
1409
|
-
if (value !== null && typeof value === "object") for (const inner of
|
|
1864
|
+
if (value !== null && typeof value === "object") for (const inner of valuesByName(value)) add(inner);
|
|
1410
1865
|
}
|
|
1411
1866
|
return found;
|
|
1412
1867
|
}
|
|
1868
|
+
function valuesByName(record) {
|
|
1869
|
+
const keys = Object.keys(record);
|
|
1870
|
+
if (Object.prototype.toString.call(record) === "[object Module]") keys.sort();
|
|
1871
|
+
return keys.map((key) => record[key]);
|
|
1872
|
+
}
|
|
1413
1873
|
//#endregion
|
|
1414
|
-
export {
|
|
1874
|
+
export { RequestClientBinder as A, CanonicalDocumentIdResolutionError as B, loadDocumentModels as C, manifestDeclaredSubgraphs as D, loadSubgraphs as E, READABLE_DOCUMENTS_NAMESPACE as F, AuthEvaluationUnsupportedError as G, AuthorizationPolicy as H, ReadableDocumentsProjection as I, MalformedStoredOperationError as J, AuthenticationRequiredError as K, applyReadableFilter as L, createCredentialInvalidator as M, DEFAULT_ROOT_TYPES as N, BaseSubgraph as O, EVERYONE as P, isDocumentListed as R, isSubpath as S, loadScalars as T, AuthorizedDocumentHandle as U, createCanonicalDocumentIdResolver as V, createAuthorizationService as W, RefusalNotRecordedError as Y, runDetached as _, PIECE_SOURCE_LIST as a, extractUpgradeManifests as b, piecesFromCdnList as c, buildGraphQlDocument as d, buildGraphQlDriveDocument as f, reportFailure as g, isSubgraphClass as h, PIECES_SUBPATH as i, AuthService as j, callerSubject as k, piecesFromListModule as l, buildGraphqlOperations as m, scalarExportsOf as n, packageRootOf as o, buildGraphqlOperation as p, ForbiddenError as q, BUILT_PIECE_LIST as r, pieceListLocation as s, extractSubgraphs as t, extractDocumentModels as u, PACKAGE_MODULE_FAILED as v, loadProcessors as w, failedLoadHeader as x, debounce as y, readableDocumentsSubquery as z };
|
|
1415
1875
|
|
|
1416
|
-
//# sourceMappingURL=subgraph-extraction-
|
|
1417
|
-
//# debugId=
|
|
1876
|
+
//# sourceMappingURL=subgraph-extraction-BA9WKjn1.mjs.map
|
|
1877
|
+
//# debugId=5ecb0ccc-1657-5ac5-9ea4-6a09c1e416e2
|