From 80a04c73daf71ec2ab9cbff481d40da87d38d99c Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Tue, 10 Nov 2026 18:28:49 +0900 Subject: [PATCH 01/10] Add GraphQL reads of resource revisions Resource.currentRevision, Resource.revisions, and the ResourceRevision node return the saved revisions of a resource, including resources saved through the common local write path without legacy typed rows. A revision returns its saved JSON as is, its whiteout details, and what the current validator finds in it. When the validator can read the document, root describes every vocabulary document in it by meaning, whatever keys spell its properties: relations and recipients at any depth, with the resource currently registered under each IRI, and custom extension properties. A document the validator cannot read comes back with interpreted set to false and its diagnostics; nothing falls back to legacy typed rows. Documents are read through interpretDocument() in the new @drfed/federation/document subpath. indexDocument() now uses it as well, so the saved revision index and GraphQL reads cannot disagree. describeDocument() in @drfed/models/document also lists the custom extension property keys of each document it describes. Revisions follow the read rule of their resource, and Relay node lookups of a revision are checked against its resource. Deleting a resource or its author hides none of its revisions, while existing fields such as Resource.detail keep hiding deleted typed rows. Until a rule is settled, the histories of resources without legacy typed rows that hold revisions received from elsewhere stay closed. https://github.com/fedify-dev/drfed/issues/154 The agent in Delta, using Claude Opus 5.5, wrote the implementation, tests, and documentation following the design and access decisions the authors made in discussion, and revised the access rules as they decided. The build, checks, and full test suite were run. Co-authored-by: Hyeonseo Kim Assisted-by: Delta:claude-opus-5-5 --- CHANGES.md | 21 + changes.d/graphql/resource-revisions.md | 16 + .../javascript/document-interpretation.md | 12 + docs/internals/local-writes.md | 15 +- docs/internals/resource-revisions.md | 34 +- packages/federation/README.md | 1 + packages/federation/package.json | 5 + packages/federation/src/document.test.ts | 111 +++ packages/federation/src/document.ts | 35 + packages/federation/src/document/interpret.ts | 264 ++++++ .../federation/src/local-write/prepare.ts | 120 +-- packages/graphql/README.md | 27 + packages/graphql/src/builder.ts | 29 +- packages/graphql/src/readable.ts | 152 ++- packages/graphql/src/resource.ts | 26 +- packages/graphql/src/revision.test.ts | 874 ++++++++++++++++++ packages/graphql/src/revision.ts | 508 ++++++++++ packages/graphql/src/schema.ts | 1 + packages/models/src/document.test.ts | 7 + packages/models/src/document.ts | 10 + 20 files changed, 2123 insertions(+), 145 deletions(-) create mode 100644 changes.d/graphql/resource-revisions.md create mode 100644 changes.d/javascript/document-interpretation.md create mode 100644 packages/federation/src/document.test.ts create mode 100644 packages/federation/src/document.ts create mode 100644 packages/federation/src/document/interpret.ts create mode 100644 packages/graphql/src/revision.test.ts create mode 100644 packages/graphql/src/revision.ts diff --git a/CHANGES.md b/CHANGES.md index 976f408a..66e830a1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -45,10 +45,24 @@ To be released. ### GraphQL APIs + - Added `Resource.currentRevision` and `Resource.revisions`, newest first, + and the `ResourceRevision` node, which return the saved revisions of a + resource, including those of resources saved without legacy details. + Each revision returns its saved JSON, whiteout deletion details, and what + the current validator finds in it. When the validator reads the + document, `root` describes it by meaning, whatever keys spell its + properties: the relations and recipients of the root and of every + document it embeds, with the resource currently registered under each + IRI, and its custom extension properties. Revisions follow the read + rules of their resource; revisions received from elsewhere for a + resource without legacy details are not readable yet. Deleting a + resource or its author hides none of its revisions. [[#154]] - Fixed `Resource.detail` to return `null` without a field error when the resource has no corresponding detail record. [[#150], [#164] by Hong Minhee\] +[#154]: https://github.com/fedify-dev/drfed/issues/154 + ### JavaScript/TypeScript APIs - Added `@drfed/federation/local-write`, the common write operations for @@ -85,6 +99,13 @@ To be released. revision ID is stale, and object histories can end with a whiteout deletion marker. [[#150], [#164] by Hong Minhee\] + - Added the `@drfed/federation/document` subpath. Its + `interpretDocument()` returns every vocabulary document of a saved + document with its relations, recipients, and custom extension + properties, read by meaning as the validator reads them. [[#154]] + - Added `extensionProperties` to the nodes `describeDocument()` in + `@drfed/models/document` returns: the source keys of each document's + custom extension properties. [[#154]] - Added the `@drfed/federation/serving` subpath. It exports `publicDocument()`, the serialization federation reads use for saved documents, `parseVocab()`, which parses such a document into a Fedify diff --git a/changes.d/graphql/resource-revisions.md b/changes.d/graphql/resource-revisions.md new file mode 100644 index 00000000..9d83fe3d --- /dev/null +++ b/changes.d/graphql/resource-revisions.md @@ -0,0 +1,16 @@ +--- +links: + '#154': https://github.com/fedify-dev/drfed/issues/154 +--- + - Added `Resource.currentRevision` and `Resource.revisions`, newest first, + and the `ResourceRevision` node, which return the saved revisions of a + resource, including those of resources saved without legacy details. + Each revision returns its saved JSON, whiteout deletion details, and what + the current validator finds in it. When the validator reads the + document, `root` describes it by meaning, whatever keys spell its + properties: the relations and recipients of the root and of every + document it embeds, with the resource currently registered under each + IRI, and its custom extension properties. Revisions follow the read + rules of their resource; revisions received from elsewhere for a + resource without legacy details are not readable yet. Deleting a + resource or its author hides none of its revisions. [[#154]] diff --git a/changes.d/javascript/document-interpretation.md b/changes.d/javascript/document-interpretation.md new file mode 100644 index 00000000..e1a07702 --- /dev/null +++ b/changes.d/javascript/document-interpretation.md @@ -0,0 +1,12 @@ +--- +links: + '#154': https://github.com/fedify-dev/drfed/issues/154 +--- + - Added the `@drfed/federation/document` subpath. Its + `interpretDocument()` returns every vocabulary document of a saved + document with its relations, recipients, and custom extension + properties, read by meaning as the validator reads them. [[#154]] + + - Added `extensionProperties` to the nodes `describeDocument()` in + `@drfed/models/document` returns: the source keys of each document's + custom extension properties. [[#154]] diff --git a/docs/internals/local-writes.md b/docs/internals/local-writes.md index 476905e8..7abc861c 100644 --- a/docs/internals/local-writes.md +++ b/docs/internals/local-writes.md @@ -136,9 +136,11 @@ from its semantic `to`, `cc`, `bto`, `bcc` and `audience`, each value at its source position: IRIs as resolved, embedded documents by `id`, `Link` values by `href`, also written as a list of one value, and anonymous values without a row. Relations index `actor`, `object`, `target`, `origin`, `result`, `instrument` -and `attributedTo`. A document that spells one of these properties in several -ways is refused, since its index would otherwise leave occurrences out. Indexes -stay `partial`; the documents remain authoritative. +and `attributedTo`. Both indexes come from `interpretDocument()` in +`@drfed/federation/document`, which GraphQL reads use too. A document that +spells one of these properties in several ways is refused, since its index +would otherwise leave occurrences out. Indexes stay `partial`; the documents +remain authoritative. Edits and deletions @@ -156,8 +158,11 @@ A deletion appends a whiteout and keeps the object's current addressing, which describes the last content. The generated `Delete` refers to the object by IRI and copies the last version's addressing under its context. -Resources created by the common write have revisions only, so GraphQL details -ignore them until #154; federation reads serve their documents. Objects created +Resources created by the common write have revisions only, so GraphQL +`Resource.detail` ignores them; `Resource.currentRevision` and +`Resource.revisions` read them, as [resource +revisions](resource-revisions.md#graphql-reads) describe, and federation reads +serve their documents. Objects created by the `createObject` mutation also have legacy typed rows that serving reads; `writeTypedResourceRevision()` keeps those rows in step. Before writing, the served columns must agree with the current revision, or the object is refused diff --git a/docs/internals/resource-revisions.md b/docs/internals/resource-revisions.md index 5a72060e..9e7ed50b 100644 --- a/docs/internals/resource-revisions.md +++ b/docs/internals/resource-revisions.md @@ -215,8 +215,7 @@ generic canonical resource can have no typed detail; its GraphQL such a resource from its current revision. The common write operations described in [local writes](local-writes.md) save new resources as revisions only and keep legacy typed objects in step when editing or deleting -them. Historical authorization and the other federation surfaces are separate -work. +them. The other federation surfaces are separate work. Appending a whiteout does not create or send a `Delete` activity. The common delete operation appends it together with the `Delete`, outbox entry and the @@ -233,3 +232,34 @@ round-trip fixtures, not claims of semantic validation or peer interoperability. Run `mise run test` for PGlite coverage and `mise run test:postgres` with an isolated `DRFED_TEST_POSTGRES_URL` for PostgreSQL migration and concurrency checks. + + +GraphQL reads +------------- + +`Resource.currentRevision`, `Resource.revisions` (newest first by sequence) +and `ResourceRevision` nodes read histories, generic resources included. A +revision returns its saved `document` as is, with blind recipients. Its +`root` and everything below it come from `interpretDocument()` in +`@drfed/federation/document`, which reads every vocabulary document by +meaning through `describeDocument()`; local writes build their revision +indexes with the same function. Relations are read from the document for +every embedded document, not from `revision_relations`, which hold the root's +only. When the validator cannot read the document, such as one whose context is +outside the offline allowlist or one with an unsupported property, +`interpreted` is false, `root` is null and `diagnostics` tell why; nothing +falls back to typed rows. + +Every revision follows the rule of its resource, in `readableHistory()` in +*packages/graphql/src/readable.ts*: the resource must be readable as +`Resource.detail` decides, so local histories are open to anyone. A Relay node +lookup of a revision checks its resource the same way. Deletion hides no +revision: deleting a resource appends a whiteout, and its history, like that of +a resource whose author is deleted, stays readable to whoever may read the +resource, whether or not it has legacy typed rows. Only the existing fields, +such as `Resource.detail`, keep hiding deleted typed rows. Readability is the +existing rule, which reads legacy typed rows. A relation's or recipient's +`resource` is opened as `Activity.object` is, deleted or not. Until the team +decides what opens them, `unprovenGenericHistory()` there closes the histories +of generic resources with a revision not captured locally, while their IRI and +kind stay readable. diff --git a/packages/federation/README.md b/packages/federation/README.md index 8edc3e11..e0d66b4e 100644 --- a/packages/federation/README.md +++ b/packages/federation/README.md @@ -42,6 +42,7 @@ Exports | ------------------------------------- | ------------------------------------------------------------- | | `@drfed/federation` | `createFederation()` (default), `buildFederation()` | | `@drfed/federation/activity-delivery` | Inbound recording, outbound delivery, and their observations | +| `@drfed/federation/document` | `interpretDocument()`, which reads saved documents by meaning | | `@drfed/federation/actor-key` | `ensureActorKeyPairs()` for persisted actor signing keys | | `@drfed/federation/task-queue` | `KeyGenerationQueue` for background actor key generation | | `@drfed/federation/local-write` | Common write operations that save, edit, and delete resources | diff --git a/packages/federation/package.json b/packages/federation/package.json index 22fb75ac..e3215492 100644 --- a/packages/federation/package.json +++ b/packages/federation/package.json @@ -54,6 +54,10 @@ "types": "./dist/object.d.mts", "default": "./dist/object.mjs" }, + "./document": { + "types": "./dist/document.d.mts", + "default": "./dist/document.mjs" + }, "./local-write": { "types": "./dist/local-write.d.mts", "default": "./dist/local-write.mjs" @@ -84,6 +88,7 @@ "src/index.ts", "src/activity-delivery.ts", "src/object.ts", + "src/document.ts", "src/local-write.ts", "src/origin.ts", "src/actor-key.ts", diff --git a/packages/federation/src/document.test.ts b/packages/federation/src/document.test.ts new file mode 100644 index 00000000..0567c061 --- /dev/null +++ b/packages/federation/src/document.test.ts @@ -0,0 +1,111 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import assert from "node:assert/strict"; + +import { interpretDocument } from "@drfed/federation/document"; +import { describe, it } from "@logtape/testing-node/autoload"; + +const AS = "https://www.w3.org/ns/activitystreams"; + +describe("interpretDocument()", () => { + it("reads relations and recipients of every document by meaning", () => { + const document = { + "@context": [ + AS, + { + about: { "@id": "as:object", "@type": "@id" }, + ex: "https://ext.example/ns#", + }, + ], + type: "Undo", + id: "https://example.com/undo", + actor: "https://example.com/alice", + to: [null, "as:Public", { type: "Person" }], + about: [ + { + type: "Like", + actor: "https://example.com/alice", + object: { type: "Link", href: "https://example.com/note" }, + "ex:note": "kept", + }, + "https://example.com/likes/2", + ], + }; + const nodes = interpretDocument(document); + assert.ok(nodes != null); + const [root, like, link] = nodes; + assert.ok(root != null && like != null && link != null); + assert.equal(root.iri, "https://example.com/undo"); + assert.equal(root.value, document); + assert.deepEqual( + root.relations.map(({ property, path, representation, iri, node }) => [ + property, + path, + representation, + iri, + node?.type ?? null, + ]), + [ + ["actor", ["actor"], "reference", "https://example.com/alice", null], + ["object", ["about", 0], "embedded", null, `${AS}#Like`], + [ + "object", + ["about", 1], + "reference", + "https://example.com/likes/2", + null, + ], + ], + ); + // A null names nothing; an anonymous recipient keeps its position. + assert.deepEqual( + root.addressing.map(({ property, position, representation, iri }) => [ + property, + position, + representation, + iri, + ]), + [ + ["to", 1, "reference", `${AS}#Public`], + ["to", 2, "embedded", null], + ], + ); + assert.equal(like.property, "object"); + assert.deepEqual(like.extensions, [{ key: "ex:note", value: "kept" }]); + assert.deepEqual( + like.relations.map(({ property, representation, iri }) => [ + property, + representation, + iri, + ]), + [ + ["actor", "reference", "https://example.com/alice"], + ["object", "link", "https://example.com/note"], + ], + ); + assert.equal(like.relations[1]?.node, link); + assert.equal(link.iri, "https://example.com/note"); + }); + + it("returns null for a document the validator does not read", () => { + assert.equal( + interpretDocument({ "@context": AS, type: "Note", tag: [] }), + null, + ); + assert.equal(interpretDocument(null), null); + }); +}); diff --git a/packages/federation/src/document.ts b/packages/federation/src/document.ts new file mode 100644 index 00000000..5aa094ee --- /dev/null +++ b/packages/federation/src/document.ts @@ -0,0 +1,35 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +/** + * The interpretation of saved documents by meaning: the relations, + * recipients and extension properties of the root and of every document it + * embeds, as the validator reads them. The indexes local writes save and the + * GraphQL read surface share it, so that they cannot disagree. Nothing here + * dereferences anything. + * @module + */ + +export { + type InterpretedNode, + RELATION_PROPERTIES, + type RecipientOccurrence, + type RecipientProperty, + type RelationOccurrence, + type RelationProperty, + type Representation, + interpretDocument, +} from "./document/interpret.ts"; diff --git a/packages/federation/src/document/interpret.ts b/packages/federation/src/document/interpret.ts new file mode 100644 index 00000000..2fbed966 --- /dev/null +++ b/packages/federation/src/document/interpret.ts @@ -0,0 +1,264 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { + ADDRESSING_PROPERTIES, + type DocumentNode, + type DocumentNodeKind, + type FieldPath, + type JsonValue, + describeDocument, +} from "@drfed/models/document"; + +/** + * The relations a document's own properties hold, which saved revisions + * index at their root: who acts, what it acts on, and who it is attributed + * to. + */ +export const RELATION_PROPERTIES = [ + "actor", + "object", + "target", + "origin", + "result", + "instrument", + "attributedTo", +] as const; + +/** The standard name of a relation property. */ +export type RelationProperty = (typeof RELATION_PROPERTIES)[number]; + +/** The standard name of an addressing property. */ +export type RecipientProperty = (typeof ADDRESSING_PROPERTIES)[number]; + +/** + * How a value names what it stands for: an IRI reference, an embedded + * document, or an embedded `Link`. + */ +export type Representation = "reference" | "embedded" | "link"; + +/** + * One vocabulary document of a saved document, the root or one embedded at + * any depth, as {@link interpretDocument} reads it by meaning. + */ +export interface InterpretedNode { + /** The source path of the document; `[]` is the root. */ + readonly path: FieldPath; + /** + * The standard name of the property that embeds the document, whatever + * its source spelling; `null` for the root. + */ + readonly property: string | null; + /** The type IRI, such as `…/activitystreams#Note`. */ + readonly type: string; + readonly kind: DocumentNodeKind; + /** + * The document's own `id`, or the `href` of a `Link`, with a compact IRI + * expanded; `null` when it has none. + */ + readonly iri: string | null; + /** The document's JSON as saved, with everything it embeds. */ + readonly value: JsonValue; + /** + * The occurrences of its own relation properties, in the order of + * {@link RELATION_PROPERTIES}, then of their source keys and values, + * including duplicates. + */ + readonly relations: readonly RelationOccurrence[]; + /** + * The occurrences of its own addressing properties, in the order of + * `ADDRESSING_PROPERTIES`, then of their source keys and values, + * including duplicates and anonymous embedded recipients. + */ + readonly addressing: readonly RecipientOccurrence[]; + /** + * Its own custom extension properties, by their source keys, sorted, with + * their values as saved. + */ + readonly extensions: readonly { + readonly key: string; + readonly value: JsonValue; + }[]; +} + +/** One value of a relation or addressing property. */ +interface Occurrence { + /** The source path of the value, including its list index if any. */ + readonly path: FieldPath; + readonly representation: Representation; + /** + * A reference as resolved, an embedded document's `id`, or a `Link`'s + * `href`; `null` for an anonymous embedded value. + */ + readonly iri: string | null; + /** The embedded document or `Link`; `null` for a reference. */ + readonly node: InterpretedNode | null; +} + +/** One value of a relation property. */ +export interface RelationOccurrence extends Occurrence { + readonly property: RelationProperty; +} + +/** One value of an addressing property. */ +export interface RecipientOccurrence extends Occurrence { + readonly property: RecipientProperty; + /** + * The index of the value in its source key's list, or 0 for a value + * written alone. + */ + readonly position: number; +} + +const pathKey = (path: FieldPath): string => JSON.stringify(path); + +/** + * Reads the value at a source path. Paths come from documents whose keys + * may be spelled `__proto__`, so only own properties are read. + * @returns The value, or `undefined` when nothing is there. + */ +export function valueAt( + document: JsonValue, + path: FieldPath, +): JsonValue | undefined { + let value: JsonValue | undefined = document; + for (const segment of path) { + if ( + value === null || + typeof value !== "object" || + !Object.hasOwn(value, segment) + ) { + return undefined; + } + value = (value as Record)[segment]; + } + return value; +} + +// A document names itself by its id; a Link by its href. A node's +// identifiers are its own values only. +const ownIri = (node: DocumentNode): string | null => + node.identifiers.find( + ({ property }) => property === (node.kind === "link" ? "href" : "id"), + )?.iri ?? null; + +interface MutableNode extends InterpretedNode { + relations: RelationOccurrence[]; + addressing: RecipientOccurrence[]; +} + +/** + * Interprets a saved document by meaning, through `describeDocument()`, so + * that aliases, full-IRI keys and compact IRIs read as the validator reads + * them, never by key spelling. The relations and recipients of every + * vocabulary document are read, not only of the root: the `object` of a + * `Like` embedded in an `Undo`, for one. Saved indexes and read surfaces + * share it, so that they cannot disagree about what a document says. + * + * A value of a relation or addressing property is a reference when it is an + * IRI, or an embedded document or `Link`. A `null` in a list, which names + * nothing, is no occurrence, and positions in a list are kept as written. + * @param document A saved document. + * @returns The root and every embedded document in traversal order, or + * `null` when `describeDocument()` cannot read the document, that + * is, unless it validates without errors. + */ +export function interpretDocument( + document: unknown, +): readonly InterpretedNode[] | null { + const described = describeDocument(document); + if (described == null || described.length === 0) return null; + // Validation has accepted it as JSON. + const json = document as JsonValue; + const nodes = new Map( + described.map((node) => [ + pathKey(node.path), + { + path: node.path, + property: node.property ?? null, + type: node.type, + kind: node.kind, + iri: ownIri(node), + value: valueAt(json, node.path) ?? null, + relations: [], + addressing: [], + extensions: node.extensionProperties.map((key) => ({ + key, + value: valueAt(json, [...node.path, key]) ?? null, + })), + }, + ]), + ); + for (const node of described) { + const interpreted = nodes.get(pathKey(node.path))!; + const references = new Map( + node.identifiers.map(({ path, iri }) => [pathKey(path), iri]), + ); + const occurrences = ( + property: string, + ): (Occurrence & { readonly position: number })[] => + (node.properties.get(property) ?? []).flatMap((source) => { + const path = [...node.path, source]; + const value = valueAt(json, path); + const entries: [FieldPath, number][] = Array.isArray(value) + ? value.map((_, position) => [[...path, position], position]) + : value == null + ? [] + : [[path, 0]]; + return entries.flatMap( + ([entryPath, position]): (Occurrence & { + readonly position: number; + })[] => { + const child = nodes.get(pathKey(entryPath)); + if (child != null) { + return [ + { + path: entryPath, + position, + representation: child.kind === "link" ? "link" : "embedded", + iri: child.iri, + node: child, + }, + ]; + } + const iri = references.get(pathKey(entryPath)); + return iri == null + ? [] + : [ + { + path: entryPath, + position, + representation: "reference", + iri, + node: null, + }, + ]; + }, + ); + }); + for (const property of RELATION_PROPERTIES) { + for (const { position: _, ...occurrence } of occurrences(property)) { + interpreted.relations.push({ property, ...occurrence }); + } + } + for (const property of ADDRESSING_PROPERTIES) { + for (const occurrence of occurrences(property)) { + interpreted.addressing.push({ property, ...occurrence }); + } + } + } + return [...nodes.values()]; +} diff --git a/packages/federation/src/local-write/prepare.ts b/packages/federation/src/local-write/prepare.ts index 86dcd522..1179e23c 100644 --- a/packages/federation/src/local-write/prepare.ts +++ b/packages/federation/src/local-write/prepare.ts @@ -34,6 +34,11 @@ import { type Uuid, uuidV7, validateUuid } from "@drfed/models/uuid"; import type { Federation } from "@fedify/fedify"; import { Object as APObject, Activity, Create } from "@fedify/vocab"; +import { + RELATION_PROPERTIES, + interpretDocument, + valueAt, +} from "../document/interpret.ts"; import { classifyHost } from "../origin.ts"; import type { WritingActor } from "./actor.ts"; import { type Allocation, toMicroseconds } from "./token.ts"; @@ -57,15 +62,6 @@ const NESTING_PROPERTIES: ReadonlySet = new Set([ "result", "instrument", ]); -const RELATION_PROPERTIES = [ - "actor", - "object", - "target", - "origin", - "result", - "instrument", - "attributedTo", -] as const; /** Database answers the preparation needs about local identities. */ export interface IdentityLookups { @@ -251,22 +247,7 @@ export function allocate(resources: readonly NewResource[]): Allocation { } // Paths come from submitted documents, whose keys may be spelled -// `__proto__`; only own properties are read or defined. -function valueAt(document: JsonValue, path: FieldPath): JsonValue | undefined { - let value: JsonValue | undefined = document; - for (const segment of path) { - if ( - value === null || - typeof value !== "object" || - !Object.hasOwn(value, segment) - ) { - return undefined; - } - value = (value as Record)[segment]; - } - return value; -} - +// `__proto__`; only own properties are defined. function setAt(document: JsonObject, path: FieldPath, value: JsonValue): void { const parent = valueAt(document, path.slice(0, -1)); if (parent === null || typeof parent !== "object") { @@ -408,83 +389,32 @@ export function checkIndexable(document: JsonObject): Diagnostic[] { } /** - * Indexes a saved document's root addressing and relations by meaning. - * @returns Addressing occurrences at their source positions, and relations. + * Indexes a saved document's root addressing and relations by meaning, as + * `interpretDocument()` reads them for every document it embeds as well. + * Several spellings of one property must have been refused by + * {@link checkIndexable}, or their positions would collide. + * @returns Addressing occurrences at their source positions, without + * anonymous recipients, and relations. */ export function indexDocument(document: JsonObject): { addressing: AddressingOccurrence[]; relations: RevisionRelationInput[]; } { - const nodes = describeDocument(document) ?? []; - const root = nodes.find(({ path }) => path.length === 0); + const root = interpretDocument(document)?.[0]; if (root == null) return { addressing: [], relations: [] }; - const children = new Map(nodes.map((node) => [pathKey(node.path), node])); - const identifiers = new Map( - root.identifiers.map((entry) => [pathKey(entry.path), entry.iri]), - ); - // An embedded document names a target by its id; a Link by its href. - const target = (path: FieldPath): string | undefined => { - const fromRoot = identifiers.get(pathKey(path)); - if (fromRoot != null) return fromRoot; - const node = children.get(pathKey(path)); - if (node == null) return undefined; - const property = node.kind === "link" ? "href" : "id"; - // A functional property may be a list with one non-null entry. - return node.identifiers.find( - (entry) => - entry.property === property && - (entry.path.length === path.length + 1 || - (entry.path.length === path.length + 2 && - typeof entry.path.at(-1) === "number")), - )?.iri; - }; - const occurrences = ( - property: string, - ): { path: FieldPath; position: number }[] => { - // Several spellings of one property were refused by checkIndexable(). - const source = root.properties.get(property)?.[0]; - if (source == null) return []; - const value = document[source]; - if (Array.isArray(value)) { - return value.map((_, position) => ({ - path: [source, position], - position, - })); - } - return value == null ? [] : [{ path: [source], position: 0 }]; + return { + addressing: root.addressing.flatMap(({ property, position, iri }) => + iri == null ? [] : [{ property, position, iri }], + ), + relations: root.relations.map( + ({ property, path, representation, iri }) => ({ + property, + path, + representation, + targetIri: iri, + }), + ), }; - const addressing: AddressingOccurrence[] = []; - for (const property of ADDRESSING_PROPERTIES) { - for (const { path, position } of occurrences(property)) { - const iri = target(path); - if (iri != null) addressing.push({ property, position, iri }); - } - } - const relations: RevisionRelationInput[] = []; - for (const property of RELATION_PROPERTIES) { - for (const { path } of occurrences(property)) { - const node = children.get(pathKey(path)); - if (node == null) { - const iri = identifiers.get(pathKey(path)); - if (iri != null) { - relations.push({ - property, - path, - representation: "reference", - targetIri: iri, - }); - } - } else { - relations.push({ - property, - path, - representation: node.kind === "link" ? "link" : "embedded", - targetIri: target(path) ?? null, - }); - } - } - } - return { addressing, relations }; } /** diff --git a/packages/graphql/README.md b/packages/graphql/README.md index 57b94a7c..c863dba2 100644 --- a/packages/graphql/README.md +++ b/packages/graphql/README.md @@ -82,6 +82,33 @@ before paging, so that neither cursors nor `totalCount` tell of it. [ActivityPub]: https://www.w3.org/TR/activitypub/ +Resource revisions +------------------ + +`Resource.currentRevision` and `Resource.revisions`, newest first, return the +saved revisions of any resource, including those saved without legacy +details; `node` and `nodes` look up a `ResourceRevision` by its ID. +`ResourceRevision.document` is the saved JSON as is, and `root` describes it +by meaning: each `DocumentNode`, the root or one embedded at any depth, has +its type IRI, its own `id` or `href`, its relations and recipients in source +order, and its custom extension properties. A relation or recipient names +the resource currently registered under its IRI, opened as +`Activity.object` is, while `node` keeps the embedded value as saved. When +the validator cannot read the document, `interpreted` is false and +`diagnostics` tell why. + +A revision, past ones included, is readable exactly when its resource is, as +above. Deletion hides no revision: deleting a resource appends a whiteout +and leaves the history before it readable, and deleting its author hides +none of it either, while `Resource.detail` and the other existing fields +keep hiding what was deleted. Local +histories, blind recipients included, are readable by anyone. The histories +of resources without legacy details that hold revisions received from +elsewhere are closed for now. See [resource revision internals]. + +[resource revision internals]: https://drfed.org/internals/resource-revisions#graphql-reads + + Login mail and shutdown ----------------------- diff --git a/packages/graphql/src/builder.ts b/packages/graphql/src/builder.ts index 96338ff3..fb27a857 100644 --- a/packages/graphql/src/builder.ts +++ b/packages/graphql/src/builder.ts @@ -31,7 +31,11 @@ import { GraphQLScalarType, Kind } from "graphql"; import { JSONResolver, URLResolver, UUIDResolver } from "graphql-scalars"; import OperationsPlugin, { type OperationTracker } from "./operations.ts"; -import { hideUnreadableNodes, memberInstances } from "./readable.ts"; +import { + hideUnreadableNodes, + memberInstances, + owningResourceOf, +} from "./readable.ts"; /** * The context data for the GraphQL server, which includes the incoming request @@ -173,18 +177,13 @@ export const builder = new SchemaBuilder({ relay: { nodeQueryOptions: { resolve: async (_, { id }, ctx, __, resolveNode) => { - const [node] = await hideUnreadableNodes(ctx, [ - filterDeleted(await resolveNode(id)), - ]); + const [node] = await hideHiddenNodes(ctx, [await resolveNode(id)]); return node; }, }, nodesQueryOptions: { resolve: async (_, { ids }, ctx, __, resolveNodes) => - await hideUnreadableNodes( - ctx, - (await resolveNodes(ids)).map(filterDeleted), - ), + await hideHiddenNodes(ctx, await resolveNodes(ids)), }, }, scopeAuth: { @@ -224,6 +223,20 @@ const filterDeleted = (node: unknown): unknown => ? null : node; +// A node that belongs to a resource, such as a revision, is hidden as that +// resource is, by hideUnreadableNodes(); its own deletion time, as that of a +// whiteout, tells of the history it records and hides nothing. +const hideHiddenNodes = ( + context: UserContext, + nodes: readonly unknown[], +): Promise => + hideUnreadableNodes( + context, + nodes.map((node) => + owningResourceOf(node) == null ? filterDeleted(node) : node, + ), + ); + /** * Determines whether the viewer is an accepted member of the `Instance` that * the given `LocalInstance` backs. Pending members, i.e. those who have been diff --git a/packages/graphql/src/readable.ts b/packages/graphql/src/readable.ts index be45ec8d..f64dd5b3 100644 --- a/packages/graphql/src/readable.ts +++ b/packages/graphql/src/readable.ts @@ -22,9 +22,11 @@ import { activityDeliveries, actors, addressing, + collections, instanceMembers, instances, objects, + resourceRevisions, resources, } from "@drfed/models/schema"; import { type Uuid, validateUuid } from "@drfed/models/uuid"; @@ -116,6 +118,15 @@ const carriers = alias(activities, "readable_carriers"); const entries = alias(addressing, "readable_addressing"); const targets = alias(resources, "readable_targets"); const deliveries = alias(activityDeliveries, "readable_deliveries"); +const visibleOwners = alias(actors, "visible_owners"); +const ownedObjects = alias(objects, "visible_objects"); +const ownedActivities = alias(activities, "visible_activities"); +const ownedCollections = alias(collections, "visible_collections"); +const typedActors = alias(actors, "history_actors"); +const typedObjects = alias(objects, "history_objects"); +const typedActivities = alias(activities, "history_activities"); +const typedCollections = alias(collections, "history_collections"); +const capturedRevisions = alias(resourceRevisions, "history_revisions"); const remoteActivity = (id: SQLWrapper): SQL => sql`exists ( select 1 from ${activities} ${remoteActivities} @@ -200,6 +211,94 @@ export function readableResource(viewer: Viewer, id: SQLWrapper): SQL { return sql`(${readableActivity(viewer, id)} and ${readableObject(viewer, id)})`; } +/** + * Excludes deleted actors and objects, including resources authored or + * owned by deleted actors. Revisions do not use it: a deletion appends a + * whiteout, and the history before it stays readable, as + * {@link readableHistory} tells. + * @param id The resource ID in an outer query. + * @returns The condition on the ID. + */ +export function visibleResource(id: SQLWrapper): SQL { + return sql`not exists ( + select 1 from ${actors} ${visibleOwners} + where ${visibleOwners.id} = ${id} and ${visibleOwners.deleted} is not null + ) and not exists ( + select 1 from ${objects} ${ownedObjects} + join ${actors} ${visibleOwners} on ${visibleOwners.id} = ${ownedObjects.actorId} + where ${ownedObjects.id} = ${id} + and (${ownedObjects.deleted} is not null or ${visibleOwners.deleted} is not null) + ) and not exists ( + select 1 from ${activities} ${ownedActivities} + join ${actors} ${visibleOwners} on ${visibleOwners.id} = ${ownedActivities.actorId} + where ${ownedActivities.id} = ${id} and ${visibleOwners.deleted} is not null + ) and not exists ( + select 1 from ${collections} ${ownedCollections} + join ${actors} ${visibleOwners} on ${visibleOwners.id} = ${ownedCollections.ownerActorId} + where ${ownedCollections.id} = ${id} and ${visibleOwners.deleted} is not null + )`; +} + +/** + * Matches a generic resource, one without a legacy typed row, with a + * revision DrFed did not save itself: received, embedded or fetched. + * + * PENDING TEAM DECISION: no evidence opens such a history yet, since the + * rules of {@link readableResource} are those of typed rows, and no write + * path creates such resources yet. Until the team decides what opens them, + * their revisions are closed, while the resource itself, its IRI and kind, + * stays readable as before. This is the one place that rule lives; + * {@link readableHistory} applies it. + * @param id The resource ID in an outer query. + * @returns The condition on the ID. + */ +export function unprovenGenericHistory(id: SQLWrapper): SQL { + return sql`(not ${legacyTypedRow(id)} and exists ( + select 1 from ${resourceRevisions} ${capturedRevisions} + where ${capturedRevisions.resourceId} = ${id} + and ${capturedRevisions.capture} <> 'local' + ))`; +} + +/** + * Matches a resource with a legacy typed row, whose readability + * {@link readableResource} decides by that row. It is the only place + * {@link unprovenGenericHistory} reads legacy typed tables, so that it goes + * when they do. + * @param id The resource ID in an outer query. + * @returns The condition on the ID. + */ +function legacyTypedRow(id: SQLWrapper): SQL { + return sql`(exists ( + select 1 from ${actors} ${typedActors} where ${typedActors.id} = ${id} + ) or exists ( + select 1 from ${objects} ${typedObjects} where ${typedObjects.id} = ${id} + ) or exists ( + select 1 from ${activities} ${typedActivities} where ${typedActivities.id} = ${id} + ) or exists ( + select 1 from ${collections} ${typedCollections} where ${typedCollections.id} = ${id} + ))`; +} + +/** + * Restricts resources to those whose revisions the viewer may read. Every + * revision, past ones included, follows the rule of its resource: it must be + * readable, as {@link readableResource} tells, and its history must not be + * one {@link unprovenGenericHistory} closes. Local resources are therefore + * readable by anyone, with their blind recipients and whether published or + * not, as `Object.document` is. Deletion hides no revision: it appends a + * whiteout, and the history before it, of a deleted resource or of one + * whose author is deleted, stays readable to whoever may read the resource. + * Readability is the existing rule, which still reads legacy typed rows; + * everything else about revisions is read from the revisions themselves. + * @param viewer The viewer and the database. + * @param id The resource ID in an outer query. + * @returns The condition on the ID. + */ +export function readableHistory(viewer: Viewer, id: SQLWrapper): SQL { + return and(readableResource(viewer, id), not(unprovenGenericHistory(id)))!; +} + /** * Finds the resources among the given IDs that the viewer may not read, as * {@link readableResource} decides. IDs of anything but a resource are never @@ -232,30 +331,63 @@ export const isReadableResource = async ( id: Uuid, ): Promise => !(await unreadableResources(viewer, [id])).has(id); -const nodeIdOf = (node: unknown): Uuid | null => +const uuidOf = (node: unknown, key: "id" | "resourceId"): Uuid | null => node != null && typeof node === "object" && - "id" in node && - validateUuid(node.id) - ? node.id + key in node && + validateUuid((node as Record)[key]) + ? ((node as Record)[key] as Uuid) : null; +/** + * Tells the resource a Relay node belongs to without being its typed detail, + * as a revision belongs to its resource. Such a node is hidden as that + * resource's history is, by {@link readableHistory}, and nothing of its own, + * such as a whiteout's deletion time, hides it. + * @returns The resource ID, or null for any other node. + */ +export const owningResourceOf = (node: unknown): Uuid | null => + uuidOf(node, "resourceId"); + /** * Replaces the Relay nodes the viewer may not read by null, as if they did * not exist. Activities, objects, and resources share their IDs, so a node's - * ID alone tells whether it is one the viewer may not read. + * ID alone tells whether it is one the viewer may not read; a node that + * belongs to a resource, such as a revision, is checked against that + * resource's history instead, as {@link owningResourceOf} tells. * @returns The nodes, in the same order. */ export async function hideUnreadableNodes( viewer: Viewer, nodes: readonly unknown[], ): Promise { - const hidden = await unreadableResources( - viewer, - nodes.map(nodeIdOf).filter((id) => id != null), + const owningIds = nodes.map(owningResourceOf); + const ids = nodes.map((node, index) => + owningIds[index] == null ? uuidOf(node, "id") : null, ); - return nodes.map((node) => { - const id = nodeIdOf(node); + const owned = [...new Set(owningIds.filter((id) => id != null))]; + const [hidden, readableOwners] = await Promise.all([ + unreadableResources( + viewer, + ids.filter((id) => id != null), + ), + owned.length === 0 + ? [] + : viewer.db + .select({ id: resources.id }) + .from(resources) + .where( + and( + inArray(resources.id, owned), + readableHistory(viewer, resources.id), + ), + ), + ]); + const open = new Set(readableOwners.map(({ id }) => id)); + return nodes.map((node, index) => { + const owner = owningIds[index]; + if (owner != null) return open.has(owner) ? node : null; + const id = ids[index]; return id != null && hidden.has(id) ? null : node; }); } diff --git a/packages/graphql/src/resource.ts b/packages/graphql/src/resource.ts index d7218b2c..6a2c7f52 100644 --- a/packages/graphql/src/resource.ts +++ b/packages/graphql/src/resource.ts @@ -33,6 +33,7 @@ import { type Viewer, isReadableResource, readableResource, + visibleResource, } from "./readable.ts"; export const ResourceKind = builder.enumType("ResourceKind", { @@ -414,28 +415,3 @@ const ActivityRef = builder.drizzleNode("activities", { }); export const Activity: DrFedObjectRef = ActivityRef; registerAddressingFields("activities"); - -/** - * Excludes deleted actors and objects, including resources authored or - * owned by deleted actors. - * @returns A predicate for a resource ID in an outer query. - */ -function visibleResource(id: SQLWrapper): SQL { - return sql`not exists ( - select 1 from ${schema.actors} - where ${schema.actors.id} = ${id} and ${schema.actors.deleted} is not null - ) and not exists ( - select 1 from ${schema.objects} - join ${schema.actors} on ${schema.actors.id} = ${schema.objects.actorId} - where ${schema.objects.id} = ${id} - and (${schema.objects.deleted} is not null or ${schema.actors.deleted} is not null) - ) and not exists ( - select 1 from ${schema.activities} - join ${schema.actors} on ${schema.actors.id} = ${schema.activities.actorId} - where ${schema.activities.id} = ${id} and ${schema.actors.deleted} is not null - ) and not exists ( - select 1 from ${schema.collections} - join ${schema.actors} on ${schema.actors.id} = ${schema.collections.ownerActorId} - where ${schema.collections.id} = ${id} and ${schema.actors.deleted} is not null - )`; -} diff --git a/packages/graphql/src/revision.test.ts b/packages/graphql/src/revision.test.ts new file mode 100644 index 00000000..44a8ab6f --- /dev/null +++ b/packages/graphql/src/revision.test.ts @@ -0,0 +1,874 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Writes and pages depend on the ones before them. +// oxlint-disable no-await-in-loop +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { + type CreateRequest, + type JsonObject, + type LocalWriteEnvironment, + type LocalWriteRequest, + commitLocalWrite, + previewLocalWrite, +} from "@drfed/federation/local-write"; +import { type Database, schema } from "@drfed/models"; +import { PUBLIC_IRI, ensureResource } from "@drfed/models/resource"; +import { + appendResourceRevision, + captureLegacyResourceRevision, + loadCurrentResourceRevision, + writeTypedResourceRevision, +} from "@drfed/models/resource-revision"; +import { type Uuid, uuidV7 } from "@drfed/models/uuid"; +import { eq } from "drizzle-orm"; + +import { type TestHarness, withTestHarness } from "./harness.test.ts"; +import { + accountId, + globalId, + localActorId, + remoteActorId, + seedAuthenticatedLocalInstance, + seedLocalActor, + seedObjects, + seedRemoteActor, +} from "./seed.test.ts"; + +const AS = "https://www.w3.org/ns/activitystreams"; +const ACTOR_IRI = `https://test-instance.drfed.org/users/${localActorId}`; +const FEATURED_IRI = `${ACTOR_IRI}/featured`; +const BLIND = "https://remote.example/users/blind"; +const PRINCIPAL = { accountId: accountId as Uuid }; + +const revisionId = (id: string): string => + Buffer.from(`ResourceRevision:${id}`).toString("base64"); + +interface Writer { + readonly harness: TestHarness; + readonly auth: RequestInit; + /** Saves new resources and returns their IDs and IRIs, root last. */ + save( + document: JsonObject, + resources?: CreateRequest["resources"], + ): Promise<{ id: Uuid; iri: string }[]>; + /** Commits an edit or deletion. */ + change(request: LocalWriteRequest): Promise; + /** Sends a query, anonymously unless `init` authenticates it. */ + query( + query: string, + variables?: Record, + init?: RequestInit, + ): Promise<{ data?: Record; errors?: unknown[] }>; +} + +async function withWriter( + // oxlint-disable-next-line promise/prefer-await-to-callbacks + callback: (writer: Writer) => Promise, +): Promise { + await withTestHarness(async (harness) => { + const auth = await seedAuthenticatedLocalInstance(harness.db); + await seedLocalActor(harness.db); + const env: LocalWriteEnvironment = { + db: harness.db, + federation: harness.federation, + rootOrigin: new URL("https://drfed.org"), + previewKey: await crypto.subtle.generateKey( + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign", "verify"], + ), + }; + const commit = async (request: LocalWriteRequest) => { + const preview = await previewLocalWrite(env, PRINCIPAL, request); + assert.ok(preview.ok, JSON.stringify(!preview.ok && preview.error)); + const outcome = await commitLocalWrite(env, PRINCIPAL, request, { + previewToken: preview.preview.token, + // Edits and deletions require a reservation; nothing is sent here. + ...(request.operation === "create" + ? {} + : { reserveDispatch: () => Promise.resolve() }), + }); + assert.ok(outcome.ok, JSON.stringify(!outcome.ok && outcome.error)); + return outcome.result; + }; + // oxlint-disable-next-line promise/prefer-await-to-callbacks, node/callback-return + await callback({ + harness, + auth, + async save(document, resources = [{ path: [], kind: "object" }]) { + const result = await commit({ + operation: "create", + actorId: localActorId, + document: { "@context": AS, ...document }, + resources, + }); + return result.resources.map(({ id, iri }) => ({ id, iri })); + }, + async change(request) { + await commit(request); + }, + async query(query, variables, init) { + const response = await harness.post( + { query, variables: variables ?? {} }, + init, + ); + return await response.json(); + }, + }); + }); +} + +async function head(db: Database, id: Uuid) { + const revision = await loadCurrentResourceRevision(db, id); + assert.ok(revision != null); + return revision; +} + +const edit = ( + objectId: Uuid, + expectedRevisionId: Uuid, + document: JsonObject, +): LocalWriteRequest => ({ + operation: "edit", + actorId: localActorId, + objectId, + expectedRevisionId, + document, +}); + +const currentRoot = (selection: string): string => + `query($id: ID!) { node(id: $id) { ... on Resource { currentRevision { root { ${selection} } } } } }`; + +describe("Resource.currentRevision", () => { + it("reads relations of embedded documents, as the Like in an Undo", async () => { + await withWriter(async ({ save, query }) => { + const [note] = await save({ type: "Note", content: "liked" }); + assert.ok(note != null); + const [undo] = await save( + { + type: "Undo", + object: { type: "Like", actor: ACTOR_IRI, object: note.iri }, + }, + [{ path: [], kind: "activity" }], + ); + assert.ok(undo != null); + const body = await query( + currentRoot(` + type kind iri + relations(property: object) { + property path representation iri resource { iri } + node { + path property type kind iri + relations(property: object) { + path representation iri node { type } + resource { iri kind currentRevision { root { type } } } + } + } + }`), + { id: globalId("Resource", undo.id) }, + ); + assert.equal(body.errors, undefined); + assert.deepEqual(body.data?.node.currentRevision.root, { + type: `${AS}#Undo`, + kind: "activity", + iri: undo.iri, + relations: [ + { + property: "object", + path: ["object"], + representation: "embedded", + iri: null, + resource: null, + node: { + path: ["object"], + property: "object", + type: `${AS}#Like`, + kind: "activity", + iri: null, + relations: [ + { + path: ["object", "object"], + representation: "reference", + iri: note.iri, + node: null, + resource: { + iri: note.iri, + kind: "object", + currentRevision: { root: { type: `${AS}#Note` } }, + }, + }, + ], + }, + }, + ], + }); + }); + }); + + it("keeps an embedded version while the resource shows its edited one", async () => { + await withWriter(async ({ harness, save, change, query }) => { + const [note, create] = await save( + { + type: "Create", + to: [PUBLIC_IRI], + object: { type: "Note", content: "A", to: [PUBLIC_IRI] }, + }, + [ + { path: [], kind: "activity" }, + { path: ["object"], kind: "object" }, + ], + ); + assert.ok(note != null && create != null); + const saved = await head(harness.db, note.id); + await change( + edit(note.id, saved.id, { + ...(saved.document as JsonObject), + content: "B", + }), + ); + const body = await query( + currentRoot(`relations(property: object) { + representation iri + node { document } + resource { currentRevision { sequence document } } + }`), + { id: globalId("Resource", create.id) }, + ); + assert.equal(body.errors, undefined); + assert.ok(body.data != null); + const [relation] = body.data.node.currentRevision.root.relations; + assert.equal(relation.representation, "embedded"); + assert.equal(relation.iri, note.iri); + assert.equal(relation.node.document.content, "A"); + assert.equal(relation.resource.currentRevision.sequence, 2); + assert.equal(relation.resource.currentRevision.document.content, "B"); + }); + }); + + it("reads no object of an intransitive activity", async () => { + await withWriter(async ({ save, query }) => { + const [arrive] = await save({ type: "Arrive" }, [ + { path: [], kind: "activity" }, + ]); + assert.ok(arrive != null); + const body = await query( + currentRoot(` + objects: relations(property: object) { iri } + actors: relations(property: actor) { + representation iri resource { kind } + }`), + { id: globalId("Resource", arrive.id) }, + ); + assert.deepEqual(body, { + data: { + node: { + currentRevision: { + root: { + objects: [], + actors: [ + { + representation: "reference", + iri: ACTOR_IRI, + resource: { kind: "actor" }, + }, + ], + }, + }, + }, + }, + }); + }); + }); + + it("reads the collection target of an Add", async () => { + await withWriter(async ({ save, query }) => { + const [note] = await save({ type: "Note", content: "featured" }); + assert.ok(note != null); + const [add] = await save( + { + type: "Add", + object: note.iri, + target: { type: "OrderedCollection", id: FEATURED_IRI }, + }, + [{ path: [], kind: "activity" }], + ); + assert.ok(add != null); + const body = await query( + currentRoot(`relations(property: target) { + representation iri node { kind type } resource { kind iri } + }`), + { id: globalId("Resource", add.id) }, + ); + assert.deepEqual(body.data?.node.currentRevision.root.relations, [ + { + representation: "embedded", + iri: FEATURED_IRI, + node: { kind: "collection", type: `${AS}#OrderedCollection` }, + resource: { kind: "collection", iri: FEATURED_IRI }, + }, + ]); + }); + }); + + it("tells unregistered IRIs from registered ones of an unknown kind", async () => { + await withWriter(async ({ harness, save, query }) => { + const unregistered = "https://remote.example/unregistered"; + const unknown = "https://remote.example/unknown"; + await ensureResource(harness.db, unknown); + const [undo] = await save( + { + type: "Undo", + object: [ + { type: "Like", object: unregistered }, + { type: "Like", object: unknown }, + ], + }, + [{ path: [], kind: "activity" }], + ); + assert.ok(undo != null); + const body = await query( + currentRoot(`relations(property: object) { + path node { relations { iri resource { iri kind } } } + }`), + { id: globalId("Resource", undo.id) }, + ); + assert.deepEqual(body.data?.node.currentRevision.root.relations, [ + { + path: ["object", 0], + node: { relations: [{ iri: unregistered, resource: null }] }, + }, + { + path: ["object", 1], + node: { + relations: [ + { iri: unknown, resource: { iri: unknown, kind: "unknown" } }, + ], + }, + }, + ]); + }); + }); + + it("returns a document with a context outside the offline allowlist uninterpreted", async () => { + await withWriter(async ({ harness, query }) => { + const resource = await ensureResource( + harness.db, + `${ACTOR_IRI}/${uuidV7()}`, + ); + const document = { + "@context": [AS, "https://context.example/ns"], + id: resource.iri, + type: "Note", + content: "contextual", + }; + await appendResourceRevision(harness.db, { + resourceId: resource.id, + resourceKind: "object", + expectedRevisionId: null, + kind: "snapshot", + capture: "local", + document, + }); + const body = await query( + `query($id: ID!) { node(id: $id) { ... on Resource { currentRevision { + kind capture interpreted root { type } document + diagnostics { reason category severity path } + } } } }`, + { id: globalId("Resource", resource.id) }, + ); + assert.deepEqual(body, { + data: { + node: { + currentRevision: { + kind: "snapshot", + capture: "local", + interpreted: false, + root: null, + document, + diagnostics: [ + { + reason: "context_unavailable_offline", + category: "support", + severity: "error", + path: ["@context", 1], + }, + ], + }, + }, + }, + }); + }); + }); + + it("returns a document with an unsupported property uninterpreted", async () => { + await withWriter(async ({ harness, query }) => { + const resource = await ensureResource( + harness.db, + `${ACTOR_IRI}/${uuidV7()}`, + ); + const document = { + "@context": AS, + id: resource.iri, + type: "Note", + content: "tagged", + tag: [{ type: "Mention", href: ACTOR_IRI }], + }; + await appendResourceRevision(harness.db, { + resourceId: resource.id, + resourceKind: "object", + expectedRevisionId: null, + kind: "snapshot", + capture: "local", + document, + }); + const body = await query( + `query($id: ID!) { node(id: $id) { ... on Resource { currentRevision { + interpreted root { type } document diagnostics { reason category severity path } + } } } }`, + { id: globalId("Resource", resource.id) }, + ); + assert.deepEqual(body, { + data: { + node: { + currentRevision: { + interpreted: false, + root: null, + document, + diagnostics: [ + { + reason: "unsupported_property", + category: "support", + severity: "error", + path: ["tag"], + }, + ], + }, + }, + }, + }); + }); + }); + + it("shows anyone the blind recipients of a local resource", async () => { + await withWriter(async ({ save, query }) => { + const [note] = await save({ + type: "Note", + content: "secret", + to: [PUBLIC_IRI], + bto: [BLIND], + bcc: [{ type: "Person", id: BLIND }, BLIND], + }); + assert.ok(note != null); + const body = await query( + `query($id: ID!) { node(id: $id) { ... on Resource { currentRevision { + document + root { + addressing { property position path representation iri } + bcc: addressing(property: bcc) { iri resource { kind } } + } + } } } }`, + { id: globalId("Resource", note.id) }, + ); + assert.equal(body.errors, undefined); + const revision = body.data?.node.currentRevision; + assert.deepEqual(revision.document.bto, [BLIND]); + assert.deepEqual(revision.document.bcc, [ + { type: "Person", id: BLIND }, + BLIND, + ]); + assert.deepEqual(revision.root.addressing, [ + { + property: "to", + position: 0, + path: ["to", 0], + representation: "reference", + iri: PUBLIC_IRI, + }, + { + property: "bto", + position: 0, + path: ["bto", 0], + representation: "reference", + iri: BLIND, + }, + { + property: "bcc", + position: 0, + path: ["bcc", 0], + representation: "embedded", + iri: BLIND, + }, + { + property: "bcc", + position: 1, + path: ["bcc", 1], + representation: "reference", + iri: BLIND, + }, + ]); + assert.deepEqual(revision.root.bcc, [ + { iri: BLIND, resource: { kind: "unknown" } }, + { iri: BLIND, resource: { kind: "unknown" } }, + ]); + }); + }); + + it("returns custom extension properties by their source keys", async () => { + await withWriter(async ({ save, query }) => { + const [note] = await save({ + "@context": [AS, { ex: "https://ext.example/ns#" }], + type: "Note", + content: "extended", + "ex:mood": { level: 3 }, + }); + assert.ok(note != null); + const body = await query(currentRoot("extensions { key value }"), { + id: globalId("Resource", note.id), + }); + assert.deepEqual(body.data?.node.currentRevision.root.extensions, [ + { key: "ex:mood", value: { level: 3 } }, + ]); + }); + }); +}); + +describe("Resource.revisions", () => { + it("pages revisions newest first and rejects an invalid cursor", async () => { + await withWriter(async ({ harness, save, change, query }) => { + const [note] = await save({ type: "Note", content: "1" }); + assert.ok(note != null); + for (const content of ["2", "3"]) { + const current = await head(harness.db, note.id); + await change( + edit(note.id, current.id, { + ...(current.document as JsonObject), + content, + }), + ); + } + const page = `query($id: ID!, $first: Int, $after: String, $last: Int, $before: String) { + node(id: $id) { ... on Resource { + revisions(first: $first, after: $after, last: $last, before: $before) { + edges { cursor node { sequence document } } + pageInfo { hasNextPage hasPreviousPage } + } + } } + }`; + const id = globalId("Resource", note.id); + const seen: [number, string][] = []; + let after: string | undefined; + for (let index = 0; index < 5; index += 1) { + const body = await query(page, { id, first: 1, after }); + assert.equal(body.errors, undefined); + assert.ok(body.data != null); + const { edges, pageInfo } = body.data.node.revisions; + assert.equal(edges.length, 1); + seen.push([edges[0].node.sequence, edges[0].node.document.content]); + if (!pageInfo.hasNextPage) break; + after = edges[0].cursor; + } + assert.deepEqual(seen, [ + [3, "3"], + [2, "2"], + [1, "1"], + ]); + const last = await query(page, { id, last: 2 }); + assert.deepEqual( + last.data?.node.revisions.edges.map( + ({ node }: { node: { sequence: number } }) => node.sequence, + ), + [2, 1], + ); + assert.equal(last.data?.node.revisions.pageInfo.hasPreviousPage, true); + for (const cursor of [ + "invalid", + Buffer.from("DC:x").toString("base64"), + ]) { + const invalid = await query(page, { id, first: 1, after: cursor }); + assert.ok((invalid.errors?.length ?? 0) > 0); + } + }); + }); + + it("ends with a whiteout whose former types are IRIs", async () => { + await withWriter(async ({ harness, save, change, query }) => { + const [note] = await save({ type: "Note", content: "gone" }); + assert.ok(note != null); + const current = await head(harness.db, note.id); + await change({ + operation: "delete", + actorId: localActorId, + objectId: note.id, + expectedRevisionId: current.id, + }); + const whiteout = await head(harness.db, note.id); + const fields = `kind deleted formerTypes document interpreted root { type } diagnostics { reason }`; + const body = await query( + `query($id: ID!, $revision: ID!) { + node(id: $id) { ... on Resource { + currentRevision { id ${fields} } + revisions { edges { node { kind } } } + } } + revision: node(id: $revision) { ... on ResourceRevision { ${fields} resource { iri } } } + }`, + { + id: globalId("Resource", note.id), + revision: revisionId(whiteout.id), + }, + ); + assert.equal(body.errors, undefined); + const expected = { + kind: "whiteout", + deleted: whiteout.deleted?.toString(), + formerTypes: [`${AS}#Note`], + document: null, + interpreted: false, + root: null, + diagnostics: [], + }; + assert.deepEqual(body.data?.node.currentRevision, { + id: revisionId(whiteout.id), + ...expected, + }); + assert.deepEqual(body.data?.node.revisions.edges, [ + { node: { kind: "whiteout" } }, + { node: { kind: "snapshot" } }, + ]); + // A whiteout's own deletion time does not hide it as a node. + assert.deepEqual(body.data?.revision, { + ...expected, + resource: { iri: note.iri }, + }); + }); + }); +}); + +describe("Access to revisions", () => { + // The rules for remote resources are still those of their legacy typed + // rows, so this fixture builds them. + it("follows the rule of a remote resource the viewer may not read", async () => { + await withWriter(async ({ harness, auth, query }) => { + const { db } = harness; + await seedRemoteActor(db); + const remoteId = uuidV7(); + const remoteIri = `https://remote.example.com/notes/${remoteId}`; + await seedObjects(db, { + id: remoteId, + actorId: remoteActorId, + type: "Note", + iri: remoteIri, + contentHtml: "private", + document: { type: "Note", content: "private" }, + addressing: { to: ["https://remote.example.com/users/carol"] }, + }); + const revision = await db.transaction((tx) => + captureLegacyResourceRevision(tx, remoteId), + ); + // A local note addresses the remote one, which reaches its resource. + const localId = uuidV7(); + await seedObjects(db, { + id: localId, + actorId: localActorId, + type: "Note", + iri: `${ACTOR_IRI}/${localId}`, + contentHtml: "public", + addressing: { to: [remoteIri] }, + }); + const read = `query($local: ID!, $revision: ID!) { + local: node(id: $local) { ... on Object { to { + iri currentRevision { document } revisions { edges { node { document } } } + } } } + revision: node(id: $revision) { ... on ResourceRevision { document } } + revisions: nodes(ids: [$revision]) { id } + }`; + const variables = { + local: globalId("Object", localId), + revision: revisionId(revision), + }; + // Neither an anonymous viewer nor a member of an instance that did not + // receive it may read it. + for (const init of [undefined, auth]) { + assert.deepEqual(await query(read, variables, init), { + data: { + local: { + to: [ + { + iri: remoteIri, + currentRevision: null, + revisions: { edges: [] }, + }, + ], + }, + revision: null, + revisions: [null], + }, + }); + } + }); + }); + + // Deletion hides typed rows from their existing fields, so the fixture + // builds one to tell that it hides no revision; a resource without typed + // rows is covered by the whiteout test above. + it("keeps the history of a deleted object and author readable", async () => { + await withWriter(async ({ harness, auth, save, query }) => { + const { db } = harness; + const noteId = uuidV7(); + const noteIri = `${ACTOR_IRI}/notes/${noteId}`; + const document = { + "@context": AS, + id: noteIri, + type: "Note", + content: "deleted contents", + }; + await seedObjects(db, { + id: noteId, + actorId: localActorId, + type: "Note", + iri: noteIri, + contentHtml: "deleted contents", + document, + }); + const snapshot = await db.transaction((tx) => + captureLegacyResourceRevision(tx, noteId), + ); + const [like] = await save({ type: "Like", object: noteIri }, [ + { path: [], kind: "activity" }, + ]); + assert.ok(like != null); + await writeTypedResourceRevision(db, { + resourceId: noteId, + expectedRevisionId: snapshot, + kind: "whiteout", + deleted: Temporal.Now.instant(), + formerTypes: ["Note"], + }); + const read = `query($note: ID!, $revision: ID!, $like: ID!) { + note: node(id: $note) { ... on Resource { + detail { __typename } + currentRevision { kind } + revisions { edges { node { kind document } } } + } } + revision: node(id: $revision) { ... on ResourceRevision { document } } + like: node(id: $like) { ... on Resource { currentRevision { root { + relations(property: object) { iri resource { iri } } + } } } } + }`; + const variables = { + note: globalId("Resource", noteId), + revision: revisionId(snapshot), + like: globalId("Resource", like.id), + }; + const expected = { + data: { + note: { + // The existing fields keep hiding what was deleted. + detail: null, + currentRevision: { kind: "whiteout" }, + revisions: { + edges: [ + { node: { kind: "whiteout", document: null } }, + { node: { kind: "snapshot", document } }, + ], + }, + }, + revision: { document }, + like: { + currentRevision: { + root: { + relations: [{ iri: noteIri, resource: { iri: noteIri } }], + }, + }, + }, + }, + }; + for (const init of [undefined, auth]) { + assert.deepEqual(await query(read, variables, init), expected); + } + // Nor does deleting the author hide the history. + await db + .update(schema.actors) + .set({ deleted: Temporal.Now.instant() }) + .where(eq(schema.actors.id, localActorId)); + assert.deepEqual(await query(read, variables), expected); + }); + }); + + it("keeps the history of a generic resource received from elsewhere closed", async () => { + await withWriter(async ({ harness, auth, save }) => { + const resource = await ensureResource( + harness.db, + `https://remote.example/generic/${uuidV7()}`, + ); + const received = await appendResourceRevision(harness.db, { + resourceId: resource.id, + resourceKind: "object", + expectedRevisionId: null, + kind: "snapshot", + capture: "received", + document: { + "@context": AS, + id: resource.iri, + type: "Note", + content: "private revision contents", + }, + }); + const [like] = await save({ type: "Like", object: resource.iri }, [ + { path: [], kind: "activity" }, + ]); + assert.ok(like != null); + const history = + "iri kind currentRevision { document } revisions { edges { node { document } } }"; + const read = `query($id: ID!, $revision: ID!, $like: ID!) { + node(id: $id) { ... on Resource { ${history} } } + revision: node(id: $revision) { ... on ResourceRevision { document } } + like: node(id: $like) { ... on Resource { currentRevision { root { + relations(property: object) { resource { ${history} } } + } } } } + }`; + const variables = { + id: globalId("Resource", resource.id), + revision: revisionId(received.id), + like: globalId("Resource", like.id), + }; + const closed = { + iri: resource.iri, + kind: "object", + currentRevision: null, + revisions: { edges: [] }, + }; + for (const init of [undefined, auth]) { + const response = await harness.post({ query: read, variables }, init); + const text = await response.text(); + assert.ok(!text.includes("private revision contents")); + assert.deepEqual(JSON.parse(text), { + data: { + node: closed, + revision: null, + like: { + currentRevision: { + root: { relations: [{ resource: closed }] }, + }, + }, + }, + }); + } + }); + }); +}); diff --git a/packages/graphql/src/revision.ts b/packages/graphql/src/revision.ts new file mode 100644 index 00000000..482ba2c1 --- /dev/null +++ b/packages/graphql/src/revision.ts @@ -0,0 +1,508 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { + type InterpretedNode, + RELATION_PROPERTIES, + type RecipientOccurrence, + type RelationOccurrence, + interpretDocument, +} from "@drfed/federation/document"; +import { schema } from "@drfed/models"; +import { + type Diagnostic, + type DiagnosticCategory, + type DiagnosticSeverity, + type DocumentNodeKind, + validateDocument, +} from "@drfed/models/document"; +import type { + ResourceRevision as ResourceRevisionRow, + Resource as ResourceRow, +} from "@drfed/models/schema"; +import { and, eq, inArray } from "drizzle-orm"; + +import builder, { type DrFedObjectRef, type UserContext } from "./builder.ts"; +import { readableHistory, readableResource } from "./readable.ts"; +import { Resource } from "./resource.ts"; + +const ACTIVITY_STREAMS = "https://www.w3.org/ns/activitystreams#"; + +const ResourceRevisionKind = builder.enumType("ResourceRevisionKind", { + description: "What a revision records.", + values: { + snapshot: { description: "A saved document." }, + unavailable: { + description: + "A legacy typed row that had no retained document; nothing replaces it.", + }, + whiteout: { + description: + "A deletion: its time and the types the resource had, but no document.", + }, + } satisfies Record, +}); +const ResourceRevisionCapture = builder.enumType("ResourceRevisionCapture", { + description: + "How DrFed came to store a revision. Neither proves ownership nor " + + "grants access.", + values: { + local: { description: "Saved by DrFed for a local actor." }, + received: { description: "Received in an inbound activity." }, + embedded: { description: "Embedded in another received document." }, + fetched: { + description: + "Fetched apart from an activity. For legacy data, a conservative " + + "flag that is no proof an HTTP fetch occurred.", + }, + } satisfies Record, +}); +const DocumentNodeKindEnum = builder.enumType("DocumentNodeKind", { + description: "The vocabulary category of a document's type.", + values: { + activity: {}, + actor: {}, + collection: {}, + link: {}, + object: {}, + } satisfies Record, +}); +const RelationProperty = builder.enumType("RelationProperty", { + description: "A property that relates a document to another resource.", + values: RELATION_PROPERTIES, +}); +const AddressingProperty = builder.enumType("AddressingProperty", { + description: "A property that addresses a document's recipients.", + values: schema.addressingPropertyEnum.enumValues, +}); +const RelationRepresentation = builder.enumType("RelationRepresentation", { + description: "How a value names what it stands for.", + values: { + reference: { description: "An IRI." }, + embedded: { description: "An embedded document." }, + link: { description: "An embedded `Link`, which names it by `href`." }, + } satisfies Record, +}); +const DiagnosticCategoryEnum = builder.enumType("DiagnosticCategory", { + values: { + vocabulary: { + description: "The document breaks a vocabulary or JSON-LD rule.", + }, + authority: { description: "The document claims what it may not." }, + support: { description: "DrFed's validator cannot check it." }, + compatibility: { + description: "Valid, but other implementations may read it otherwise.", + }, + } satisfies Record, +}); +const DiagnosticSeverityEnum = builder.enumType("DiagnosticSeverity", { + values: { + error: {}, + warning: {}, + } satisfies Record, +}); + +const DocumentExtension = builder.objectRef<{ + readonly key: string; + readonly value: unknown; +}>("DocumentExtension"); +DocumentExtension.implement({ + description: "A custom extension property, preserved as opaque JSON.", + fields: (t) => ({ + key: t.exposeString("key", { + description: "The key in its source spelling.", + }), + value: t.expose("value", { type: "JSON", description: "As saved." }), + }), +}); + +const DocumentDiagnostic = builder.objectRef("DocumentDiagnostic"); +DocumentDiagnostic.implement({ + description: "A finding of the document validator.", + fields: (t) => ({ + reason: t.exposeString("reason", { + description: + "A stable classification, such as `unsupported_property`. Use it " + + "for decisions rather than `message`.", + }), + category: t.expose("category", { type: DiagnosticCategoryEnum }), + severity: t.expose("severity", { type: DiagnosticSeverityEnum }), + path: t.expose("path", { + type: "JSON", + description: + "The source keys and list indexes leading to the finding; `[]` is " + + "the root.", + }), + message: t.exposeString("message", { + description: "For people; it may change.", + }), + }), +}); + +const DocumentNode = builder.objectRef("DocumentNode"); +const DocumentRelation = + builder.objectRef("DocumentRelation"); +const DocumentRecipient = + builder.objectRef("DocumentRecipient"); + +const resourceLookups = new WeakMap< + UserContext, + Map> +>(); + +/** + * Finds the resource registered under an IRI, as `Activity.object` opens + * it: only when the viewer may read it. A deleted one is found too, since + * its revisions stay readable. Lookups are shared within a request, since + * a document may name one IRI many times. + * @returns The resource, or null. + */ +function registeredResource( + ctx: UserContext, + iri: string | null, +): Promise { + if (iri == null) return Promise.resolve(null); + let lookups = resourceLookups.get(ctx); + if (lookups == null) { + lookups = new Map(); + resourceLookups.set(ctx, lookups); + } + let lookup = lookups.get(iri); + if (lookup == null) { + lookup = (async () => + (await ctx.db.query.resources.findFirst({ + where: { + iri, + RAW: (table) => readableResource(ctx, table.id), + }, + })) ?? null)(); + lookups.set(iri, lookup); + } + return lookup; +} + +const occurrenceFields = { + representation: { + description: + "Whether the value is an IRI, an embedded document or a `Link`.", + }, + iri: + "A reference's IRI, an embedded document's `id`, or a `Link`'s `href`, " + + "with a compact IRI expanded; null for an anonymous embedded value.", + resource: + "The resource currently registered under `iri`, or null when there is " + + "none, or when the viewer may not read it. A deleted resource is " + + "returned too, since its revisions stay readable. It is never fetched.", +} as const; + +DocumentRelation.implement({ + description: + "One value of a relation property, in source order including duplicates.", + fields: (t) => ({ + property: t.expose("property", { type: RelationProperty }), + path: t.expose("path", { + type: "JSON", + description: + "The source path of the value from the root of the saved document, " + + 'such as `["object", 0]`.', + }), + representation: t.expose("representation", { + type: RelationRepresentation, + ...occurrenceFields.representation, + }), + iri: t.expose("iri", { + type: "URL", + nullable: true, + description: occurrenceFields.iri, + }), + node: t.expose("node", { + type: DocumentNode, + nullable: true, + description: + "The embedded document or `Link` as the saved document embeds it, " + + "which may differ from the resource's current revision; null for a " + + "reference.", + }), + resource: t.field({ + type: Resource, + nullable: true, + description: occurrenceFields.resource, + resolve: (occurrence, _, ctx) => registeredResource(ctx, occurrence.iri), + }), + }), +}); + +DocumentRecipient.implement({ + description: + "One value of an addressing property, in source order including " + + "duplicates and anonymous embedded recipients.", + fields: (t) => ({ + property: t.expose("property", { type: AddressingProperty }), + position: t.exposeInt("position", { + description: + "The index of the value in its property's list, or 0 for a value " + + "written alone.", + }), + path: t.expose("path", { + type: "JSON", + description: + "The source path of the value from the root of the saved document.", + }), + representation: t.expose("representation", { + type: RelationRepresentation, + ...occurrenceFields.representation, + }), + iri: t.expose("iri", { + type: "URL", + nullable: true, + description: occurrenceFields.iri, + }), + resource: t.field({ + type: Resource, + nullable: true, + description: occurrenceFields.resource, + resolve: (occurrence, _, ctx) => registeredResource(ctx, occurrence.iri), + }), + }), +}); + +DocumentNode.implement({ + description: + "A vocabulary document of a saved revision, the root or one embedded in " + + "it at any depth, read by meaning, whatever keys spell its properties. " + + "It may be anonymous.", + fields: (t) => ({ + path: t.expose("path", { + type: "JSON", + description: + 'The source path from the root, such as `["object", 0]`; `[]` is ' + + "the root.", + }), + property: t.exposeString("property", { + nullable: true, + description: + "The standard name of the property that embeds it, whatever its " + + "source spelling; null for the root.", + }), + type: t.expose("type", { + type: "URL", + description: "The type IRI, such as `…/activitystreams#Note`.", + }), + kind: t.expose("kind", { type: DocumentNodeKindEnum }), + iri: t.expose("iri", { + type: "URL", + nullable: true, + description: + "Its `id`, or the `href` of a `Link`, with a compact IRI expanded; " + + "null when it has none.", + }), + document: t.expose("value", { + type: "JSON", + description: "Its JSON as saved, with everything it embeds.", + }), + relations: t.field({ + type: [DocumentRelation], + args: { property: t.arg({ type: RelationProperty }) }, + description: + "Its own `actor`, `object`, `target`, `origin`, `result`, " + + "`instrument` and `attributedTo` values, or those of one property, " + + "in that order, then in source order including duplicates. Empty " + + "for a property it does not have.", + resolve: (node, { property }) => + property == null + ? node.relations + : node.relations.filter((entry) => entry.property === property), + }), + addressing: t.field({ + type: [DocumentRecipient], + args: { property: t.arg({ type: AddressingProperty }) }, + description: + "Its own `to`, `cc`, `bto`, `bcc` and `audience` values, or those " + + "of one property, in that order, then in source order including " + + "duplicates.", + resolve: (node, { property }) => + property == null + ? node.addressing + : node.addressing.filter((entry) => entry.property === property), + }), + extensions: t.expose("extensions", { + type: [DocumentExtension], + description: + "Its own custom extension properties, by their source keys, sorted.", + }), + }), +}); + +type Content = Pick; + +const interpretations = new WeakMap(); +const validations = new WeakMap(); + +/** + * Interprets a revision's document once per loaded row. + * @returns The root, or null unless the revision is a snapshot whose + * document the validator reads without errors. + */ +function rootOf(revision: Content): InterpretedNode | null { + if (!interpretations.has(revision)) { + interpretations.set( + revision, + revision.kind === "snapshot" + ? (interpretDocument(revision.document)?.[0] ?? null) + : null, + ); + } + return interpretations.get(revision)!; +} + +function diagnosticsOf(revision: Content): readonly Diagnostic[] { + let diagnostics = validations.get(revision); + if (diagnostics == null) { + diagnostics = + revision.kind === "snapshot" + ? validateDocument(revision.document).diagnostics + : []; + validations.set(revision, diagnostics); + } + return diagnostics; +} + +const content = { columns: { kind: true, document: true } } as const; + +const ResourceRevisionRef = builder.drizzleNode("resourceRevisions", { + name: "ResourceRevision", + description: + "An immutable revision of a resource. Every revision, past ones " + + "included, is readable exactly when its resource's history is: a local " + + "resource's by anyone, blind recipients and unpublished activities " + + "included; a remote one's as `Activity` and `Object` tell; never one " + + "hidden by a deletion. A revision the viewer may not read is left out " + + "as if it did not exist.", + // A node lookup checks the revision against its resource. + select: { columns: { id: true, resourceId: true } }, + id: { column: (revision) => revision.id }, + fields: (t) => ({ + resource: t.relation("resource"), + sequence: t.exposeInt("sequence", { + description: "Increases with each revision of the resource.", + }), + kind: t.expose("kind", { type: ResourceRevisionKind }), + capture: t.expose("capture", { type: ResourceRevisionCapture }), + backfilled: t.exposeBoolean("backfilled", { + description: "Whether the migration from legacy typed rows created it.", + }), + created: t.expose("created", { + type: "DateTime", + description: "When DrFed stored the revision.", + }), + document: t.expose("document", { + type: "JSON", + nullable: true, + description: + "The saved JSON as is, `bto` and `bcc` included for local " + + "resources. Read `root` instead of parsing it by keys, which " + + "aliases and contexts may spell otherwise. Null unless `kind` is " + + "`snapshot`, or for a snapshot of JSON null.", + }), + interpreted: t.boolean({ + description: + "Whether `root` could be derived from `document`. When false, " + + "`root` is null and, for a snapshot, `diagnostics` explain why.", + select: content, + resolve: (revision) => rootOf(revision) != null, + }), + root: t.field({ + type: DocumentNode, + nullable: true, + description: + "The root document read by meaning; null unless `interpreted`.", + select: content, + resolve: (revision) => rootOf(revision), + }), + diagnostics: t.field({ + type: [DocumentDiagnostic], + description: + "What the current validator finds in the saved document, which may " + + "differ from what it found when the revision was stored. Empty " + + "unless `kind` is `snapshot`.", + select: content, + resolve: (revision) => diagnosticsOf(revision), + }), + deleted: t.expose("deleted", { + type: "DateTime", + nullable: true, + description: "The deletion time of a whiteout; null otherwise.", + }), + formerTypes: t.field({ + type: ["URL"], + nullable: true, + description: + "The type IRIs the resource had, for a whiteout; null otherwise. " + + 'Stored ActivityStreams names, such as `"Note"`, are expanded with ' + + "`https://www.w3.org/ns/activitystreams#`.", + select: { columns: { formerTypes: true } }, + resolve: (revision) => + revision.formerTypes?.map((type) => + type.includes(":") ? type : `${ACTIVITY_STREAMS}${type}`, + ) ?? null, + }), + }), +}); +export const ResourceRevision: DrFedObjectRef = ResourceRevisionRef; + +builder.drizzleObjectField("resources", "currentRevision", (t) => + t.field({ + type: ResourceRevisionRef, + nullable: true, + description: + "The current revision; null for a resource without revisions, or when " + + "the viewer may not read the resource's revisions.", + select: { columns: { id: true } }, + resolve: async (resource, _, ctx) => + (await ctx.db.query.resourceRevisions.findFirst({ + where: { + RAW: (table) => + and( + inArray( + table.id, + ctx.db + .select({ id: schema.resourceHeads.revisionId }) + .from(schema.resourceHeads) + .where(eq(schema.resourceHeads.resourceId, resource.id)), + ), + readableHistory(ctx, table.resourceId), + )!, + }, + })) ?? null, + }), +); + +builder.drizzleObjectField("resources", "revisions", (t) => + t.relatedConnection( + "revisions", + { + description: + "Every revision, newest first. Empty when the viewer may not read " + + "the resource's revisions.", + query: (_, ctx) => ({ + where: { RAW: (table) => readableHistory(ctx, table.resourceId) }, + orderBy: { sequence: "desc" }, + }), + }, + { name: "ResourceRevisionConnection" }, + { name: "ResourceRevisionEdge" }, + ), +); diff --git a/packages/graphql/src/schema.ts b/packages/graphql/src/schema.ts index aca3c3e4..869cc19e 100644 --- a/packages/graphql/src/schema.ts +++ b/packages/graphql/src/schema.ts @@ -19,6 +19,7 @@ import "./instance.ts"; import "./auth/entry.ts"; import "./actor.ts"; import "./object.ts"; +import "./revision.ts"; import "./activity-delivery/entry.ts"; import "./key.ts"; import builder from "./builder.ts"; diff --git a/packages/models/src/document.test.ts b/packages/models/src/document.test.ts index 28434066..4d997d17 100644 --- a/packages/models/src/document.test.ts +++ b/packages/models/src/document.test.ts @@ -4126,6 +4126,7 @@ describe("describeDocument() semantic view", () => { }, ], custom: { type: "Note", actor: "https://example.com/mallory" }, + "https://ext.example/ns#flag": true, }; const original = structuredClone(input); const nodes = describeDocument(input); @@ -4165,6 +4166,12 @@ describe("describeDocument() semantic view", () => { object: ["object"], type: ["type"], }); + // Neither `@context` nor any key of a standard property is an extension. + assert.deepEqual(nodes[0]!.extensionProperties, [ + "custom", + "https://ext.example/ns#flag", + ]); + assert.deepEqual(nodes[1]!.extensionProperties, []); assert.deepEqual(input, original); }); diff --git a/packages/models/src/document.ts b/packages/models/src/document.ts index 7d37fc1e..33712b63 100644 --- a/packages/models/src/document.ts +++ b/packages/models/src/document.ts @@ -2602,6 +2602,12 @@ export interface DocumentNode { * not listed. */ readonly properties: ReadonlyMap; + /** + * The source keys of the document's own custom extension properties, whose + * values are preserved as opaque JSON, sorted by key. Together with + * the keys in `properties` and `@context`, they are all of its keys. + */ + readonly extensionProperties: readonly string[]; /** * String IRI references held by this document's own reference properties * (`id`, `actor`, `object`, addressing, `href`, and so on), with compact @@ -3043,6 +3049,10 @@ export function describeDocument( fields.filter(({ compatible }) => compatible), context, ), + // Validation has reported any other unnamed key as an error. + extensionProperties: fields + .filter(({ name }) => name == null) + .map(({ source }) => source), })); const described = [ ...extensions.map(({ values, path, context }) => From db4b210d3bd717b963ec2cd322b31f9a15a1d89c Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Fri, 13 Nov 2026 17:22:46 +0900 Subject: [PATCH 02/10] Record the sources of embedded documents A saved revision now records, for each embedded document with an id, the revision it came from and whether it keeps that revision's contents (snapshot) or was derived from it. An embedded document without a record has an unknown source. This replaces comparing transaction timestamps, which do not follow commit order, with comparing revisions of one resource. The new revision_embeddings table is part of a revision's immutable history: rows are written with the revision, through the embeddings input of appendResourceRevision() and writeTypedResourceRevision(), and the database refuses a source that is not a snapshot of another resource, rows added after publication, and any change or removal. commitLocalWrite() records the source of each embedded document from a resource saved earlier in the same write, from a revision the request declares in its new sources field, or from the current snapshot of the resource registered under its id when the contents are unchanged. Previews and results do not report sources, so a writer cannot test guessed documents against revisions they may not read. createLegacyObject() records none. GraphQL reads each revision by evidence of its own instead of the rule of its resource: local capture, public addressing of the revision, a receipt for an instance the viewer belongs to, or, for a revision without these, being the current revision of a readable resource with a legacy typed row. A revision is also readable only when the viewer may read every revision it carries through its embeddings, so a local document embedding a private received revision is hidden as a whole from those who could not read that revision. DocumentNode.source exposes the relation, the source revision, and whether that revision is still current, superseded, or deleted. https://github.com/fedify-dev/drfed/issues/154 The agent in Delta, using Claude Opus 5.5, wrote the schema, migration, and models API itself, delegated the models tests, the local write recording, and the GraphQL access rule and fields to parallel subagents following the design the authors settled in discussion, and wrote the documentation and changelog. The build, checks, and full test suite were run with PGlite; the PostgreSQL variants were skipped. Co-authored-by: Hyeonseo Kim Assisted-by: Delta:claude-opus-5-5 --- CHANGES.md | 20 +- changes.d/graphql/resource-revisions.md | 13 +- changes.d/javascript/embedded-sources.md | 11 + docs/internals/local-writes.md | 44 + docs/internals/resource-revisions.md | 80 +- .../src/local-write-embedding.test.ts | 538 ++ packages/federation/src/local-write.ts | 1 + .../federation/src/local-write/context.ts | 67 + .../federation/src/local-write/embedding.ts | 361 ++ .../federation/src/local-write/existing.ts | 23 +- .../federation/src/local-write/operation.ts | 33 + .../federation/src/local-write/prepare.ts | 60 +- packages/federation/src/local-write/types.ts | 20 + packages/graphql/README.md | 19 +- packages/graphql/src/readable.ts | 167 +- packages/graphql/src/revision.test.ts | 340 ++ packages/graphql/src/revision.ts | 216 +- .../migration.sql | 14 + .../snapshot.json | 4634 +++++++++++++++++ .../migration.sql | 42 + .../snapshot.json | 4634 +++++++++++++++++ packages/models/migrations-manifest.json | 8 + packages/models/src/relations.ts | 18 + .../src/resource-revision-embedding.test.ts | 379 ++ packages/models/src/resource-revision.ts | 70 + packages/models/src/schema.ts | 42 + 26 files changed, 11723 insertions(+), 131 deletions(-) create mode 100644 changes.d/javascript/embedded-sources.md create mode 100644 packages/federation/src/local-write-embedding.test.ts create mode 100644 packages/federation/src/local-write/context.ts create mode 100644 packages/federation/src/local-write/embedding.ts create mode 100644 packages/models/drizzle/20261113080536_revision_embeddings/migration.sql create mode 100644 packages/models/drizzle/20261113080536_revision_embeddings/snapshot.json create mode 100644 packages/models/drizzle/20261113080537_guard_revision_embeddings/migration.sql create mode 100644 packages/models/drizzle/20261113080537_guard_revision_embeddings/snapshot.json create mode 100644 packages/models/src/resource-revision-embedding.test.ts diff --git a/CHANGES.md b/CHANGES.md index 66e830a1..95526134 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -53,10 +53,15 @@ To be released. document, `root` describes it by meaning, whatever keys spell its properties: the relations and recipients of the root and of every document it embeds, with the resource currently registered under each - IRI, and its custom extension properties. Revisions follow the read - rules of their resource; revisions received from elsewhere for a - resource without legacy details are not readable yet. Deleting a - resource or its author hides none of its revisions. [[#154]] + IRI, and its custom extension properties. Each revision is read by + evidence of its own: local revisions by anyone, revisions addressed to the + public by anyone, and received revisions by members of the instance that + received them. `DocumentNode.source` tells which revision an embedded + document came from, whether it keeps that revision's contents or was + derived from it, and whether that revision is still current, superseded, or + deleted. A revision that embeds documents from revisions the viewer may + not read is hidden as a whole. Deleting a resource or its author hides + none of its revisions by itself. [[#154]] - Fixed `Resource.detail` to return `null` without a field error when the resource has no corresponding detail record. [[#150], [#164] by Hong Minhee\] @@ -137,6 +142,13 @@ To be released. poll-specific rules remain separate work. The supported properties and representation limits are documented in *packages/models/README.md*. [[#151], [#166] by Jiwon Kwon\] + - `appendResourceRevision()` and `writeTypedResourceRevision()` in + `@drfed/models/resource-revision` accept `embeddings`, which record the + revision each embedded document came from and whether it keeps that + revision's contents or was derived from it. `commitLocalWrite()` in + `@drfed/federation/local-write` records them for every document it saves, + and `create` and `edit` requests accept `sources` to declare the revision + an embedded document was loaded from. [[#154]] [#151]: https://github.com/fedify-dev/drfed/issues/151 [#152]: https://github.com/fedify-dev/drfed/issues/152 diff --git a/changes.d/graphql/resource-revisions.md b/changes.d/graphql/resource-revisions.md index 9d83fe3d..7a349aae 100644 --- a/changes.d/graphql/resource-revisions.md +++ b/changes.d/graphql/resource-revisions.md @@ -10,7 +10,12 @@ links: document, `root` describes it by meaning, whatever keys spell its properties: the relations and recipients of the root and of every document it embeds, with the resource currently registered under each - IRI, and its custom extension properties. Revisions follow the read - rules of their resource; revisions received from elsewhere for a - resource without legacy details are not readable yet. Deleting a - resource or its author hides none of its revisions. [[#154]] + IRI, and its custom extension properties. Each revision is read by + evidence of its own: local revisions by anyone, revisions addressed to the + public by anyone, and received revisions by members of the instance that + received them. `DocumentNode.source` tells which revision an embedded + document came from, whether it keeps that revision's contents or was + derived from it, and whether that revision is still current, superseded, or + deleted. A revision that embeds documents from revisions the viewer may + not read is hidden as a whole. Deleting a resource or its author hides + none of its revisions by itself. [[#154]] diff --git a/changes.d/javascript/embedded-sources.md b/changes.d/javascript/embedded-sources.md new file mode 100644 index 00000000..b2f64944 --- /dev/null +++ b/changes.d/javascript/embedded-sources.md @@ -0,0 +1,11 @@ +--- +links: + '#154': https://github.com/fedify-dev/drfed/issues/154 +--- + - `appendResourceRevision()` and `writeTypedResourceRevision()` in + `@drfed/models/resource-revision` accept `embeddings`, which record the + revision each embedded document came from and whether it keeps that + revision's contents or was derived from it. `commitLocalWrite()` in + `@drfed/federation/local-write` records them for every document it saves, + and `create` and `edit` requests accept `sources` to declare the revision + an embedded document was loaded from. [[#154]] diff --git a/docs/internals/local-writes.md b/docs/internals/local-writes.md index 7abc861c..cd9db414 100644 --- a/docs/internals/local-writes.md +++ b/docs/internals/local-writes.md @@ -143,6 +143,50 @@ would otherwise leave occurrences out. Indexes stay `partial`; the documents remain authoritative. +Embedded document sources +------------------------- + +Every saved document records, for each embedded document with an `id`, the +revision it came from when the server knows it, as +[resource revisions](resource-revisions.md#embedded-document-sources) +describe. `Link` values and anonymous documents get no source. The source is +found in this order: + +1. A resource saved earlier in the same write, such as a nested new resource + kept embedded or the version an edit's `Update` embeds. + +2. A source the request declares for the embedded document's submitted path: + + ~~~~ ts + const request = { + operation: "create", + actorId, + document: { type: "Like", object: changedNote }, + resources: [{ path: [], kind: "activity" }], + sources: [{ path: ["object"], revisionId: loadedRevisionId }], + } as const; + ~~~~ + + An editor declares the revision it loaded a document from, so that a + changed copy keeps its source. Both `create` and `edit` accept `sources`, + and the preview token binds them. Each path must name an embedded document + with an `id` that is not a new resource of the write, and its revision + must be a snapshot of the resource registered under that `id`; otherwise + the write is refused. + +3. The current revision of the resource registered under the `id`, only + when the embedded document keeps its contents unchanged. + +An embedded document is a `snapshot` of its source when its effective context +equals the source document's and its JSON, apart from the `@context` key, +equals the source document's, whatever the order of object keys. Otherwise it +is `derived`. The comparison is strict, so a document only re-serialized +differently reads as derived, never the reverse. Previews and commit results +do not report sources: a writer could otherwise learn whether a guessed +document equals a revision they may not read. Writes through +`createLegacyObject()` record no sources. + + Edits and deletions ------------------- diff --git a/docs/internals/resource-revisions.md b/docs/internals/resource-revisions.md index 9e7ed50b..ea674777 100644 --- a/docs/internals/resource-revisions.md +++ b/docs/internals/resource-revisions.md @@ -169,6 +169,33 @@ ownership or grants access. For legacy data, `fetched` inherits the old conservative flag and is not proof that an HTTP fetch occurred. +Embedded document sources +------------------------- + +`revision_embeddings` records where an embedded document of a revision came +from: its source path, the `source_revision_id` of a snapshot of another +resource, and its `relation`. A `snapshot` keeps the source revision's +contents, apart from the context it inherits; a `derived` document started +from that revision and was changed, for example to test how a peer handles +other addressing. An embedded document without a row has an unknown source, +which proves neither that it was nor that it was never saved as a revision: +older data and pasted documents lack the record. An IRI reference is a +separate choice, recorded as the `reference` representation of a relation, +and has no source. + +Rows are written with the revision through the `embeddings` input of +`appendResourceRevision()` and `writeTypedResourceRevision()`, and like other +projections they cannot be added after the revision is published, changed or +removed. The database also refuses a source that is not a snapshot or that +belongs to the same resource. The +[local writes](local-writes.md#embedded-document-sources) decide the rows; +legacy capture and received documents record none. + +Comparing an embedded document with the current state therefore compares +revisions of one resource by `sequence`, not timestamps of different +transactions, which do not follow commit order. + + Legacy capture and upgrades --------------------------- @@ -250,16 +277,43 @@ outside the offline allowlist or one with an unsupported property, `interpreted` is false, `root` is null and `diagnostics` tell why; nothing falls back to typed rows. -Every revision follows the rule of its resource, in `readableHistory()` in -*packages/graphql/src/readable.ts*: the resource must be readable as -`Resource.detail` decides, so local histories are open to anyone. A Relay node -lookup of a revision checks its resource the same way. Deletion hides no -revision: deleting a resource appends a whiteout, and its history, like that of -a resource whose author is deleted, stays readable to whoever may read the -resource, whether or not it has legacy typed rows. Only the existing fields, -such as `Resource.detail`, keep hiding deleted typed rows. Readability is the -existing rule, which reads legacy typed rows. A relation's or recipient's -`resource` is opened as `Activity.object` is, deleted or not. Until the team -decides what opens them, `unprovenGenericHistory()` there closes the histories -of generic resources with a revision not captured locally, while their IRI and -kind stay readable. +Each revision is read by evidence of its own, in `readableRevision()` in +*packages/graphql/src/readable.ts*, not by the rule of its resource. An +administrator reads every revision. Anyone else reads one that was captured +`local`, whose own revision addressing names the public, or that a receipt +links to an inbound delivery to a local instance the viewer is an accepted +member of. A revision without such evidence is readable only while it is the +current revision of a resource with a legacy typed row that the viewer may +read, as `Resource.detail` decides. Local histories are therefore open to +anyone, blind recipients and unpublished activities included. Evidence for +one revision opens no other: a later delivery naming the same IRI does not +open an earlier private revision, and a later restriction of the current +resource does not hide an earlier public one. A Relay node lookup of a +revision checks the revision itself, and `Resource.revisions` leaves out the +ones the viewer may not read, so their sequences can skip. + +A revision is also readable only when the viewer may read, by the same +evidence, every revision it carries through its +[embedded document sources](#embedded-document-sources), directly or through +the local revisions it embeds. A local `Announce` that embeds a `Note` +received only by one instance is thus readable only by that instance's +members and administrators; anyone else reads it as if it did not exist. The +whole revision is hidden rather than the embedded part, so that the same saved +JSON is never read differently by different viewers, and a reader of a +revision may always read its sources. + +Deletion hides no revision by itself: deleting a resource appends a whiteout, +and its earlier revisions, like those of a resource whose author is deleted, +stay readable by their own evidence. Only the existing fields, such as +`Resource.detail`, keep hiding deleted typed rows. A relation's or +recipient's `resource` is opened as `Activity.object` is, deleted or not. + +`DocumentNode.source` tells where an embedded document came from: its +`relation`, `snapshot` or `derived`, the source `revision`, and `status`, +which compares that revision with the current revision of its resource: +`current` when it is the current one, `deleted` when the current revision is +a whiteout, and `superseded` otherwise. The status compares revisions only, +not contents. It is null when the viewer may not read the current revision, +which would otherwise tell of a revision they may not read. `source` is null +for the root, for an embedded document whose source is unknown, and when the +viewer may not read the source revision. diff --git a/packages/federation/src/local-write-embedding.test.ts b/packages/federation/src/local-write-embedding.test.ts new file mode 100644 index 00000000..d329cb7c --- /dev/null +++ b/packages/federation/src/local-write-embedding.test.ts @@ -0,0 +1,538 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Writes in one test depend on the state the previous ones left. +// oxlint-disable no-await-in-loop + +import assert from "node:assert/strict"; + +import { + type CommitOptions, + type CreateRequest, + type EmbeddedSource, + type JsonObject, + type LocalWriteEnvironment, + type LocalWriteRequest, + commitLocalWrite, + previewLocalWrite, +} from "@drfed/federation/local-write"; +import { type Database, schema } from "@drfed/models"; +import { PUBLIC_IRI } from "@drfed/models/resource"; +import { loadCurrentResourceRevision } from "@drfed/models/resource-revision"; +import type { Uuid } from "@drfed/models/uuid"; +import { describe, it } from "@logtape/testing-node/autoload"; +import { eq } from "drizzle-orm"; + +import { withFederation } from "./harness.test.ts"; +import { + created, + localActorId, + localInstanceId, + seedLocalActor, +} from "./seed.test.ts"; + +const AS = "https://www.w3.org/ns/activitystreams"; +const ROOT_ORIGIN = new URL("https://drfed.org"); +const ACCOUNT_ID = "00000000-0000-4000-8000-000000000301" as Uuid; +const PRINCIPAL = { accountId: ACCOUNT_ID }; +const MISSING_REVISION_ID = "00000000-0000-4000-8000-000000000999" as Uuid; +const NOTE = { + "@context": AS, + type: "Note", + content: "

Hello

", + to: [PUBLIC_IRI], +}; + +async function seedMember(db: Database) { + await seedLocalActor(db, { keys: false }); + await db.insert(schema.accounts).values({ + id: ACCOUNT_ID, + email: "member@example.com", + name: "Member", + created, + }); + await db.insert(schema.instanceMembers).values({ + accountId: ACCOUNT_ID, + instanceId: localInstanceId, + accepted: created, + created, + }); +} + +async function environment( + harness: Parameters[0]>[0], +): Promise { + return { + db: harness.db, + federation: harness.federation, + rootOrigin: ROOT_ORIGIN, + previewKey: await crypto.subtle.generateKey( + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign", "verify"], + ), + }; +} + +function create( + document: JsonObject, + resources: CreateRequest["resources"] = [{ path: [], kind: "object" }], + sources?: readonly EmbeddedSource[], +): CreateRequest { + return { + operation: "create", + actorId: localActorId, + document, + resources, + ...(sources == null ? {} : { sources }), + }; +} + +const activity = ( + document: JsonObject, + sources?: readonly EmbeddedSource[], +): CreateRequest => create(document, [{ path: [], kind: "activity" }], sources); + +const reserve: NonNullable = () => + Promise.resolve(); + +async function write(env: LocalWriteEnvironment, request: LocalWriteRequest) { + const preview = await previewLocalWrite(env, PRINCIPAL, request); + assert.ok(preview.ok, JSON.stringify(!preview.ok && preview.error)); + const outcome = await commitLocalWrite(env, PRINCIPAL, request, { + previewToken: preview.preview.token, + ...(request.operation === "create" && request.publish !== true + ? {} + : { reserveDispatch: reserve }), + }); + assert.ok(outcome.ok, JSON.stringify(!outcome.ok && outcome.error)); + return outcome.result; +} + +async function head(db: Database, id: Uuid) { + const revision = await loadCurrentResourceRevision(db, id); + assert.ok(revision != null && revision.document != null); + return { ...revision, document: revision.document as JsonObject }; +} + +async function embeddings(db: Database, revisionId: Uuid) { + const rows = await db + .select() + .from(schema.revisionEmbeddings) + .where(eq(schema.revisionEmbeddings.revisionId, revisionId)); + return rows + .map(({ path, sourceRevisionId, relation }) => ({ + path, + sourceRevisionId, + relation, + })) + .toSorted((left, right) => + JSON.stringify(left.path).localeCompare(JSON.stringify(right.path)), + ); +} + +const withoutContext = ({ "@context": _, ...rest }: JsonObject): JsonObject => + rest; + +/** + * Saves a Note and edits it once, so that its first revision is past. + * @returns The saved Note, its first revision, and its current revision. + */ +async function savedNote(env: LocalWriteEnvironment, db: Database) { + const [note] = (await write(env, create(NOTE))).resources; + assert.ok(note != null); + const first = await head(db, note.id); + await write(env, { + operation: "edit", + actorId: localActorId, + objectId: note.id, + expectedRevisionId: first.id, + document: { ...first.document, content: "

Edited

" }, + }); + return { note, first, current: await head(db, note.id) }; +} + +describe("embedded document sources", () => { + it("records a nested new resource kept embedded as a snapshot", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const document = { + "@context": AS, + type: "Create", + to: [PUBLIC_IRI], + object: { type: "Note", content: "

Nested

", to: [PUBLIC_IRI] }, + }; + for (const representation of ["embedded", "reference"] as const) { + const [note, root] = ( + await write( + env, + create(document, [ + { path: [], kind: "activity" }, + { path: ["object"], kind: "object", representation }, + ]), + ) + ).resources; + assert.ok(note != null && root != null); + assert.deepEqual( + await embeddings(harness.db, root.revisionId), + representation === "embedded" + ? [ + { + path: ["object"], + sourceRevisionId: note.revisionId, + relation: "snapshot", + }, + ] + : [], + ); + assert.deepEqual(await embeddings(harness.db, note.revisionId), []); + } + }); + }); + + it("records the Update of an edit as a snapshot of the new version", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const [note] = (await write(env, create(NOTE))).resources; + assert.ok(note != null); + const first = await head(harness.db, note.id); + const [version, update] = ( + await write(env, { + operation: "edit", + actorId: localActorId, + objectId: note.id, + expectedRevisionId: first.id, + document: { ...first.document, content: "

B

" }, + }) + ).resources; + assert.ok(version != null && update != null); + assert.deepEqual(await embeddings(harness.db, update.revisionId), [ + { + path: ["object"], + sourceRevisionId: version.revisionId, + relation: "snapshot", + }, + ]); + assert.deepEqual(await embeddings(harness.db, version.revisionId), []); + }); + }); + + it("records a declared source as kept or derived by comparing documents", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first } = await savedNote(env, harness.db); + for (const [content, relation] of [ + ["

Hello

", "snapshot"], + ["

Changed

", "derived"], + ] as const) { + const [like] = ( + await write( + env, + activity( + { + "@context": AS, + type: "Like", + object: { ...withoutContext(first.document), content }, + to: [PUBLIC_IRI], + }, + [{ path: ["object"], revisionId: first.id }], + ), + ) + ).resources; + assert.ok(like != null); + assert.deepEqual(await embeddings(harness.db, like.revisionId), [ + { path: ["object"], sourceRevisionId: first.id, relation }, + ]); + } + }); + }); + + it("records declared sources of an edited version, not of its Update", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first } = await savedNote(env, harness.db); + const [other] = (await write(env, create(NOTE))).resources; + assert.ok(other != null); + const otherHead = await head(harness.db, other.id); + const [version, update] = ( + await write(env, { + operation: "edit", + actorId: localActorId, + objectId: other.id, + expectedRevisionId: otherHead.id, + document: { + ...otherHead.document, + location: withoutContext(first.document), + }, + sources: [{ path: ["location"], revisionId: first.id }], + }) + ).resources; + assert.ok(version != null && update != null); + assert.deepEqual(await embeddings(harness.db, version.revisionId), [ + { + path: ["location"], + sourceRevisionId: first.id, + relation: "snapshot", + }, + ]); + // The past version the Update carries has no current match. + assert.deepEqual(await embeddings(harness.db, update.revisionId), [ + { + path: ["object"], + sourceRevisionId: version.revisionId, + relation: "snapshot", + }, + ]); + }); + }); + + it("treats a different context as derived, and an equal one spelled as a list as kept", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first } = await savedNote(env, harness.db); + for (const [context, relation] of [ + [[AS], "snapshot"], + [[AS, { extra: "https://example.com/extra" }], "derived"], + ] as const) { + const [like] = ( + await write( + env, + activity( + { + "@context": context, + type: "Like", + object: withoutContext(first.document), + to: [PUBLIC_IRI], + }, + [{ path: ["object"], revisionId: first.id }], + ), + ) + ).resources; + assert.ok(like != null); + assert.deepEqual(await embeddings(harness.db, like.revisionId), [ + { path: ["object"], sourceRevisionId: first.id, relation }, + ]); + } + }); + }); + + it("matches an undeclared document only to the current snapshot it keeps", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first, current } = await savedNote(env, harness.db); + for (const [object, expected] of [ + [ + withoutContext(current.document), + [ + { + path: ["object"], + sourceRevisionId: current.id, + relation: "snapshot", + }, + ], + ], + // The past version and a changed copy have no known source. + [withoutContext(first.document), []], + [{ ...withoutContext(current.document), content: "

X

" }, []], + ] as const) { + const [like] = ( + await write( + env, + activity({ + "@context": AS, + type: "Like", + object, + to: [PUBLIC_IRI], + }), + ) + ).resources; + assert.ok(like != null); + assert.deepEqual( + await embeddings(harness.db, like.revisionId), + expected, + ); + } + }); + }); + + it("records nothing for a Link, a reference, or a deletion", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { note, current } = await savedNote(env, harness.db); + for (const object of [{ type: "Link", href: note.iri }, note.iri]) { + const [like] = ( + await write( + env, + activity({ + "@context": AS, + type: "Like", + object, + to: [PUBLIC_IRI], + }), + ) + ).resources; + assert.ok(like != null); + assert.deepEqual(await embeddings(harness.db, like.revisionId), []); + } + const [removal] = ( + await write(env, { + operation: "delete", + actorId: localActorId, + objectId: note.id, + expectedRevisionId: current.id, + }) + ).resources; + assert.ok(removal != null); + assert.deepEqual(await embeddings(harness.db, removal.revisionId), []); + }); + }); + + it("refuses invalid declarations in the preview", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { note, first } = await savedNote(env, harness.db); + const [other] = (await write(env, create(NOTE))).resources; + assert.ok(other != null); + const otherHead = await head(harness.db, other.id); + const like = { + "@context": AS, + type: "Like", + object: withoutContext(first.document), + instrument: { type: "Link", href: note.iri }, + to: [PUBLIC_IRI], + }; + const cases: [string, LocalWriteRequest][] = [ + ["root", activity(like, [{ path: [], revisionId: first.id }])], + [ + "not a document", + activity(like, [{ path: ["to", 0], revisionId: first.id }]), + ], + [ + "Link", + activity(like, [{ path: ["instrument"], revisionId: first.id }]), + ], + [ + "twice", + activity(like, [ + { path: ["object"], revisionId: first.id }, + { path: ["object"], revisionId: first.id }, + ]), + ], + [ + "another resource's revision", + activity(like, [{ path: ["object"], revisionId: otherHead.id }]), + ], + [ + "missing revision", + activity(like, [ + { path: ["object"], revisionId: MISSING_REVISION_ID }, + ]), + ], + [ + "no id", + activity( + { + ...like, + object: { type: "Note", content: "

Anonymous

" }, + }, + [{ path: ["object"], revisionId: first.id }], + ), + ], + [ + "new resource", + create( + { + "@context": AS, + type: "Create", + to: [PUBLIC_IRI], + object: { type: "Note", content: "

New

" }, + }, + [ + { path: [], kind: "activity" }, + { path: ["object"], kind: "object" }, + ], + [{ path: ["object"], revisionId: first.id }], + ), + ], + [ + "malformed", + { + ...activity(like), + sources: "object" as unknown as EmbeddedSource[], + }, + ], + [ + "malformed in an edit", + { + operation: "edit", + actorId: localActorId, + objectId: other.id, + expectedRevisionId: otherHead.id, + document: otherHead.document, + sources: [{ path: ["object"], revisionId: "nope" as Uuid }], + }, + ], + ]; + for (const [label, request] of cases) { + const preview = await previewLocalWrite(env, PRINCIPAL, request); + assert.ok(!preview.ok, label); + assert.equal(preview.error.type, "invalid_request", label); + } + }); + }); + + it("binds declared sources to the preview token", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first, current } = await savedNote(env, harness.db); + const like = { + "@context": AS, + type: "Like", + object: withoutContext(first.document), + to: [PUBLIC_IRI], + }; + const preview = await previewLocalWrite( + env, + PRINCIPAL, + activity(like, [{ path: ["object"], revisionId: first.id }]), + ); + assert.ok(preview.ok); + for (const sources of [ + undefined, + [{ path: ["object"], revisionId: current.id }], + ]) { + const outcome = await commitLocalWrite( + env, + PRINCIPAL, + activity(like, sources), + { previewToken: preview.preview.token }, + ); + assert.ok(!outcome.ok); + assert.equal(outcome.error.type, "stale_preview"); + } + assert.equal(await harness.db.$count(schema.revisionEmbeddings), 1); + }); + }); +}); diff --git a/packages/federation/src/local-write.ts b/packages/federation/src/local-write.ts index c6268b1c..ea8b23c6 100644 --- a/packages/federation/src/local-write.ts +++ b/packages/federation/src/local-write.ts @@ -40,6 +40,7 @@ export type { CreateRequest, DeleteRequest, EditRequest, + EmbeddedSource, JsonObject, LocalWriteEnvironment, LocalWriteError, diff --git a/packages/federation/src/local-write/context.ts b/packages/federation/src/local-write/context.ts new file mode 100644 index 00000000..4dfcbd4a --- /dev/null +++ b/packages/federation/src/local-write/context.ts @@ -0,0 +1,67 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import type { FieldPath, JsonValue } from "@drfed/models/document"; + +import { valueAt } from "../document/interpret.ts"; + +const ACTIVITY_STREAMS = "https://www.w3.org/ns/activitystreams"; + +/** + * Keys a path for maps and token allocations. + * @returns The path's JSON. + */ +export function pathKey(path: FieldPath): string { + return JSON.stringify(path); +} + +/** + * Lists the entries of a `@context` value, a list or one context. + * @returns The entries; none for a missing value. + */ +export function contextEntries(value: JsonValue | undefined): JsonValue[] { + if (value === undefined) return []; + return Array.isArray(value) ? [...value] : [value]; +} + +/** + * Reads the context a document embedded at a path is read with: the + * contexts of the documents along the path, its own last, after the + * ActivityStreams context the validator assumes when the root states none. + * @param document The root document. + * @param nodePaths The keys of the paths of the documents it describes, as + * {@link pathKey} spells them; other values on the path, + * such as plain JSON objects, state no context. + * @param path The embedded document's path; `[]` for the root. + * @returns The context entries, in order. + */ +export function effectiveContext( + document: JsonValue, + nodePaths: ReadonlySet, + path: FieldPath, +): JsonValue[] { + const chain: JsonValue[] = []; + for (let length = 0; length <= path.length; length += 1) { + const prefix = path.slice(0, length); + if (!nodePaths.has(pathKey(prefix))) continue; + chain.push(...contextEntries(valueAt(document, [...prefix, "@context"]))); + } + // The validator reads a document without a context as ActivityStreams. + if (valueAt(document, ["@context"]) === undefined) { + chain.unshift(ACTIVITY_STREAMS); + } + return chain; +} diff --git a/packages/federation/src/local-write/embedding.ts b/packages/federation/src/local-write/embedding.ts new file mode 100644 index 00000000..ebfe90e0 --- /dev/null +++ b/packages/federation/src/local-write/embedding.ts @@ -0,0 +1,361 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { type Database, type Transaction, schema } from "@drfed/models"; +import type { + DocumentNode, + FieldPath, + JsonValue, +} from "@drfed/models/document"; +import type { RevisionEmbeddingInput } from "@drfed/models/resource-revision"; +import type { Uuid } from "@drfed/models/uuid"; +import { and, eq, inArray } from "drizzle-orm"; + +import { + type InterpretedNode, + interpretDocument, +} from "../document/interpret.ts"; +import { effectiveContext, pathKey } from "./context.ts"; +import { + type EmbeddedSource, + type JsonObject, + type LocalWriteError, + type PreparedResource, + writeError, +} from "./types.ts"; + +const ROOT_PATHS: ReadonlySet = new Set([pathKey([])]); + +/** A stored revision an embedded document may come from. */ +export interface SourceRevision { + /** The IRI of the resource the revision belongs to. */ + readonly iri: string; + readonly kind: "snapshot" | "unavailable" | "whiteout"; +} + +/** A stored snapshot an embedding names, with its document to compare. */ +export interface SourceSnapshot { + readonly revisionId: Uuid; + readonly document: JsonValue; +} + +/** + * Loads the revisions that requests name as sources, with the IRIs of their + * resources. + * @returns The revisions by their lowercase IDs; unknown IDs are absent. + */ +export async function loadSourceRevisions( + db: Database | Transaction, + ids: readonly Uuid[], +): Promise> { + if (ids.length === 0) return new Map(); + const rows = await db + .select({ + id: schema.resourceRevisions.id, + kind: schema.resourceRevisions.kind, + iri: schema.resources.iri, + }) + .from(schema.resourceRevisions) + .innerJoin( + schema.resources, + eq(schema.resources.id, schema.resourceRevisions.resourceId), + ) + .where(inArray(schema.resourceRevisions.id, [...new Set(ids)])); + return new Map( + rows.map(({ id, kind, iri }) => [id.toLowerCase(), { iri, kind }]), + ); +} + +/** + * Checks the sources a request declares against the submitted document: + * each names, once, an embedded document that is not a `Link`, is not a new + * resource of the write, and has an `id`, and a stored snapshot of the + * resource registered under that `id`. + * @param sources The declared sources. + * @param nodes The documents the submitted document describes. + * @param newPaths The keys of the paths of the write's new resources. + * @param revisions Looks up the declared revisions. + * @returns Why a declaration is invalid, or null. + */ +export async function checkSources( + sources: readonly EmbeddedSource[], + nodes: readonly DocumentNode[], + newPaths: ReadonlySet, + revisions: ( + ids: readonly Uuid[], + ) => Promise>, +): Promise { + if (sources.length === 0) return null; + const invalid = (message: string) => writeError("invalid_request", message); + const byPath = new Map(nodes.map((node) => [pathKey(node.path), node])); + const seen = new Set(); + const named: { key: string; iri: string; revisionId: Uuid }[] = []; + for (const { path, revisionId } of sources) { + const key = pathKey(path); + if (seen.has(key)) return invalid(`The source of ${key} is listed twice.`); + seen.add(key); + const node = byPath.get(key); + if (node == null || path.length === 0 || node.kind === "link") { + return invalid(`${key} is not an embedded document.`); + } + if (newPaths.has(key)) { + return invalid(`${key} is a new resource, which has no source.`); + } + const iri = node.identifiers.find(({ property }) => property === "id")?.iri; + if (iri == null) return invalid(`${key} has no id to name its source.`); + named.push({ key, iri, revisionId }); + } + const found = await revisions(named.map(({ revisionId }) => revisionId)); + for (const { key, iri, revisionId } of named) { + const revision = found.get(revisionId.toLowerCase()); + if (revision?.kind !== "snapshot" || revision.iri !== iri) { + return invalid(`The source of ${key} is not a saved version of ${iri}.`); + } + } + return null; +} + +/** + * Compares JSON values by structure: object keys in any order, lists in + * order. + * @returns Whether the values are equal. + */ +export function sameJson(left: JsonValue, right: JsonValue): boolean { + if (left === right) return true; + if ( + left === null || + right === null || + typeof left !== "object" || + typeof right !== "object" || + Array.isArray(left) !== Array.isArray(right) + ) { + return false; + } + if (Array.isArray(left)) { + const list = right as readonly JsonValue[]; + return ( + left.length === list.length && + left.every((entry, index) => sameJson(entry, list[index]!)) + ); + } + const own = left as JsonObject; + const other = right as JsonObject; + const keys = Object.keys(own); + return ( + keys.length === Object.keys(other).length && + keys.every( + (key) => Object.hasOwn(other, key) && sameJson(own[key]!, other[key]!), + ) + ); +} + +const withoutContext = (value: JsonValue): JsonValue => { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return value; + } + const { "@context": _, ...rest } = value as JsonObject; + return rest; +}; + +/** + * Tells how an embedded document relates to a stored snapshot: it keeps the + * snapshot when it is read with the same context entries and, apart from + * their own `@context`, its JSON equals the snapshot's. + * @param document The saved document that embeds it. + * @param nodePaths The keys of the paths of the documents `document` + * describes. + * @param path The embedded document's path in `document`. + * @param value The embedded document. + * @param source The snapshot's document. + * @returns `snapshot` or `derived`. + */ +export function embeddingRelation( + document: JsonValue, + nodePaths: ReadonlySet, + path: FieldPath, + value: JsonValue, + source: JsonValue, +): RevisionEmbeddingInput["relation"] { + return sameJson( + effectiveContext(document, nodePaths, path), + effectiveContext(source, ROOT_PATHS, []), + ) && sameJson(withoutContext(value), withoutContext(source)) + ? "snapshot" + : "derived"; +} + +/** + * Reads the current snapshots of the resources registered under IRIs. + * @returns The snapshots by IRI; resources whose current revision is not a + * snapshot, and unregistered IRIs, are absent. + */ +async function currentSnapshots( + tx: Transaction, + iris: readonly string[], +): Promise> { + if (iris.length === 0) return new Map(); + const rows = await tx + .select({ + iri: schema.resources.iri, + revisionId: schema.resourceRevisions.id, + document: schema.resourceRevisions.document, + }) + .from(schema.resources) + .innerJoin( + schema.resourceHeads, + eq(schema.resourceHeads.resourceId, schema.resources.id), + ) + .innerJoin( + schema.resourceRevisions, + and( + eq( + schema.resourceRevisions.resourceId, + schema.resourceHeads.resourceId, + ), + eq(schema.resourceRevisions.id, schema.resourceHeads.revisionId), + ), + ) + .where( + and( + inArray(schema.resources.iri, [...new Set(iris)]), + eq(schema.resourceRevisions.kind, "snapshot"), + ), + ); + return new Map( + rows.map(({ iri, revisionId, document }) => [ + iri, + { revisionId, document: document as JsonValue }, + ]), + ); +} + +async function storedSnapshots( + tx: Transaction, + ids: readonly Uuid[], +): Promise> { + if (ids.length === 0) return new Map(); + const rows = await tx + .select({ + revisionId: schema.resourceRevisions.id, + document: schema.resourceRevisions.document, + }) + .from(schema.resourceRevisions) + .where( + and( + inArray(schema.resourceRevisions.id, [...new Set(ids)]), + eq(schema.resourceRevisions.kind, "snapshot"), + ), + ); + return new Map( + rows.map(({ revisionId, document }) => [ + revisionId.toLowerCase(), + { revisionId, document: document as JsonValue }, + ]), + ); +} + +/** + * Finds where the documents a saved document embeds came from, as + * `revisionEmbeddings` records it. Only embedded documents, not `Link`s, + * with an `id` other than the saved resource's own are considered, at any + * depth. Each takes its source from, in order: + * + * 1. the revision this write saved for its IRI, as a new nested resource + * or an edited object; + * 2. the revision the request declares for its submitted path, for a + * document the request submitted rather than one the server generated; + * 3. the current snapshot of the resource registered under its IRI, only + * when the embedded document keeps it. + * + * Any other has an unknown source and no row. + * @param tx The write's transaction. + * @param resource The prepared resource about to be saved. + * @param declared Declared source revisions by the keys of submitted paths. + * @param saved The snapshots this write has saved so far, by IRI. + * @returns The embeddings to save with the resource's revision. + */ +export async function findEmbeddings( + tx: Transaction, + resource: PreparedResource, + declared: ReadonlyMap, + saved: ReadonlyMap, +): Promise { + const nodes = interpretDocument(resource.document) ?? []; + const nodePaths = new Set(nodes.map(({ path }) => pathKey(path))); + const embedded = nodes.filter( + (node): node is InterpretedNode & { readonly iri: string } => + node.path.length > 0 && + node.kind !== "link" && + node.iri != null && + node.iri !== resource.iri, + ); + const declaredFor = (node: InterpretedNode): Uuid | undefined => + resource.generated + ? undefined + : declared.get(pathKey([...resource.path, ...node.path])); + const [declaredSnapshots, currentByIri] = await Promise.all([ + storedSnapshots( + tx, + embedded.flatMap((node) => { + const id = saved.has(node.iri) ? undefined : declaredFor(node); + return id == null ? [] : [id]; + }), + ), + currentSnapshots( + tx, + embedded + .filter((node) => !saved.has(node.iri) && declaredFor(node) == null) + .map(({ iri }) => iri), + ), + ]); + const relation = (node: InterpretedNode, source: SourceSnapshot) => + embeddingRelation( + resource.document, + nodePaths, + node.path, + node.value, + source.document, + ); + return embedded.flatMap((node): RevisionEmbeddingInput[] => { + const own = saved.get(node.iri); + const declaredId = own == null ? declaredFor(node) : undefined; + const source = + own ?? + (declaredId == null + ? currentByIri.get(node.iri) + : declaredSnapshots.get(declaredId.toLowerCase())); + if (source == null) return []; + const found = relation(node, source); + // An undeclared document matched by IRI alone has a source only when + // it keeps the current snapshot. + if (own == null && declaredId == null && found !== "snapshot") return []; + return [ + { path: node.path, sourceRevisionId: source.revisionId, relation: found }, + ]; + }); +} + +/** + * Indexes a request's declared sources by the keys of their paths. + * @returns The declared revision IDs. + */ +export function declaredSources( + sources: readonly EmbeddedSource[] | undefined, +): ReadonlyMap { + return new Map( + (sources ?? []).map(({ path, revisionId }) => [pathKey(path), revisionId]), + ); +} diff --git a/packages/federation/src/local-write/existing.ts b/packages/federation/src/local-write/existing.ts index 5c590757..928d88d4 100644 --- a/packages/federation/src/local-write/existing.ts +++ b/packages/federation/src/local-write/existing.ts @@ -40,9 +40,11 @@ import { Activity } from "@fedify/vocab"; import { asc, eq } from "drizzle-orm"; import type { WritingActor } from "./actor.ts"; +import { checkSources } from "./embedding.ts"; import { type IdentityLookups, checkIndexable, + checkSourceShapes, deniedClaims, indexDocument, pathKey, @@ -100,7 +102,9 @@ export function checkExistingRequest( ) { return invalid("The document must be a JSON object."); } - return null; + return request.operation === "edit" + ? checkSourceShapes(request.sources) + : null; } /** @@ -115,7 +119,15 @@ export function bindableExisting( actorId: request.actorId, objectId: request.objectId, expectedRevisionId: request.expectedRevisionId, - ...(request.operation === "edit" ? { document: request.document } : {}), + ...(request.operation === "edit" + ? { + document: request.document, + sources: (request.sources ?? []).map(({ path, revisionId }) => ({ + path, + revisionId, + })), + } + : {}), }; } @@ -413,6 +425,13 @@ export async function prepareEdit( validateDocument(submitted).diagnostics, ); } + const sourceError = await checkSources( + request.sources ?? [], + nodes, + new Set(), + lookups.revisions, + ); + if (sourceError != null) return sourceError; const root = nodes[0]!; if (root.type !== target.type) { return writeError( diff --git a/packages/federation/src/local-write/operation.ts b/packages/federation/src/local-write/operation.ts index 0e903777..e193fc0a 100644 --- a/packages/federation/src/local-write/operation.ts +++ b/packages/federation/src/local-write/operation.ts @@ -32,6 +32,7 @@ import { LegacyResourceRevisionError, ResourceRevisionStateError, RevisionConflictError, + type RevisionEmbeddingInput, appendResourceRevision, writeTypedResourceRevision, } from "@drfed/models/resource-revision"; @@ -44,6 +45,12 @@ import { localActorIris, registeredIris, } from "./actor.ts"; +import { + type SourceSnapshot, + declaredSources, + findEmbeddings, + loadSourceRevisions, +} from "./embedding.ts"; import { type WriteTarget, bindableExisting, @@ -91,6 +98,7 @@ function lookups( return { localActors: (iris) => localActorIris(db, actor.instanceId, iris), registered: (iris) => registeredIris(db, iris), + revisions: (ids) => loadSourceRevisions(db, ids), }; } @@ -231,6 +239,7 @@ async function writeObjectVersion( target: WriteTarget, object: PreparedResource, typed: TypedProjection | null | undefined, + embeddings: readonly RevisionEmbeddingInput[], ): Promise { if (target.typed != null && typed != null) { const { attributedTo: _, ...columns } = typed; @@ -242,6 +251,7 @@ async function writeObjectVersion( columns, addressingOccurrences: object.addressing, relations: object.relations, + embeddings, }); return revision.id; } @@ -254,6 +264,7 @@ async function writeObjectVersion( capture: "local", addressingOccurrences: object.addressing, relations: object.relations, + embeddings, }); await replaceAddressing(tx, target.id, object.addressing); return revision.id; @@ -416,15 +427,32 @@ export async function commitLocalWrite( allocation.timestamp, ); } + const declared = declaredSources( + request.operation === "delete" ? undefined : request.sources, + ); + // Children are saved before what embeds them, and an edited object + // before its Update, so each finds the revisions it embeds here. + const snapshots = new Map(); for (const resource of resources) { + const embeddings = await findEmbeddings( + tx, + resource, + declared, + snapshots, + ); if (target != null && resource.id === target.id) { const revisionId = await writeObjectVersion( tx, target, resource, typed, + embeddings, ); saved.push({ ...resource, revisionId }); + snapshots.set(resource.iri, { + revisionId, + document: resource.document, + }); continue; } const revision = await appendResourceRevision(tx, { @@ -436,9 +464,14 @@ export async function commitLocalWrite( capture: "local", addressingOccurrences: resource.addressing, relations: resource.relations, + embeddings, }); await storeAddressingOccurrences(tx, resource.id, resource.addressing); saved.push({ ...resource, revisionId: revision.id }); + snapshots.set(resource.iri, { + revisionId: revision.id, + document: resource.document, + }); } if (outboxed) { const activity = saved.at(-1)!; diff --git a/packages/federation/src/local-write/prepare.ts b/packages/federation/src/local-write/prepare.ts index 1179e23c..f1ab21cb 100644 --- a/packages/federation/src/local-write/prepare.ts +++ b/packages/federation/src/local-write/prepare.ts @@ -41,6 +41,8 @@ import { } from "../document/interpret.ts"; import { classifyHost } from "../origin.ts"; import type { WritingActor } from "./actor.ts"; +import { effectiveContext, pathKey } from "./context.ts"; +import { type SourceRevision, checkSources } from "./embedding.ts"; import { type Allocation, toMicroseconds } from "./token.ts"; import { type CreateRequest, @@ -69,6 +71,8 @@ export interface IdentityLookups { localActors(iris: readonly string[]): Promise>; /** The IRIs that are registered resources. */ registered(iris: readonly string[]): Promise>; + /** The stored revisions among IDs, by their lowercase IDs. */ + revisions(ids: readonly Uuid[]): Promise>; } /** The submitted documents and their saved forms, ready to persist. */ @@ -78,13 +82,7 @@ export interface PreparedWrite { readonly resources: readonly PreparedResource[]; } -/** - * Keys a path for maps and token allocations. - * @returns The path's JSON. - */ -export function pathKey(path: FieldPath): string { - return JSON.stringify(path); -} +export { pathKey } from "./context.ts"; function isPlainObject(value: unknown): value is Record { if (value === null || typeof value !== "object" || Array.isArray(value)) { @@ -105,6 +103,26 @@ function isPath(value: unknown): value is FieldPath { ); } +/** + * Checks the shape of a request's declared sources. + * @returns Why they are malformed, or null. + */ +export function checkSourceShapes(sources: unknown): LocalWriteError | null { + return sources === undefined || + (Array.isArray(sources) && + sources.every( + (source: unknown) => + isPlainObject(source) && + isPath(source.path) && + validateUuid(source.revisionId), + )) + ? null + : writeError( + "invalid_request", + "sources must be a list of paths with revision IDs.", + ); +} + /** * Checks the request's shape before anything reads its document, since the * request may come straight from a client. @@ -127,6 +145,8 @@ export function checkCreateRequest( if (!Array.isArray(request.resources)) { return invalid("resources must be an array."); } + const sourceError = checkSourceShapes(request.sources); + if (sourceError != null) return sourceError; for (const resource of request.resources as unknown[]) { if ( !isPlainObject(resource) || @@ -160,6 +180,10 @@ export function bindableRequest(request: CreateRequest): unknown { representation: representation ?? "embedded", })), publish: request.publish === true, + sources: (request.sources ?? []).map(({ path, revisionId }) => ({ + path, + revisionId, + })), }; } @@ -359,11 +383,6 @@ export async function deniedClaims( ].map((path) => ({ allowed: false, path })); } -function contextEntries(value: JsonValue | undefined): JsonValue[] { - if (value === undefined) return []; - return Array.isArray(value) ? [...value] : [value]; -} - /** * Refuses a document that spells one indexed property in several ways, as * in `to` beside an alias of it: their occurrences would share positions, @@ -438,16 +457,8 @@ function extractNested( const changes: NormalizationChange[] = []; const value = valueAt(working, path) as JsonObject; const standalone = structuredClone(value) as Record; - const chain: JsonValue[] = []; - for (let length = 0; length <= path.length; length += 1) { - const prefix = path.slice(0, length); - if (!preparedNodes.has(pathKey(prefix))) continue; - const own = valueAt(prepared, [...prefix, "@context"]); - chain.push(...contextEntries(own)); - } + const chain = effectiveContext(prepared, preparedNodes, path); const own = value["@context"]; - // The validator reads a document without a context as ActivityStreams. - if (prepared["@context"] === undefined) chain.unshift(ACTIVITY_STREAMS); if (chain.length > 0) { const context = chain.length === 1 ? chain[0]! : chain; if (JSON.stringify(context) !== JSON.stringify(own ?? null)) { @@ -515,6 +526,13 @@ export async function prepareCreate( const byPath = new Map(nodes.map((node) => [pathKey(node.path), node])); const descriptorError = checkDescriptors(request, byPath); if (descriptorError != null) return descriptorError; + const sourceError = await checkSources( + request.sources ?? [], + nodes, + new Set(request.resources.map(({ path }) => pathKey(path))), + lookups.revisions, + ); + if (sourceError != null) return sourceError; const keys = request.resources.map(({ path }) => pathKey(path)); if ( allocation.ids.size !== keys.length || diff --git a/packages/federation/src/local-write/types.ts b/packages/federation/src/local-write/types.ts index 52fa3bcd..7da7bdd9 100644 --- a/packages/federation/src/local-write/types.ts +++ b/packages/federation/src/local-write/types.ts @@ -61,6 +61,22 @@ export interface NewResource { readonly representation?: "embedded" | "reference"; } +/** + * The stored revision an embedded document of a request was derived from, + * such as a loaded `Note` changed for an experiment. A revision's readers + * may read where each document it embeds came from; the server decides + * whether the document still keeps that revision or was derived from it. + */ +export interface EmbeddedSource { + /** + * The submitted path of an embedded document with an `id`, not a `Link` + * nor a new resource of the write. + */ + readonly path: FieldPath; + /** A snapshot of the resource registered under the document's `id`. */ + readonly revisionId: Uuid; +} + /** Saves new resources: an object alone, an activity, or both nested. */ export interface CreateRequest { readonly operation: "create"; @@ -71,6 +87,8 @@ export interface CreateRequest { readonly resources: readonly NewResource[]; /** Adds the root activity to the actor's outbox; needs a reservation. */ readonly publish?: boolean; + /** Where embedded documents that are not new resources came from. */ + readonly sources?: readonly EmbeddedSource[]; } /** @@ -85,6 +103,8 @@ export interface EditRequest { readonly expectedRevisionId: Uuid; /** The complete new version, usually the loaded document changed. */ readonly document: JsonObject; + /** Where documents the new version embeds came from. */ + readonly sources?: readonly EmbeddedSource[]; } /** diff --git a/packages/graphql/README.md b/packages/graphql/README.md index c863dba2..6df0132d 100644 --- a/packages/graphql/README.md +++ b/packages/graphql/README.md @@ -97,14 +97,17 @@ the resource currently registered under its IRI, opened as the validator cannot read the document, `interpreted` is false and `diagnostics` tell why. -A revision, past ones included, is readable exactly when its resource is, as -above. Deletion hides no revision: deleting a resource appends a whiteout -and leaves the history before it readable, and deleting its author hides -none of it either, while `Resource.detail` and the other existing fields -keep hiding what was deleted. Local -histories, blind recipients included, are readable by anyone. The histories -of resources without legacy details that hold revisions received from -elsewhere are closed for now. See [resource revision internals]. +Each revision is read by evidence of its own: anyone reads local revisions, +blind recipients included, and revisions addressed to the public; members of +a local instance read what a delivery to it carried; and a revision without +such evidence is readable only while it is current and its resource is, as +above. A revision whose embedded documents came from revisions the viewer +may not read is hidden as a whole. Deletion hides no revision by itself, +while `Resource.detail` and the other existing fields keep hiding what was +deleted. `DocumentNode.source` names the revision an embedded document came +from, whether it keeps that revision's contents or was derived from it, and +whether that revision is still current, superseded, or deleted. See +[resource revision internals]. [resource revision internals]: https://drfed.org/internals/resource-revisions#graphql-reads diff --git a/packages/graphql/src/readable.ts b/packages/graphql/src/readable.ts index f64dd5b3..9a984ac6 100644 --- a/packages/graphql/src/readable.ts +++ b/packages/graphql/src/readable.ts @@ -26,8 +26,12 @@ import { instanceMembers, instances, objects, + resourceHeads, resourceRevisions, resources, + revisionAddressing, + revisionEmbeddings, + revisionReceipts, } from "@drfed/models/schema"; import { type Uuid, validateUuid } from "@drfed/models/uuid"; import { @@ -122,11 +126,17 @@ const visibleOwners = alias(actors, "visible_owners"); const ownedObjects = alias(objects, "visible_objects"); const ownedActivities = alias(activities, "visible_activities"); const ownedCollections = alias(collections, "visible_collections"); -const typedActors = alias(actors, "history_actors"); -const typedObjects = alias(objects, "history_objects"); -const typedActivities = alias(activities, "history_activities"); -const typedCollections = alias(collections, "history_collections"); -const capturedRevisions = alias(resourceRevisions, "history_revisions"); +const typedActors = alias(actors, "legacy_typed_actors"); +const typedObjects = alias(objects, "legacy_typed_objects"); +const typedActivities = alias(activities, "legacy_typed_activities"); +const typedCollections = alias(collections, "legacy_typed_collections"); +const evidenced = alias(resourceRevisions, "evidenced_revisions"); +const evidencedAddressing = alias(revisionAddressing, "evidenced_addressing"); +const evidencedReceipts = alias(revisionReceipts, "evidenced_receipts"); +const receiptDeliveries = alias(activityDeliveries, "receipt_deliveries"); +const evidencedHeads = alias(resourceHeads, "evidenced_heads"); +const embedded = alias(revisionEmbeddings, "embedded_sources"); +const transitive = alias(revisionEmbeddings, "transitive_sources"); const remoteActivity = (id: SQLWrapper): SQL => sql`exists ( select 1 from ${activities} ${remoteActivities} @@ -215,7 +225,7 @@ export function readableResource(viewer: Viewer, id: SQLWrapper): SQL { * Excludes deleted actors and objects, including resources authored or * owned by deleted actors. Revisions do not use it: a deletion appends a * whiteout, and the history before it stays readable, as - * {@link readableHistory} tells. + * {@link readableRevision} tells. * @param id The resource ID in an outer query. * @returns The condition on the ID. */ @@ -239,32 +249,11 @@ export function visibleResource(id: SQLWrapper): SQL { )`; } -/** - * Matches a generic resource, one without a legacy typed row, with a - * revision DrFed did not save itself: received, embedded or fetched. - * - * PENDING TEAM DECISION: no evidence opens such a history yet, since the - * rules of {@link readableResource} are those of typed rows, and no write - * path creates such resources yet. Until the team decides what opens them, - * their revisions are closed, while the resource itself, its IRI and kind, - * stays readable as before. This is the one place that rule lives; - * {@link readableHistory} applies it. - * @param id The resource ID in an outer query. - * @returns The condition on the ID. - */ -export function unprovenGenericHistory(id: SQLWrapper): SQL { - return sql`(not ${legacyTypedRow(id)} and exists ( - select 1 from ${resourceRevisions} ${capturedRevisions} - where ${capturedRevisions.resourceId} = ${id} - and ${capturedRevisions.capture} <> 'local' - ))`; -} - /** * Matches a resource with a legacy typed row, whose readability * {@link readableResource} decides by that row. It is the only place - * {@link unprovenGenericHistory} reads legacy typed tables, so that it goes - * when they do. + * {@link readableRevision} reads legacy typed tables, so that it goes when + * they do. * @param id The resource ID in an outer query. * @returns The condition on the ID. */ @@ -280,23 +269,77 @@ function legacyTypedRow(id: SQLWrapper): SQL { ))`; } +// What a revision itself proves of who may read it, whatever it embeds. +const ownEvidence = (viewer: Viewer, id: SQLWrapper): SQL => sql`exists ( + select 1 from ${resourceRevisions} ${evidenced} + where ${evidenced.id} = ${id} and ( + ${evidenced.capture} = 'local' + or exists ( + select 1 from ${revisionAddressing} ${evidencedAddressing} + where ${evidencedAddressing.revisionId} = ${evidenced.id} + and ${inArray(evidencedAddressing.iri, PUBLIC_IRIS)} + ) + or exists ( + select 1 from ${revisionReceipts} ${evidencedReceipts} + join ${activityDeliveries} ${receiptDeliveries} + on ${receiptDeliveries.id} = ${evidencedReceipts.deliveryId} + where ${evidencedReceipts.revisionId} = ${evidenced.id} + and ${receiptDeliveries.direction} = 'inbound' + and ${viewableInstance(viewer, receiptDeliveries.instanceId)} + ) + or ( + exists ( + select 1 from ${resourceHeads} ${evidencedHeads} + where ${evidencedHeads.resourceId} = ${evidenced.resourceId} + and ${evidencedHeads.revisionId} = ${evidenced.id} + ) + and ${legacyTypedRow(evidenced.resourceId)} + and ${readableResource(viewer, evidenced.resourceId)} + ) + ) +)`; + /** - * Restricts resources to those whose revisions the viewer may read. Every - * revision, past ones included, follows the rule of its resource: it must be - * readable, as {@link readableResource} tells, and its history must not be - * one {@link unprovenGenericHistory} closes. Local resources are therefore - * readable by anyone, with their blind recipients and whether published or - * not, as `Object.document` is. Deletion hides no revision: it appends a - * whiteout, and the history before it, of a deleted resource or of one - * whose author is deleted, stays readable to whoever may read the resource. - * Readability is the existing rule, which still reads legacy typed rows; - * everything else about revisions is read from the revisions themselves. + * Restricts revisions to those the viewer may read. An administrator reads + * every revision. Anyone else reads a revision by evidence of that + * particular revision, never by the current state of its resource: + * + * - Its own evidence: DrFed saved it for a local actor, so it is readable + * by anyone, with its blind recipients and whether published or not, as + * `Object.document` is; its own addressing is public; a receipt links it + * to an inbound delivery to a local instance the viewer may read, as + * {@link viewableInstance} tells; or it is the current revision of a + * resource with a legacy typed row that {@link readableResource} lets + * the viewer read, since that row describes only its current version. + * - The evidence of what it embeds: every revision its recorded + * embeddings name as their sources, and theirs in turn, must have its + * own evidence too. A local document embedding a private received + * revision is thus readable only by those who could read that revision, + * including when it was derived from it. + * + * A later revision being restricted, or deleted, hides no earlier one that + * was public, and a later delivery or public revision of the same IRI opens + * no earlier private one. A revision of a deleted resource, or of one + * whose author is deleted, stays readable to whoever may read it. * @param viewer The viewer and the database. - * @param id The resource ID in an outer query. + * @param id The revision ID in an outer query. * @returns The condition on the ID. */ -export function readableHistory(viewer: Viewer, id: SQLWrapper): SQL { - return and(readableResource(viewer, id), not(unprovenGenericHistory(id)))!; +export function readableRevision(viewer: Viewer, id: SQLWrapper): SQL { + if (viewer.account?.admin === true) return sql`true`; + // Sources are stored before what embeds them, so the recursion ends; the + // union stops it on a cycle all the same. + return sql`(${ownEvidence(viewer, id)} and not exists ( + with recursive readable_sources(id) as ( + select ${embedded.sourceRevisionId} from ${revisionEmbeddings} ${embedded} + where ${embedded.revisionId} = ${id} + union + select ${transitive.sourceRevisionId} from ${revisionEmbeddings} ${transitive} + join readable_sources on readable_sources.id = ${transitive.revisionId} + ) + select 1 from readable_sources + where not ${ownEvidence(viewer, sql`readable_sources.id`)} + ))`; } /** @@ -341,9 +384,9 @@ const uuidOf = (node: unknown, key: "id" | "resourceId"): Uuid | null => /** * Tells the resource a Relay node belongs to without being its typed detail, - * as a revision belongs to its resource. Such a node is hidden as that - * resource's history is, by {@link readableHistory}, and nothing of its own, - * such as a whiteout's deletion time, hides it. + * as a revision belongs to its resource. Such a node is hidden by its own + * readability, as {@link readableRevision} tells, and nothing of its + * resource's, such as a deletion, hides it. * @returns The resource ID, or null for any other node. */ export const owningResourceOf = (node: unknown): Uuid | null => @@ -353,40 +396,46 @@ export const owningResourceOf = (node: unknown): Uuid | null => * Replaces the Relay nodes the viewer may not read by null, as if they did * not exist. Activities, objects, and resources share their IDs, so a node's * ID alone tells whether it is one the viewer may not read; a node that - * belongs to a resource, such as a revision, is checked against that - * resource's history instead, as {@link owningResourceOf} tells. + * belongs to a resource, such as a revision, is checked by + * {@link readableRevision} instead, as {@link owningResourceOf} tells. * @returns The nodes, in the same order. */ export async function hideUnreadableNodes( viewer: Viewer, nodes: readonly unknown[], ): Promise { - const owningIds = nodes.map(owningResourceOf); + const owned = nodes.map((node) => + owningResourceOf(node) == null ? null : uuidOf(node, "id"), + ); const ids = nodes.map((node, index) => - owningIds[index] == null ? uuidOf(node, "id") : null, + owned[index] == null && owningResourceOf(node) == null + ? uuidOf(node, "id") + : null, ); - const owned = [...new Set(owningIds.filter((id) => id != null))]; - const [hidden, readableOwners] = await Promise.all([ + const revisionIds = [...new Set(owned.filter((id) => id != null))]; + const [hidden, readableRevisions] = await Promise.all([ unreadableResources( viewer, ids.filter((id) => id != null), ), - owned.length === 0 + revisionIds.length === 0 ? [] : viewer.db - .select({ id: resources.id }) - .from(resources) + .select({ id: resourceRevisions.id }) + .from(resourceRevisions) .where( and( - inArray(resources.id, owned), - readableHistory(viewer, resources.id), + inArray(resourceRevisions.id, revisionIds), + readableRevision(viewer, resourceRevisions.id), ), ), ]); - const open = new Set(readableOwners.map(({ id }) => id)); + const open = new Set(readableRevisions.map(({ id }) => id)); return nodes.map((node, index) => { - const owner = owningIds[index]; - if (owner != null) return open.has(owner) ? node : null; + if (owningResourceOf(node) != null) { + const id = owned[index]; + return id != null && open.has(id) ? node : null; + } const id = ids[index]; return id != null && hidden.has(id) ? null : node; }); diff --git a/packages/graphql/src/revision.test.ts b/packages/graphql/src/revision.test.ts index 44a8ab6f..fb5222a5 100644 --- a/packages/graphql/src/revision.test.ts +++ b/packages/graphql/src/revision.test.ts @@ -38,11 +38,14 @@ import { import { type Uuid, uuidV7 } from "@drfed/models/uuid"; import { eq } from "drizzle-orm"; +import { hashSecret } from "./auth/hash.ts"; import { type TestHarness, withTestHarness } from "./harness.test.ts"; import { accountId, + created, globalId, localActorId, + localInstanceId, remoteActorId, seedAuthenticatedLocalInstance, seedLocalActor, @@ -872,3 +875,340 @@ describe("Access to revisions", () => { }); }); }); + +/** + * Signs in an account that is no member of the local instance, or an + * administrator. + * @returns The request options that authenticate as it. + */ +async function seedViewer(db: Database, admin: boolean): Promise { + const id = uuidV7(); + const token = `token-${id}`; + await db.insert(schema.accounts).values({ + id, + email: `${id}@example.com`, + name: admin ? "Admin" : "Outsider", + admin, + created, + }); + await db.insert(schema.sessions).values({ + id: uuidV7(), + accountId: id, + tokenHash: await hashSecret(token), + }); + return { headers: { authorization: `Bearer ${token}` } }; +} + +/** + * Stores a revision received from elsewhere, addressed as given. + * @returns Its resource's IRI and the revision ID. + */ +async function receive( + db: Database, + iri: string, + to: readonly string[], + content: string, +): Promise<{ resourceId: Uuid; revisionId: Uuid }> { + const resource = await ensureResource(db, iri); + const current = await loadCurrentResourceRevision(db, resource.id); + const revision = await appendResourceRevision(db, { + resourceId: resource.id, + resourceKind: "object", + expectedRevisionId: current?.id ?? null, + kind: "snapshot", + capture: "received", + document: { "@context": AS, id: iri, type: "Note", content, to: [...to] }, + addressing: { to: [...to] }, + }); + return { resourceId: resource.id, revisionId: revision.id }; +} + +/** Links a revision to an inbound delivery to the local instance. */ +async function receipt(db: Database, revision: Uuid): Promise { + const deliveryId = uuidV7(); + await db.insert(schema.activityDeliveries).values({ + id: deliveryId, + instanceId: localInstanceId, + direction: "inbound", + status: "received", + verificationResult: "verified", + inboxUrl: `${ACTOR_IRI}/inbox`, + body: Buffer.from(""), + completed: Temporal.Now.instant(), + }); + await db + .insert(schema.revisionReceipts) + .values({ deliveryId, revisionId: revision, role: "object" }); +} + +/** + * Saves a local activity that embeds a document as its `object`, with the + * embedding recorded when a source is given. + * @returns The activity's resource ID and its revision ID. + */ +async function embed( + db: Database, + type: string, + object: JsonObject, + source?: { revisionId: Uuid; relation: "snapshot" | "derived" }, +): Promise<{ resourceId: Uuid; revisionId: Uuid }> { + const resource = await ensureResource(db, `${ACTOR_IRI}/${uuidV7()}`); + const revision = await appendResourceRevision(db, { + resourceId: resource.id, + resourceKind: "activity", + expectedRevisionId: null, + kind: "snapshot", + capture: "local", + document: { + "@context": AS, + id: resource.iri, + type, + actor: ACTOR_IRI, + object, + }, + ...(source == null + ? {} + : { + embeddings: [ + { + path: ["object"], + sourceRevisionId: source.revisionId, + relation: source.relation, + }, + ], + }), + }); + return { resourceId: resource.id, revisionId: revision.id }; +} + +const withoutContext = ({ "@context": _, ...rest }: JsonObject): JsonObject => + rest; + +describe("Access to revisions by their embeddings", () => { + it("opens a document embedding a private received revision only to its readers", async () => { + await withWriter(async ({ harness, auth, query }) => { + const { db } = harness; + const iri = `https://remote.example/notes/${uuidV7()}`; + const followers = "https://remote.example/users/carol/followers"; + const received = await receive(db, iri, [followers], "secret"); + await receipt(db, received.revisionId); + const stored = await loadCurrentResourceRevision(db, received.resourceId); + const announce = await embed( + db, + "Announce", + withoutContext(stored!.document as JsonObject), + { revisionId: received.revisionId, relation: "snapshot" }, + ); + // An intermediate local revision carries the requirement on. + const announced = await loadCurrentResourceRevision( + db, + announce.resourceId, + ); + const undo = await embed( + db, + "Undo", + withoutContext(announced!.document as JsonObject), + { revisionId: announce.revisionId, relation: "snapshot" }, + ); + const read = `query($announce: ID!, $announceRevision: ID!, $undo: ID!, $undoRevision: ID!) { + announcement: node(id: $announce) { ... on Resource { + currentRevision { id } revisions { edges { node { id } } } + } } + announceRevision: node(id: $announceRevision) { ... on ResourceRevision { id } } + undoing: node(id: $undo) { ... on Resource { currentRevision { id } } } + undoRevisions: nodes(ids: [$undoRevision]) { id } + }`; + const variables = { + announce: globalId("Resource", announce.resourceId), + announceRevision: revisionId(announce.revisionId), + undo: globalId("Resource", undo.resourceId), + undoRevision: revisionId(undo.revisionId), + }; + const open = { + data: { + announcement: { + currentRevision: { id: variables.announceRevision }, + revisions: { + edges: [{ node: { id: variables.announceRevision } }], + }, + }, + announceRevision: { id: variables.announceRevision }, + undoing: { currentRevision: { id: variables.undoRevision } }, + undoRevisions: [{ id: variables.undoRevision }], + }, + }; + const closed = { + data: { + announcement: { currentRevision: null, revisions: { edges: [] } }, + announceRevision: null, + undoing: { currentRevision: null }, + undoRevisions: [null], + }, + }; + const outsider = await seedViewer(db, false); + const admin = await seedViewer(db, true); + for (const init of [undefined, outsider]) { + const response = await harness.post({ query: read, variables }, init); + assert.deepEqual(await response.json(), closed); + } + for (const init of [auth, admin]) { + assert.deepEqual(await query(read, variables, init), open); + } + }); + }); + + it("keeps an earlier public revision readable after a private one", async () => { + await withWriter(async ({ harness, query }) => { + const { db } = harness; + const iri = `https://remote.example/notes/${uuidV7()}`; + const first = await receive(db, iri, [PUBLIC_IRI], "public"); + await receive(db, iri, ["https://remote.example/users/carol"], "private"); + const stored = (await db.query.resourceRevisions.findFirst({ + where: { id: first.revisionId }, + }))!; + const like = await embed( + db, + "Like", + withoutContext(stored.document as JsonObject), + { revisionId: first.revisionId, relation: "snapshot" }, + ); + const read = `query($id: ID!, $like: ID!) { + node(id: $id) { ... on Resource { + currentRevision { id } + revisions { edges { node { sequence document } } } + } } + like: node(id: $like) { ... on Resource { currentRevision { root { + relations(property: object) { node { source { + relation status revision { sequence } + } } } + } } } } + }`; + const variables = { + id: globalId("Resource", first.resourceId), + like: globalId("Resource", like.resourceId), + }; + const sourceOf = (status: string | null) => ({ + currentRevision: { + root: { + relations: [ + { + node: { + source: { + relation: "snapshot", + status, + revision: { sequence: 1 }, + }, + }, + }, + ], + }, + }, + }); + const response = await harness.post({ query: read, variables }); + const text = await response.text(); + assert.ok(!text.includes('"private"')); + assert.deepEqual(JSON.parse(text), { + data: { + node: { + currentRevision: null, + revisions: { + edges: [{ node: { sequence: 1, document: stored.document } }], + }, + }, + // Whether a later revision exists is not told without reading it. + like: sourceOf(null), + }, + }); + const admin = await seedViewer(db, true); + const body = await query(read, variables, admin); + assert.equal(body.data?.node.revisions.edges.length, 2); + assert.deepEqual(body.data?.like, sourceOf("superseded")); + }); + }); +}); + +describe("DocumentNode.source", () => { + const source = `query($id: ID!) { node(id: $id) { ... on Resource { + currentRevision { root { source { relation } relations(property: object) { + node { source { relation status revision { id sequence } } } + } } } + } } }`; + + const read = async ( + query: Writer["query"], + resourceId: Uuid, + ): Promise => { + const body = await query(source, { id: globalId("Resource", resourceId) }); + assert.equal(body.errors, undefined); + const root = body.data?.node.currentRevision.root; + // The root is no embedded document. + assert.equal(root.source, null); + return root.relations[0].node.source; + }; + + it("tells snapshots and derived documents and where their sources stand", async () => { + await withWriter(async ({ harness, query }) => { + const { db } = harness; + const note = await ensureResource(db, `${ACTOR_IRI}/notes/${uuidV7()}`); + const document = { id: note.iri, type: "Note", content: "1" }; + const first = await appendResourceRevision(db, { + resourceId: note.id, + resourceKind: "object", + expectedRevisionId: null, + kind: "snapshot", + capture: "local", + document: { "@context": AS, ...document }, + }); + const create = await embed(db, "Create", document, { + revisionId: first.id, + relation: "snapshot", + }); + const announce = await embed( + db, + "Announce", + { ...document, content: "changed" }, + { revisionId: first.id, relation: "derived" }, + ); + const pasted = await embed(db, "Like", document); + const expected = (relation: string, status: string) => ({ + relation, + status, + revision: { id: revisionId(first.id), sequence: 1 }, + }); + assert.deepEqual( + await read(query, create.resourceId), + expected("snapshot", "current"), + ); + assert.deepEqual( + await read(query, announce.resourceId), + expected("derived", "current"), + ); + // A document embedded without a recorded source has an unknown one. + assert.equal(await read(query, pasted.resourceId), null); + const second = await appendResourceRevision(db, { + resourceId: note.id, + resourceKind: "object", + expectedRevisionId: first.id, + kind: "snapshot", + capture: "local", + document: { "@context": AS, ...document, content: "2" }, + }); + assert.deepEqual( + await read(query, create.resourceId), + expected("snapshot", "superseded"), + ); + await appendResourceRevision(db, { + resourceId: note.id, + resourceKind: "object", + expectedRevisionId: second.id, + kind: "whiteout", + deleted: Temporal.Now.instant(), + formerTypes: ["Note"], + }); + assert.deepEqual( + await read(query, create.resourceId), + expected("snapshot", "deleted"), + ); + }); + }); +}); diff --git a/packages/graphql/src/revision.ts b/packages/graphql/src/revision.ts index 482ba2c1..66573b25 100644 --- a/packages/graphql/src/revision.ts +++ b/packages/graphql/src/revision.ts @@ -32,11 +32,13 @@ import { import type { ResourceRevision as ResourceRevisionRow, Resource as ResourceRow, + RevisionEmbedding, } from "@drfed/models/schema"; +import type { Uuid } from "@drfed/models/uuid"; import { and, eq, inArray } from "drizzle-orm"; import builder, { type DrFedObjectRef, type UserContext } from "./builder.ts"; -import { readableHistory, readableResource } from "./readable.ts"; +import { readableResource, readableRevision } from "./readable.ts"; import { Resource } from "./resource.ts"; const ACTIVITY_STREAMS = "https://www.w3.org/ns/activitystreams#"; @@ -152,6 +154,44 @@ DocumentDiagnostic.implement({ }), }); +const DocumentSourceRelation = builder.enumType("DocumentSourceRelation", { + description: + "How an embedded document relates to the revision it came from, as " + + "recorded when the document embedding it was saved.", + values: { + snapshot: { + description: + "It keeps the source revision's contents, apart from the context " + + "it inherits from the document embedding it.", + }, + derived: { + description: + "It started from the source revision and was changed, as a test " + + "input with other addressing or an altered property.", + }, + } satisfies Record, +}); +const DocumentSourceStatus = builder.enumType("DocumentSourceStatus", { + description: + "Where the source revision stands in its resource's history. It " + + "compares revisions, not contents.", + values: { + current: { description: "It is the resource's current revision." }, + superseded: { + description: + "A later revision is current, which may have the same contents.", + }, + deleted: { description: "The resource's current revision is a whiteout." }, + }, +}); + +/** An embedding of a revision, with the source it names. */ +interface Source { + readonly relation: RevisionEmbedding["relation"]; + readonly revision: ResourceRevisionRow; +} +const DocumentSource = builder.objectRef("DocumentSource"); + const DocumentNode = builder.objectRef("DocumentNode"); const DocumentRelation = builder.objectRef("DocumentRelation"); @@ -194,6 +234,102 @@ function registeredResource( return lookup; } +// The revision each interpreted node belongs to. +const nodeRevisions = new WeakMap(); + +const embeddingLookups = new WeakMap< + UserContext, + Map>> +>(); + +/** + * Loads the recorded embeddings of a revision by their paths, once per + * request. + * @returns The embeddings, keyed by the JSON of their paths. + */ +function embeddingsOf( + ctx: UserContext, + revisionId: Uuid, +): Promise> { + let lookups = embeddingLookups.get(ctx); + if (lookups == null) { + lookups = new Map(); + embeddingLookups.set(ctx, lookups); + } + let lookup = lookups.get(revisionId); + if (lookup == null) { + lookup = (async () => + new Map( + ( + await ctx.db + .select() + .from(schema.revisionEmbeddings) + .where(eq(schema.revisionEmbeddings.revisionId, revisionId)) + ).map((row) => [JSON.stringify(row.path), row]), + ))(); + lookups.set(revisionId, lookup); + } + return lookup; +} + +/** + * Finds the recorded source of an embedded document, when the viewer may + * read the source revision. + * @returns The source, or null for the root, for a document whose source is + * unknown, and for a source the viewer may not read. + */ +async function sourceOf( + ctx: UserContext, + node: InterpretedNode, +): Promise { + const revisionId = nodeRevisions.get(node); + if (revisionId == null || node.path.length === 0) return null; + const embedding = (await embeddingsOf(ctx, revisionId)).get( + JSON.stringify(node.path), + ); + if (embedding == null) return null; + const revision = await ctx.db.query.resourceRevisions.findFirst({ + where: { + id: embedding.sourceRevisionId, + RAW: (table) => readableRevision(ctx, table.id), + }, + }); + return revision == null ? null : { relation: embedding.relation, revision }; +} + +/** + * Tells where a source revision stands against its resource's current + * revision. An `unavailable` current revision, a legacy typed row without a + * retained document, is a later revision like any other. + * @returns The status, or null when the viewer may not read the current + * revision. + */ +async function statusOf( + ctx: UserContext, + revision: ResourceRevisionRow, +): Promise<"current" | "superseded" | "deleted" | null> { + const [current] = await ctx.db + .select({ + id: schema.resourceRevisions.id, + kind: schema.resourceRevisions.kind, + }) + .from(schema.resourceHeads) + .innerJoin( + schema.resourceRevisions, + eq(schema.resourceRevisions.id, schema.resourceHeads.revisionId), + ) + .where( + and( + eq(schema.resourceHeads.resourceId, revision.resourceId), + readableRevision(ctx, schema.resourceRevisions.id), + ), + ) + .limit(1); + if (current == null) return null; + if (current.id === revision.id) return "current"; + return current.kind === "whiteout" ? "deleted" : "superseded"; +} + const occurrenceFields = { representation: { description: @@ -343,10 +479,44 @@ DocumentNode.implement({ description: "Its own custom extension properties, by their source keys, sorted.", }), + source: t.field({ + type: DocumentSource, + nullable: true, + description: + "The revision this embedded document came from, as recorded when " + + "the document embedding it was saved. Null for the root, for an " + + "embedded document whose source is unknown, such as one saved " + + "before sources were recorded or pasted without one, and when the " + + "viewer may not read the source revision.", + resolve: (node, _, ctx) => sourceOf(ctx, node), + }), + }), +}); + +DocumentSource.implement({ + description: + "The revision an embedded document came from. The viewer may read it, " + + "since a revision is readable only to those who may read its sources.", + fields: (t) => ({ + relation: t.expose("relation", { type: DocumentSourceRelation }), + revision: t.field({ + type: ResourceRevisionRef, + description: "The source revision, of the resource the document names.", + resolve: (source) => source.revision, + }), + status: t.field({ + type: DocumentSourceStatus, + nullable: true, + description: + "Whether the source revision is still current, or a later revision " + + "or a deletion followed it; null when the viewer may not read the " + + "resource's current revision.", + resolve: (source, _, ctx) => statusOf(ctx, source.revision), + }), }), }); -type Content = Pick; +type Content = Pick; const interpretations = new WeakMap(); const validations = new WeakMap(); @@ -358,12 +528,12 @@ const validations = new WeakMap(); */ function rootOf(revision: Content): InterpretedNode | null { if (!interpretations.has(revision)) { - interpretations.set( - revision, + const nodes = revision.kind === "snapshot" - ? (interpretDocument(revision.document)?.[0] ?? null) - : null, - ); + ? interpretDocument(revision.document) + : null; + for (const node of nodes ?? []) nodeRevisions.set(node, revision.id); + interpretations.set(revision, nodes?.[0] ?? null); } return interpretations.get(revision)!; } @@ -380,18 +550,24 @@ function diagnosticsOf(revision: Content): readonly Diagnostic[] { return diagnostics; } -const content = { columns: { kind: true, document: true } } as const; +const content = { columns: { id: true, kind: true, document: true } } as const; const ResourceRevisionRef = builder.drizzleNode("resourceRevisions", { name: "ResourceRevision", description: - "An immutable revision of a resource. Every revision, past ones " + - "included, is readable exactly when its resource's history is: a local " + - "resource's by anyone, blind recipients and unpublished activities " + - "included; a remote one's as `Activity` and `Object` tell; never one " + - "hidden by a deletion. A revision the viewer may not read is left out " + - "as if it did not exist.", - // A node lookup checks the revision against its resource. + "An immutable revision of a resource. Each revision, past ones " + + "included, is readable by evidence of its own, not by the current " + + "state of its resource: one saved by DrFed for a local actor by anyone, " + + "blind recipients and unpublished activities included; one addressed " + + "to the public by anyone; one a receipt links to a delivery to a local " + + "instance the viewer is a member of by its members; and the current " + + "revision of a resource with a legacy typed row as `Activity` and " + + "`Object` tell. A revision whose embedded documents came from other " + + "revisions is readable only by those who may read every one of them, " + + "and theirs in turn. Administrators read every revision. A later " + + "restriction or deletion of the resource hides no earlier revision. A " + + "revision the viewer may not read is left out as if it did not exist.", + // A node lookup checks the revision by its own ID. select: { columns: { id: true, resourceId: true } }, id: { column: (revision) => revision.id }, fields: (t) => ({ @@ -469,7 +645,7 @@ builder.drizzleObjectField("resources", "currentRevision", (t) => nullable: true, description: "The current revision; null for a resource without revisions, or when " + - "the viewer may not read the resource's revisions.", + "the viewer may not read the current revision.", select: { columns: { id: true } }, resolve: async (resource, _, ctx) => (await ctx.db.query.resourceRevisions.findFirst({ @@ -483,7 +659,7 @@ builder.drizzleObjectField("resources", "currentRevision", (t) => .from(schema.resourceHeads) .where(eq(schema.resourceHeads.resourceId, resource.id)), ), - readableHistory(ctx, table.resourceId), + readableRevision(ctx, table.id), )!, }, })) ?? null, @@ -495,10 +671,10 @@ builder.drizzleObjectField("resources", "revisions", (t) => "revisions", { description: - "Every revision, newest first. Empty when the viewer may not read " + - "the resource's revisions.", + "The revisions the viewer may read, newest first. Others are left " + + "out, so sequences may skip.", query: (_, ctx) => ({ - where: { RAW: (table) => readableHistory(ctx, table.resourceId) }, + where: { RAW: (table) => readableRevision(ctx, table.id) }, orderBy: { sequence: "desc" }, }), }, diff --git a/packages/models/drizzle/20261113080536_revision_embeddings/migration.sql b/packages/models/drizzle/20261113080536_revision_embeddings/migration.sql new file mode 100644 index 00000000..623e7389 --- /dev/null +++ b/packages/models/drizzle/20261113080536_revision_embeddings/migration.sql @@ -0,0 +1,14 @@ +CREATE TYPE "revision_embedding_relation" AS ENUM('snapshot', 'derived');--> statement-breakpoint +CREATE TABLE "revision_embeddings" ( + "revision_id" uuid, + "path" jsonb, + "source_revision_id" uuid NOT NULL, + "relation" "revision_embedding_relation" NOT NULL, + CONSTRAINT "revision_embeddings_pkey" PRIMARY KEY("revision_id","path"), + CONSTRAINT "revision_embeddings_path_check" CHECK (jsonb_typeof("path") = 'array' AND jsonb_array_length("path") > 0), + CONSTRAINT "revision_embeddings_source_check" CHECK ("source_revision_id" <> "revision_id") +); +--> statement-breakpoint +CREATE INDEX "revision_embeddings_source_index" ON "revision_embeddings" ("source_revision_id");--> statement-breakpoint +ALTER TABLE "revision_embeddings" ADD CONSTRAINT "revision_embeddings_revision_id_resource_revisions_id_fkey" FOREIGN KEY ("revision_id") REFERENCES "resource_revisions"("id") ON DELETE RESTRICT;--> statement-breakpoint +ALTER TABLE "revision_embeddings" ADD CONSTRAINT "revision_embeddings_source_revision_fkey" FOREIGN KEY ("source_revision_id") REFERENCES "resource_revisions"("id") ON DELETE RESTRICT; \ No newline at end of file diff --git a/packages/models/drizzle/20261113080536_revision_embeddings/snapshot.json b/packages/models/drizzle/20261113080536_revision_embeddings/snapshot.json new file mode 100644 index 00000000..34ddb991 --- /dev/null +++ b/packages/models/drizzle/20261113080536_revision_embeddings/snapshot.json @@ -0,0 +1,4634 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "f867ba22-2861-4e0b-a6c6-4c560fc4682e", + "prevIds": ["871c1f3c-b3f3-4880-9f18-bb1e3a844354"], + "ddl": [ + { + "values": ["inbound", "outbound"], + "name": "activity_delivery_direction", + "entityType": "enums", + "schema": "public" + }, + { + "values": [ + "received", + "acknowledged", + "unverified", + "rejected", + "queued", + "sent", + "failed", + "permanently_failed", + "abandoned" + ], + "name": "activity_delivery_status", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["http_signature", "ld_signature", "object_integrity_proof"], + "name": "activity_delivery_verification_mechanism", + "entityType": "enums", + "schema": "public" + }, + { + "values": [ + "verified", + "invalid_signature", + "key_fetch_error", + "no_signature", + "unattempted", + "unobserved" + ], + "name": "activity_delivery_verification_result", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Create"], + "name": "activity_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Application", "Group", "Organization", "Person", "Service"], + "name": "actor_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["to", "cc", "bto", "bcc", "audience"], + "name": "addressing_property", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["followers", "following", "featured", "outbox"], + "name": "collection_role", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Collection", "OrderedCollection"], + "name": "collection_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["RSASSA-PKCS1-v1_5", "Ed25519"], + "name": "local_actor_key_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Article", "Note"], + "name": "object_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["actor", "object", "activity", "collection", "unknown"], + "name": "resource_kind", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["local", "received", "embedded", "fetched"], + "name": "resource_revision_capture", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["snapshot", "unavailable", "whiteout"], + "name": "resource_revision_kind", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["partial", "complete"], + "name": "resource_revision_projection", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["snapshot", "derived"], + "name": "revision_embedding_relation", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["activity", "object"], + "name": "revision_receipt_role", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["reference", "embedded", "link"], + "name": "revision_relation_representation", + "entityType": "enums", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "accounts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_deliveries", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_delivery_actor_collections", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_delivery_actors", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "actor_collection_references", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "actors", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "addressing", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "collection_items", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "collections", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "instance_members", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "instances", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "key_versions", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "keys", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "local_actor_keys", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "local_actors", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "local_instances", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "login_challenges", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "objects", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "resource_heads", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "resource_revisions", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "resources", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_addressing", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_embeddings", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_receipts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_relations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "sessions", + "entityType": "tables", + "schema": "public" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "email", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "varchar(100)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "10", + "generated": null, + "identity": null, + "name": "max_instances", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "admin", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "activity_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "object_id", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "published", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "instance_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_direction", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "direction", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_status", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_verification_mechanism", + "typeSchema": "public", + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "verification_mechanism", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_verification_result", + "typeSchema": "public", + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "verification_result", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "types", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "carried_snapshot", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "fetched_object", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "carried_object_snapshot", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "object_type", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "object_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "signed_key_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "verification_key_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_actor_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_host", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "inbox_url", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "request_url", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "headers", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "bytea", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "body", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status_code", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "response_body", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "error", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "payload", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "recipient_iris", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "completed", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "collection_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "inbox_owner", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "addressed", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "addressed_directly", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "sender", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "succeeded", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status_code", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "response_body", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "error", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "actor_collection_references" + }, + { + "type": "collection_role", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "role", + "entityType": "columns", + "schema": "public", + "table": "actor_collection_references" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "collection_id", + "entityType": "columns", + "schema": "public", + "table": "actor_collection_references" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "local_id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "actor_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "username", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "instance_id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "inbox_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "followers_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "profile_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "avatar_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "header_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "bio_html", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "automatically_approves_followers", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "field_htmls", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "emojis", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "tags", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "sensitive", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "suspended", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "suspended_until", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "successor_id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": "(ARRAY[]::text[])", + "generated": null, + "identity": null, + "name": "aliases", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "name": "following_count", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "name": "followers_count", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "updated", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "published", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deleted", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_id", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "addressing_property", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "property", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "target_id", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "collection_id", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "item_id", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "observed", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "collection_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "owner_actor_id", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "total_items", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "updated", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "instance_id", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "admin", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "accepted", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "local_id", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "varchar(259)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "host", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "node_info_url", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "software", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "software_version", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "key_id", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "public_key", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "fingerprint", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "first_seen", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_seen", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "keys" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iri", + "entityType": "columns", + "schema": "public", + "table": "keys" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "keys" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "local_actor_id", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "local_actor_key_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "public_key", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "private_key", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "local_actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "avatar", + "entityType": "columns", + "schema": "public", + "table": "local_actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "header", + "entityType": "columns", + "schema": "public", + "table": "local_actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "varchar(63)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "slug", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "10", + "generated": null, + "identity": null, + "name": "max_actors", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "char(6)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "code", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP + INTERVAL '15 minutes'", + "generated": null, + "identity": null, + "name": "expires", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "consumed", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_id", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "fetched", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "object_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "url", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "summary", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "content_html", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "varchar(35)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "language", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "sensitive", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "published", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "updated", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deleted", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "resource_id", + "entityType": "columns", + "schema": "public", + "table": "resource_heads" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "resource_heads" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "gen_random_uuid()", + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "resource_id", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "sequence", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "resource_revision_kind", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "resource_revision_capture", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "capture", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "backfilled", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 1, + "default": null, + "generated": null, + "identity": null, + "name": "former_types", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deleted", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "resource_revision_projection", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": "'partial'", + "generated": null, + "identity": null, + "name": "projection", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iri", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "resource_kind", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "addressing_property", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "property", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iri", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "path", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "revision_embedding_relation", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "relation", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "revision_receipts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_receipts" + }, + { + "type": "revision_receipt_role", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "role", + "entityType": "columns", + "schema": "public", + "table": "revision_receipts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "occurrence", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "property", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "path", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "revision_relation_representation", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "representation", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "target_iri", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_hash", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP + INTERVAL '1 month'", + "generated": null, + "identity": null, + "name": "expires", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"published\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_actor_published_index", + "entityType": "indexes", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "object_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "published", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_object_published_index", + "entityType": "indexes", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"created\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_instance_created_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_actor_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"created\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_activity_created_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "verification_key_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_verification_key_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_iri", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "inbox_url", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": "\"direction\" = 'outbound'", + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_outbound_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"created\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"delivery_id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_actor_created_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "delivery_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_attempt_delivery_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "collection_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "actor_collection_reference_collection_index", + "entityType": "indexes", + "schema": "public", + "table": "actor_collection_references" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "username", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": "\"local_id\" IS NOT NULL", + "with": "", + "method": "btree", + "concurrently": false, + "name": "username_key", + "entityType": "indexes", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "actor_instance_index", + "entityType": "indexes", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "target_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "property", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "addressing_target_property_index", + "entityType": "indexes", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "collection_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "position", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "collection_item_position_index", + "entityType": "indexes", + "schema": "public", + "table": "collection_items" + }, + { + "nameExplicit": false, + "columns": [ + { + "value": "account_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": "\"accepted\" IS NOT NULL", + "with": "", + "method": "btree", + "concurrently": false, + "name": "instance_members_accountId_index", + "entityType": "indexes", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": false, + "columns": [ + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": "\"accepted\" IS NOT NULL", + "with": "", + "method": "btree", + "concurrently": false, + "name": "instance_members_instanceId_index", + "entityType": "indexes", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "key_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "first_seen", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "key_version_key_first_seen_index", + "entityType": "indexes", + "schema": "public", + "table": "key_versions" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"published\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "object_actor_published_index", + "entityType": "indexes", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "iri", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "property", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_addressing_iri_property_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_addressing" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_revision_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_embeddings_source_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_embeddings" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "revision_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_receipts_revision_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_receipts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "property", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "target_iri", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revision_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_relations_property_target_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_relations" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activities_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activities_actorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": false, + "columns": ["object_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "activities_object_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": false, + "columns": ["instance_id"], + "schemaTo": "public", + "tableTo": "instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_deliveries_instance_id_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "activity_deliveries_actor_id_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": false, + "columns": ["activity_id"], + "schemaTo": "public", + "tableTo": "activities", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "activity_deliveries_activity_id_activities_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": false, + "columns": ["verification_key_id"], + "schemaTo": "public", + "tableTo": "key_versions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "activity_deliveries_verification_key_id_key_versions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": ["delivery_id", "actor_id"], + "schemaTo": "public", + "tableTo": "activity_delivery_actors", + "columnsTo": ["delivery_id", "actor_id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_actor_collections_link_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "nameExplicit": false, + "columns": ["delivery_id"], + "schemaTo": "public", + "tableTo": "activity_deliveries", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_actors_eZEmaeqml3qX_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_actors_actor_id_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "nameExplicit": false, + "columns": ["delivery_id"], + "schemaTo": "public", + "tableTo": "activity_deliveries", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_attempts_BJqYxUSnVaXX_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actor_collection_references_actorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actor_collection_references" + }, + { + "nameExplicit": false, + "columns": ["collection_id"], + "schemaTo": "public", + "tableTo": "collections", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actor_collection_references_collectionId_collections_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actor_collection_references" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actors_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["local_id"], + "schemaTo": "public", + "tableTo": "local_actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actors_localId_local_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["instance_id"], + "schemaTo": "public", + "tableTo": "instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actors_instanceId_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["successor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "actors_successorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["source_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "addressing_sourceId_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": false, + "columns": ["target_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "addressing_targetId_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": false, + "columns": ["collection_id"], + "schemaTo": "public", + "tableTo": "collections", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collection_items_collectionId_collections_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collection_items" + }, + { + "nameExplicit": false, + "columns": ["item_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collection_items_itemId_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collection_items" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collections_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collections" + }, + { + "nameExplicit": false, + "columns": ["owner_actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collections_ownerActorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collections" + }, + { + "nameExplicit": false, + "columns": ["account_id"], + "schemaTo": "public", + "tableTo": "accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "instance_members_accountId_accounts_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": false, + "columns": ["instance_id"], + "schemaTo": "public", + "tableTo": "instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "instance_members_instanceId_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": false, + "columns": ["local_id"], + "schemaTo": "public", + "tableTo": "local_instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "instances_localId_local_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "instances" + }, + { + "nameExplicit": false, + "columns": ["key_id"], + "schemaTo": "public", + "tableTo": "keys", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "key_versions_key_id_keys_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "key_versions" + }, + { + "nameExplicit": false, + "columns": ["local_actor_id"], + "schemaTo": "public", + "tableTo": "local_actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "local_actor_keys_local_actor_id_local_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "local_actor_keys" + }, + { + "nameExplicit": false, + "columns": ["account_id"], + "schemaTo": "public", + "tableTo": "accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "login_tokens_accountId_accounts_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "login_challenges" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "objects_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "objects_actorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": false, + "columns": ["activity_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "objects_activity_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": false, + "columns": ["resource_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "resource_heads_resource_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "resource_heads" + }, + { + "nameExplicit": true, + "columns": ["resource_id", "revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["resource_id", "id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "resource_heads_resource_revision_fkey", + "entityType": "fks", + "schema": "public", + "table": "resource_heads" + }, + { + "nameExplicit": false, + "columns": ["resource_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "resource_revisions_resource_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "resource_revisions" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_addressing_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_addressing" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_embeddings_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "nameExplicit": true, + "columns": ["source_revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_embeddings_source_revision_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "nameExplicit": false, + "columns": ["delivery_id"], + "schemaTo": "public", + "tableTo": "activity_deliveries", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "revision_receipts_delivery_id_activity_deliveries_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_receipts" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_receipts_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_receipts" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_relations_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_relations" + }, + { + "nameExplicit": false, + "columns": ["account_id"], + "schemaTo": "public", + "tableTo": "accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "sessions_accountId_accounts_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "sessions" + }, + { + "columns": ["delivery_id", "actor_id", "collection_iri"], + "nameExplicit": false, + "name": "activity_delivery_actor_collections_pkey", + "entityType": "pks", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "columns": ["delivery_id", "actor_id"], + "nameExplicit": false, + "name": "activity_delivery_actors_pkey", + "entityType": "pks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "columns": ["actor_id", "role"], + "nameExplicit": false, + "name": "actor_collection_references_pkey", + "entityType": "pks", + "schema": "public", + "table": "actor_collection_references" + }, + { + "columns": ["collection_id", "item_id"], + "nameExplicit": false, + "name": "collection_items_pkey", + "entityType": "pks", + "schema": "public", + "table": "collection_items" + }, + { + "columns": ["instance_id", "account_id"], + "nameExplicit": false, + "name": "instance_members_pkey", + "entityType": "pks", + "schema": "public", + "table": "instance_members" + }, + { + "columns": ["local_actor_id", "type"], + "nameExplicit": false, + "name": "local_actor_keys_pkey", + "entityType": "pks", + "schema": "public", + "table": "local_actor_keys" + }, + { + "columns": ["revision_id", "property", "position"], + "nameExplicit": false, + "name": "revision_addressing_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_addressing" + }, + { + "columns": ["revision_id", "path"], + "nameExplicit": false, + "name": "revision_embeddings_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "columns": ["delivery_id", "revision_id", "role"], + "nameExplicit": false, + "name": "revision_receipts_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_receipts" + }, + { + "columns": ["revision_id", "occurrence"], + "nameExplicit": false, + "name": "revision_relations_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_relations" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "accounts_pkey", + "schema": "public", + "table": "accounts", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "activities_pkey", + "schema": "public", + "table": "activities", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "activity_deliveries_pkey", + "schema": "public", + "table": "activity_deliveries", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "activity_delivery_attempts_pkey", + "schema": "public", + "table": "activity_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "actors_pkey", + "schema": "public", + "table": "actors", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "addressing_pkey", + "schema": "public", + "table": "addressing", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "collections_pkey", + "schema": "public", + "table": "collections", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "instances_pkey", + "schema": "public", + "table": "instances", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "key_versions_pkey", + "schema": "public", + "table": "key_versions", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "keys_pkey", + "schema": "public", + "table": "keys", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "local_actors_pkey", + "schema": "public", + "table": "local_actors", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "local_instances_pkey", + "schema": "public", + "table": "local_instances", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "login_tokens_pkey", + "schema": "public", + "table": "login_challenges", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "objects_pkey", + "schema": "public", + "table": "objects", + "entityType": "pks" + }, + { + "columns": ["resource_id"], + "nameExplicit": false, + "name": "resource_heads_pkey", + "schema": "public", + "table": "resource_heads", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "resource_revisions_pkey", + "schema": "public", + "table": "resource_revisions", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "resources_pkey", + "schema": "public", + "table": "resources", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "sessions_pkey", + "schema": "public", + "table": "sessions", + "entityType": "pks" + }, + { + "nameExplicit": true, + "columns": ["source_id", "property", "position"], + "nullsNotDistinct": false, + "name": "addressing_source_property_position_key", + "entityType": "uniques", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": true, + "columns": ["key_id", "fingerprint"], + "nullsNotDistinct": false, + "name": "key_versions_key_id_fingerprint_unique", + "entityType": "uniques", + "schema": "public", + "table": "key_versions" + }, + { + "nameExplicit": true, + "columns": ["activity_id"], + "nullsNotDistinct": false, + "name": "objects_activity_id_key", + "entityType": "uniques", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": true, + "columns": ["resource_id", "sequence"], + "nullsNotDistinct": false, + "name": "resource_revisions_resource_sequence_key", + "entityType": "uniques", + "schema": "public", + "table": "resource_revisions" + }, + { + "nameExplicit": true, + "columns": ["resource_id", "id"], + "nullsNotDistinct": false, + "name": "resource_revisions_resource_id_key", + "entityType": "uniques", + "schema": "public", + "table": "resource_revisions" + }, + { + "nameExplicit": false, + "columns": ["email"], + "nullsNotDistinct": false, + "name": "accounts_email_key", + "schema": "public", + "table": "accounts", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["local_id"], + "nullsNotDistinct": false, + "name": "actors_localId_key", + "schema": "public", + "table": "actors", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["host"], + "nullsNotDistinct": false, + "name": "instances_host_key", + "schema": "public", + "table": "instances", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["iri"], + "nullsNotDistinct": false, + "name": "keys_iri_key", + "schema": "public", + "table": "keys", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["slug"], + "nullsNotDistinct": false, + "name": "local_instances_slug_key", + "schema": "public", + "table": "local_instances", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["iri"], + "nullsNotDistinct": false, + "name": "resources_iri_key", + "schema": "public", + "table": "resources", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["token_hash"], + "nullsNotDistinct": false, + "name": "sessions_tokenHash_key", + "schema": "public", + "table": "sessions", + "entityType": "uniques" + }, + { + "value": "\"email\" ~ '^[^@]+@[^@]+\\.[^@]+$'", + "name": "accounts_email_check", + "entityType": "checks", + "schema": "public", + "table": "accounts" + }, + { + "value": "\"max_instances\" >= 0", + "name": "accounts_max_instances_check", + "entityType": "checks", + "schema": "public", + "table": "accounts" + }, + { + "value": "trim(both from \"name\") <> ''", + "name": "accounts_name_check", + "entityType": "checks", + "schema": "public", + "table": "accounts" + }, + { + "value": "(\"direction\" = 'inbound' AND \"status\" IN ('received', 'acknowledged', 'unverified', 'rejected')) OR (\"direction\" = 'outbound' AND \"status\" IN ('queued', 'sent', 'failed', 'permanently_failed', 'abandoned'))", + "name": "activity_deliveries_direction_status_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "(\"completed\" IS NULL) = (\"status\" = 'queued')", + "name": "activity_deliveries_completed_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"status_code\" IS NULL OR \"status_code\" BETWEEN 100 AND 599", + "name": "activity_deliveries_status_code_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"direction\" <> 'outbound' OR \"verification_key_id\" IS NULL", + "name": "activity_deliveries_outbound_key_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "(\"direction\" = 'inbound') = (\"verification_result\" IS NOT NULL)", + "name": "activity_deliveries_verification_result_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"verification_mechanism\" IS NULL OR (\"direction\" = 'inbound' AND \"verification_result\" NOT IN ('unattempted', 'unobserved'))", + "name": "activity_deliveries_verification_mechanism_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "(\"direction\" = 'inbound') = (\"body\" IS NOT NULL)", + "name": "activity_deliveries_body_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"activity_id\" IS NULL OR \"direction\" = 'outbound' OR (\"verification_result\" = 'verified' AND \"status\" IN ('received', 'acknowledged'))", + "name": "activity_deliveries_activity_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"inbox_owner\" OR \"addressed\" OR \"sender\"", + "name": "activity_delivery_actors_role_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "value": "NOT \"addressed_directly\" OR \"addressed\"", + "name": "activity_delivery_actors_addressed_directly_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "value": "\"status_code\" IS NULL OR \"status_code\" BETWEEN 100 AND 599", + "name": "activity_delivery_attempts_status_code_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "value": "\"succeeded\" = (\"error\" IS NULL)", + "name": "activity_delivery_attempts_error_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "value": "\"local_id\" IS NULL OR \"username\" NOT LIKE '%@%'", + "name": "actors_username_check", + "entityType": "checks", + "schema": "public", + "table": "actors" + }, + { + "value": "\"local_id\" IS NULL OR \"username\" IS NOT NULL", + "name": "actors_local_username_check", + "entityType": "checks", + "schema": "public", + "table": "actors" + }, + { + "value": "\n \"suspended_until\" IS NULL OR (\n \"suspended\" IS NOT NULL AND\n \"suspended_until\" > \"suspended\"\n )\n ", + "name": "actors_suspended_check", + "entityType": "checks", + "schema": "public", + "table": "actors" + }, + { + "value": "\"last_seen\" >= \"first_seen\"", + "name": "key_versions_seen_check", + "entityType": "checks", + "schema": "public", + "table": "key_versions" + }, + { + "value": "NOT (\"public_key\" ?| array['d','p','q','dp','dq','qi','oth','k'])", + "name": "key_versions_public_key_check", + "entityType": "checks", + "schema": "public", + "table": "key_versions" + }, + { + "value": "jsonb_typeof(\"public_key\") = 'object' AND NOT (\"public_key\" ?| array['d','p','q','dp','dq','qi','oth','k'])", + "name": "local_actor_keys_public_key_check", + "entityType": "checks", + "schema": "public", + "table": "local_actor_keys" + }, + { + "value": "\"slug\" ~ '^[a-z0-9][a-z0-9-]{2,61}[a-z0-9]$'\n AND (\"slug\" !~ '^..--' OR \"slug\" ~ '^xn--')", + "name": "local_instances_slug_check", + "entityType": "checks", + "schema": "public", + "table": "local_instances" + }, + { + "value": "\"max_actors\" > 0", + "name": "instances_max_actors_check", + "entityType": "checks", + "schema": "public", + "table": "local_instances" + }, + { + "value": "trim(both from \"content_html\") <> ''", + "name": "objects_content_html_check", + "entityType": "checks", + "schema": "public", + "table": "objects" + }, + { + "value": "\"sequence\" > 0", + "name": "resource_revisions_sequence_check", + "entityType": "checks", + "schema": "public", + "table": "resource_revisions" + }, + { + "value": "(\"kind\" = 'snapshot' AND \"document\" IS NOT NULL)\n OR (\"kind\" IN ('unavailable', 'whiteout') AND \"document\" IS NULL)", + "name": "resource_revisions_document_check", + "entityType": "checks", + "schema": "public", + "table": "resource_revisions" + }, + { + "value": "(\"kind\" = 'whiteout' AND \"deleted\" IS NOT NULL AND \"former_types\" IS NOT NULL)\n OR (\"kind\" <> 'whiteout' AND \"deleted\" IS NULL AND \"former_types\" IS NULL)", + "name": "resource_revisions_deletion_check", + "entityType": "checks", + "schema": "public", + "table": "resource_revisions" + }, + { + "value": "\"position\" >= 0", + "name": "revision_addressing_position_check", + "entityType": "checks", + "schema": "public", + "table": "revision_addressing" + }, + { + "value": "jsonb_typeof(\"path\") = 'array' AND jsonb_array_length(\"path\") > 0", + "name": "revision_embeddings_path_check", + "entityType": "checks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "value": "\"source_revision_id\" <> \"revision_id\"", + "name": "revision_embeddings_source_check", + "entityType": "checks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "value": "\"occurrence\" >= 0", + "name": "revision_relations_occurrence_check", + "entityType": "checks", + "schema": "public", + "table": "revision_relations" + }, + { + "value": "\"path\" IS NULL OR json_typeof(\"path\") = 'array'", + "name": "revision_relations_path_check", + "entityType": "checks", + "schema": "public", + "table": "revision_relations" + }, + { + "value": "\"representation\" <> 'reference' OR \"target_iri\" IS NOT NULL", + "name": "revision_relations_reference_check", + "entityType": "checks", + "schema": "public", + "table": "revision_relations" + } + ], + "renames": [] +} diff --git a/packages/models/drizzle/20261113080537_guard_revision_embeddings/migration.sql b/packages/models/drizzle/20261113080537_guard_revision_embeddings/migration.sql new file mode 100644 index 00000000..c6cd5961 --- /dev/null +++ b/packages/models/drizzle/20261113080537_guard_revision_embeddings/migration.sql @@ -0,0 +1,42 @@ +-- An embedding names the stored snapshot of another resource it came from. +CREATE FUNCTION drfed_guard_revision_embedding_insert() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + owner_id uuid; + source_owner_id uuid; + source_kind resource_revision_kind; +BEGIN + SELECT resource_id INTO owner_id + FROM resource_revisions WHERE id = NEW.revision_id; + SELECT resource_id, kind INTO source_owner_id, source_kind + FROM resource_revisions WHERE id = NEW.source_revision_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Embedding source revision does not exist' + USING ERRCODE = '23503', + CONSTRAINT = 'revision_embeddings_source_revision_fkey'; + END IF; + IF source_kind <> 'snapshot' THEN + RAISE EXCEPTION 'An embedding source must be a snapshot' + USING ERRCODE = '23514', + CONSTRAINT = 'revision_embeddings_source_kind_guard'; + END IF; + IF source_owner_id = owner_id THEN + RAISE EXCEPTION 'An embedding source must belong to another resource' + USING ERRCODE = '23514', + CONSTRAINT = 'revision_embeddings_source_resource_guard'; + END IF; + RETURN NEW; +END; +$$; +--> statement-breakpoint +CREATE TRIGGER revision_embeddings_source_guard BEFORE INSERT ON revision_embeddings +FOR EACH ROW EXECUTE FUNCTION drfed_guard_revision_embedding_insert(); +--> statement-breakpoint +CREATE TRIGGER revision_embeddings_insert_guard BEFORE INSERT ON revision_embeddings +FOR EACH ROW EXECUTE FUNCTION drfed_guard_revision_projection_insert(); +--> statement-breakpoint +CREATE TRIGGER revision_embeddings_immutable BEFORE UPDATE OR DELETE ON revision_embeddings +FOR EACH ROW EXECUTE FUNCTION drfed_reject_revision_mutation(); +--> statement-breakpoint +CREATE TRIGGER revision_embeddings_no_truncate BEFORE TRUNCATE ON revision_embeddings +FOR EACH STATEMENT EXECUTE FUNCTION drfed_reject_revision_mutation(); diff --git a/packages/models/drizzle/20261113080537_guard_revision_embeddings/snapshot.json b/packages/models/drizzle/20261113080537_guard_revision_embeddings/snapshot.json new file mode 100644 index 00000000..714ebfd1 --- /dev/null +++ b/packages/models/drizzle/20261113080537_guard_revision_embeddings/snapshot.json @@ -0,0 +1,4634 @@ +{ + "id": "cca19e71-9298-4ce6-91cd-a43b4753442f", + "prevIds": ["f867ba22-2861-4e0b-a6c6-4c560fc4682e"], + "version": "8", + "dialect": "postgres", + "ddl": [ + { + "values": ["inbound", "outbound"], + "name": "activity_delivery_direction", + "entityType": "enums", + "schema": "public" + }, + { + "values": [ + "received", + "acknowledged", + "unverified", + "rejected", + "queued", + "sent", + "failed", + "permanently_failed", + "abandoned" + ], + "name": "activity_delivery_status", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["http_signature", "ld_signature", "object_integrity_proof"], + "name": "activity_delivery_verification_mechanism", + "entityType": "enums", + "schema": "public" + }, + { + "values": [ + "verified", + "invalid_signature", + "key_fetch_error", + "no_signature", + "unattempted", + "unobserved" + ], + "name": "activity_delivery_verification_result", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Create"], + "name": "activity_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Application", "Group", "Organization", "Person", "Service"], + "name": "actor_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["to", "cc", "bto", "bcc", "audience"], + "name": "addressing_property", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["followers", "following", "featured", "outbox"], + "name": "collection_role", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Collection", "OrderedCollection"], + "name": "collection_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["RSASSA-PKCS1-v1_5", "Ed25519"], + "name": "local_actor_key_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["Article", "Note"], + "name": "object_type", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["actor", "object", "activity", "collection", "unknown"], + "name": "resource_kind", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["local", "received", "embedded", "fetched"], + "name": "resource_revision_capture", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["snapshot", "unavailable", "whiteout"], + "name": "resource_revision_kind", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["partial", "complete"], + "name": "resource_revision_projection", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["snapshot", "derived"], + "name": "revision_embedding_relation", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["activity", "object"], + "name": "revision_receipt_role", + "entityType": "enums", + "schema": "public" + }, + { + "values": ["reference", "embedded", "link"], + "name": "revision_relation_representation", + "entityType": "enums", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "accounts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_deliveries", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_delivery_actor_collections", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_delivery_actors", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "activity_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "actor_collection_references", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "actors", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "addressing", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "collection_items", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "collections", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "instance_members", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "instances", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "key_versions", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "keys", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "local_actor_keys", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "local_actors", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "local_instances", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "login_challenges", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "objects", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "resource_heads", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "resource_revisions", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "resources", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_addressing", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_embeddings", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_receipts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "revision_relations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "sessions", + "entityType": "tables", + "schema": "public" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "email", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "varchar(100)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "10", + "generated": null, + "identity": null, + "name": "max_instances", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "admin", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "accounts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "activity_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "object_id", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "published", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activities" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "instance_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_direction", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "direction", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_status", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_verification_mechanism", + "typeSchema": "public", + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "verification_mechanism", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "activity_delivery_verification_result", + "typeSchema": "public", + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "verification_result", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "types", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "carried_snapshot", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "fetched_object", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "carried_object_snapshot", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "object_type", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "object_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "signed_key_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "verification_key_id", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_actor_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_host", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "inbox_url", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "request_url", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "headers", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "bytea", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "body", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status_code", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "response_body", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "error", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "payload", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "recipient_iris", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "completed", + "entityType": "columns", + "schema": "public", + "table": "activity_deliveries" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "collection_iri", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "inbox_owner", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "addressed", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "addressed_directly", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "sender", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "succeeded", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status_code", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "response_body", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "error", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "actor_collection_references" + }, + { + "type": "collection_role", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "role", + "entityType": "columns", + "schema": "public", + "table": "actor_collection_references" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "collection_id", + "entityType": "columns", + "schema": "public", + "table": "actor_collection_references" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "local_id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "actor_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "username", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "instance_id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "inbox_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "followers_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "profile_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "avatar_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "header_url", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "bio_html", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "automatically_approves_followers", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "field_htmls", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "emojis", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'{}'", + "generated": null, + "identity": null, + "name": "tags", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "sensitive", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "suspended", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "suspended_until", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "successor_id", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": "(ARRAY[]::text[])", + "generated": null, + "identity": null, + "name": "aliases", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "name": "following_count", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "name": "followers_count", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "updated", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "published", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deleted", + "entityType": "columns", + "schema": "public", + "table": "actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_id", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "addressing_property", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "property", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "target_id", + "entityType": "columns", + "schema": "public", + "table": "addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "collection_id", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "item_id", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "observed", + "entityType": "columns", + "schema": "public", + "table": "collection_items" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "collection_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "owner_actor_id", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "total_items", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "updated", + "entityType": "columns", + "schema": "public", + "table": "collections" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "instance_id", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "admin", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "accepted", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "instance_members" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "local_id", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "varchar(259)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "host", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "node_info_url", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "software", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "software_version", + "entityType": "columns", + "schema": "public", + "table": "instances" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "key_id", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "public_key", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "fingerprint", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "first_seen", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_seen", + "entityType": "columns", + "schema": "public", + "table": "key_versions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "keys" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iri", + "entityType": "columns", + "schema": "public", + "table": "keys" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "keys" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "local_actor_id", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "local_actor_key_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "public_key", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "private_key", + "entityType": "columns", + "schema": "public", + "table": "local_actor_keys" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "local_actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "avatar", + "entityType": "columns", + "schema": "public", + "table": "local_actors" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "header", + "entityType": "columns", + "schema": "public", + "table": "local_actors" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "varchar(63)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "slug", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "10", + "generated": null, + "identity": null, + "name": "max_actors", + "entityType": "columns", + "schema": "public", + "table": "local_instances" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "char(6)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "code", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP + INTERVAL '15 minutes'", + "generated": null, + "identity": null, + "name": "expires", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "consumed", + "entityType": "columns", + "schema": "public", + "table": "login_challenges" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "actor_id", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_id", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "fetched", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "object_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "url", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "summary", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "content_html", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "varchar(35)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "language", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "sensitive", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "published", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "updated", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deleted", + "entityType": "columns", + "schema": "public", + "table": "objects" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "resource_id", + "entityType": "columns", + "schema": "public", + "table": "resource_heads" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "resource_heads" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "gen_random_uuid()", + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "resource_id", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "sequence", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "resource_revision_kind", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "resource_revision_capture", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "capture", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "backfilled", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "document", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 1, + "default": null, + "generated": null, + "identity": null, + "name": "former_types", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deleted", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "resource_revision_projection", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": "'partial'", + "generated": null, + "identity": null, + "name": "projection", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "resource_revisions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iri", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "resource_kind", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "resources" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "addressing_property", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "property", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iri", + "entityType": "columns", + "schema": "public", + "table": "revision_addressing" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "path", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "revision_embedding_relation", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "relation", + "entityType": "columns", + "schema": "public", + "table": "revision_embeddings" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "delivery_id", + "entityType": "columns", + "schema": "public", + "table": "revision_receipts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_receipts" + }, + { + "type": "revision_receipt_role", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "role", + "entityType": "columns", + "schema": "public", + "table": "revision_receipts" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revision_id", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "occurrence", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "property", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "json", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "path", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "revision_relation_representation", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "representation", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "target_iri", + "entityType": "columns", + "schema": "public", + "table": "revision_relations" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_hash", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP", + "generated": null, + "identity": null, + "name": "created", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "CURRENT_TIMESTAMP + INTERVAL '1 month'", + "generated": null, + "identity": null, + "name": "expires", + "entityType": "columns", + "schema": "public", + "table": "sessions" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"published\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_actor_published_index", + "entityType": "indexes", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "object_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "published", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_object_published_index", + "entityType": "indexes", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"created\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_instance_created_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_actor_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"created\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_activity_created_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "verification_key_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_verification_key_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_iri", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "inbox_url", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": "\"direction\" = 'outbound'", + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_outbound_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"created\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"delivery_id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_actor_created_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "delivery_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "activity_delivery_attempt_delivery_index", + "entityType": "indexes", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "collection_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "actor_collection_reference_collection_index", + "entityType": "indexes", + "schema": "public", + "table": "actor_collection_references" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "username", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": "\"local_id\" IS NOT NULL", + "with": "", + "method": "btree", + "concurrently": false, + "name": "username_key", + "entityType": "indexes", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "actor_instance_index", + "entityType": "indexes", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "target_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "property", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "addressing_target_property_index", + "entityType": "indexes", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "collection_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "position", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "collection_item_position_index", + "entityType": "indexes", + "schema": "public", + "table": "collection_items" + }, + { + "nameExplicit": false, + "columns": [ + { + "value": "account_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": "\"accepted\" IS NOT NULL", + "with": "", + "method": "btree", + "concurrently": false, + "name": "instance_members_accountId_index", + "entityType": "indexes", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": false, + "columns": [ + { + "value": "instance_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": "\"accepted\" IS NOT NULL", + "with": "", + "method": "btree", + "concurrently": false, + "name": "instance_members_instanceId_index", + "entityType": "indexes", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "key_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "first_seen", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "key_version_key_first_seen_index", + "entityType": "indexes", + "schema": "public", + "table": "key_versions" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "actor_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"published\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "\"id\" desc", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "object_actor_published_index", + "entityType": "indexes", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "iri", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "property", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_addressing_iri_property_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_addressing" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_revision_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_embeddings_source_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_embeddings" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "revision_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_receipts_revision_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_receipts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "property", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "target_iri", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revision_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "revision_relations_property_target_index", + "entityType": "indexes", + "schema": "public", + "table": "revision_relations" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activities_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activities_actorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": false, + "columns": ["object_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "activities_object_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activities" + }, + { + "nameExplicit": false, + "columns": ["instance_id"], + "schemaTo": "public", + "tableTo": "instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_deliveries_instance_id_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "activity_deliveries_actor_id_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": false, + "columns": ["activity_id"], + "schemaTo": "public", + "tableTo": "activities", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "activity_deliveries_activity_id_activities_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": false, + "columns": ["verification_key_id"], + "schemaTo": "public", + "tableTo": "key_versions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "activity_deliveries_verification_key_id_key_versions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "nameExplicit": true, + "columns": ["delivery_id", "actor_id"], + "schemaTo": "public", + "tableTo": "activity_delivery_actors", + "columnsTo": ["delivery_id", "actor_id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_actor_collections_link_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "nameExplicit": false, + "columns": ["delivery_id"], + "schemaTo": "public", + "tableTo": "activity_deliveries", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_actors_eZEmaeqml3qX_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_actors_actor_id_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "nameExplicit": false, + "columns": ["delivery_id"], + "schemaTo": "public", + "tableTo": "activity_deliveries", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "activity_delivery_attempts_BJqYxUSnVaXX_fkey", + "entityType": "fks", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actor_collection_references_actorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actor_collection_references" + }, + { + "nameExplicit": false, + "columns": ["collection_id"], + "schemaTo": "public", + "tableTo": "collections", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actor_collection_references_collectionId_collections_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actor_collection_references" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actors_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["local_id"], + "schemaTo": "public", + "tableTo": "local_actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actors_localId_local_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["instance_id"], + "schemaTo": "public", + "tableTo": "instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "actors_instanceId_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["successor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "actors_successorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "actors" + }, + { + "nameExplicit": false, + "columns": ["source_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "addressing_sourceId_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": false, + "columns": ["target_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "addressing_targetId_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": false, + "columns": ["collection_id"], + "schemaTo": "public", + "tableTo": "collections", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collection_items_collectionId_collections_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collection_items" + }, + { + "nameExplicit": false, + "columns": ["item_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collection_items_itemId_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collection_items" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collections_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collections" + }, + { + "nameExplicit": false, + "columns": ["owner_actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "collections_ownerActorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "collections" + }, + { + "nameExplicit": false, + "columns": ["account_id"], + "schemaTo": "public", + "tableTo": "accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "instance_members_accountId_accounts_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": false, + "columns": ["instance_id"], + "schemaTo": "public", + "tableTo": "instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "instance_members_instanceId_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "instance_members" + }, + { + "nameExplicit": false, + "columns": ["local_id"], + "schemaTo": "public", + "tableTo": "local_instances", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "instances_localId_local_instances_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "instances" + }, + { + "nameExplicit": false, + "columns": ["key_id"], + "schemaTo": "public", + "tableTo": "keys", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "key_versions_key_id_keys_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "key_versions" + }, + { + "nameExplicit": false, + "columns": ["local_actor_id"], + "schemaTo": "public", + "tableTo": "local_actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "local_actor_keys_local_actor_id_local_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "local_actor_keys" + }, + { + "nameExplicit": false, + "columns": ["account_id"], + "schemaTo": "public", + "tableTo": "accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "login_tokens_accountId_accounts_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "login_challenges" + }, + { + "nameExplicit": false, + "columns": ["id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "objects_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": false, + "columns": ["actor_id"], + "schemaTo": "public", + "tableTo": "actors", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "objects_actorId_actors_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": false, + "columns": ["activity_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "name": "objects_activity_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": false, + "columns": ["resource_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "resource_heads_resource_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "resource_heads" + }, + { + "nameExplicit": true, + "columns": ["resource_id", "revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["resource_id", "id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "resource_heads_resource_revision_fkey", + "entityType": "fks", + "schema": "public", + "table": "resource_heads" + }, + { + "nameExplicit": false, + "columns": ["resource_id"], + "schemaTo": "public", + "tableTo": "resources", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "resource_revisions_resource_id_resources_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "resource_revisions" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_addressing_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_addressing" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_embeddings_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "nameExplicit": true, + "columns": ["source_revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_embeddings_source_revision_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "nameExplicit": false, + "columns": ["delivery_id"], + "schemaTo": "public", + "tableTo": "activity_deliveries", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "revision_receipts_delivery_id_activity_deliveries_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_receipts" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_receipts_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_receipts" + }, + { + "nameExplicit": false, + "columns": ["revision_id"], + "schemaTo": "public", + "tableTo": "resource_revisions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "name": "revision_relations_revision_id_resource_revisions_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "revision_relations" + }, + { + "nameExplicit": false, + "columns": ["account_id"], + "schemaTo": "public", + "tableTo": "accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "sessions_accountId_accounts_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "sessions" + }, + { + "columns": ["delivery_id", "actor_id", "collection_iri"], + "nameExplicit": false, + "name": "activity_delivery_actor_collections_pkey", + "entityType": "pks", + "schema": "public", + "table": "activity_delivery_actor_collections" + }, + { + "columns": ["delivery_id", "actor_id"], + "nameExplicit": false, + "name": "activity_delivery_actors_pkey", + "entityType": "pks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "columns": ["actor_id", "role"], + "nameExplicit": false, + "name": "actor_collection_references_pkey", + "entityType": "pks", + "schema": "public", + "table": "actor_collection_references" + }, + { + "columns": ["collection_id", "item_id"], + "nameExplicit": false, + "name": "collection_items_pkey", + "entityType": "pks", + "schema": "public", + "table": "collection_items" + }, + { + "columns": ["instance_id", "account_id"], + "nameExplicit": false, + "name": "instance_members_pkey", + "entityType": "pks", + "schema": "public", + "table": "instance_members" + }, + { + "columns": ["local_actor_id", "type"], + "nameExplicit": false, + "name": "local_actor_keys_pkey", + "entityType": "pks", + "schema": "public", + "table": "local_actor_keys" + }, + { + "columns": ["revision_id", "property", "position"], + "nameExplicit": false, + "name": "revision_addressing_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_addressing" + }, + { + "columns": ["revision_id", "path"], + "nameExplicit": false, + "name": "revision_embeddings_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "columns": ["delivery_id", "revision_id", "role"], + "nameExplicit": false, + "name": "revision_receipts_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_receipts" + }, + { + "columns": ["revision_id", "occurrence"], + "nameExplicit": false, + "name": "revision_relations_pkey", + "entityType": "pks", + "schema": "public", + "table": "revision_relations" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "accounts_pkey", + "schema": "public", + "table": "accounts", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "activities_pkey", + "schema": "public", + "table": "activities", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "activity_deliveries_pkey", + "schema": "public", + "table": "activity_deliveries", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "activity_delivery_attempts_pkey", + "schema": "public", + "table": "activity_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "actors_pkey", + "schema": "public", + "table": "actors", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "addressing_pkey", + "schema": "public", + "table": "addressing", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "collections_pkey", + "schema": "public", + "table": "collections", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "instances_pkey", + "schema": "public", + "table": "instances", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "key_versions_pkey", + "schema": "public", + "table": "key_versions", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "keys_pkey", + "schema": "public", + "table": "keys", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "local_actors_pkey", + "schema": "public", + "table": "local_actors", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "local_instances_pkey", + "schema": "public", + "table": "local_instances", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "login_tokens_pkey", + "schema": "public", + "table": "login_challenges", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "objects_pkey", + "schema": "public", + "table": "objects", + "entityType": "pks" + }, + { + "columns": ["resource_id"], + "nameExplicit": false, + "name": "resource_heads_pkey", + "schema": "public", + "table": "resource_heads", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "resource_revisions_pkey", + "schema": "public", + "table": "resource_revisions", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "resources_pkey", + "schema": "public", + "table": "resources", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "sessions_pkey", + "schema": "public", + "table": "sessions", + "entityType": "pks" + }, + { + "nameExplicit": true, + "columns": ["source_id", "property", "position"], + "nullsNotDistinct": false, + "name": "addressing_source_property_position_key", + "entityType": "uniques", + "schema": "public", + "table": "addressing" + }, + { + "nameExplicit": true, + "columns": ["key_id", "fingerprint"], + "nullsNotDistinct": false, + "name": "key_versions_key_id_fingerprint_unique", + "entityType": "uniques", + "schema": "public", + "table": "key_versions" + }, + { + "nameExplicit": true, + "columns": ["activity_id"], + "nullsNotDistinct": false, + "name": "objects_activity_id_key", + "entityType": "uniques", + "schema": "public", + "table": "objects" + }, + { + "nameExplicit": true, + "columns": ["resource_id", "sequence"], + "nullsNotDistinct": false, + "name": "resource_revisions_resource_sequence_key", + "entityType": "uniques", + "schema": "public", + "table": "resource_revisions" + }, + { + "nameExplicit": true, + "columns": ["resource_id", "id"], + "nullsNotDistinct": false, + "name": "resource_revisions_resource_id_key", + "entityType": "uniques", + "schema": "public", + "table": "resource_revisions" + }, + { + "nameExplicit": false, + "columns": ["email"], + "nullsNotDistinct": false, + "name": "accounts_email_key", + "schema": "public", + "table": "accounts", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["local_id"], + "nullsNotDistinct": false, + "name": "actors_localId_key", + "schema": "public", + "table": "actors", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["host"], + "nullsNotDistinct": false, + "name": "instances_host_key", + "schema": "public", + "table": "instances", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["iri"], + "nullsNotDistinct": false, + "name": "keys_iri_key", + "schema": "public", + "table": "keys", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["slug"], + "nullsNotDistinct": false, + "name": "local_instances_slug_key", + "schema": "public", + "table": "local_instances", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["iri"], + "nullsNotDistinct": false, + "name": "resources_iri_key", + "schema": "public", + "table": "resources", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": ["token_hash"], + "nullsNotDistinct": false, + "name": "sessions_tokenHash_key", + "schema": "public", + "table": "sessions", + "entityType": "uniques" + }, + { + "value": "\"email\" ~ '^[^@]+@[^@]+\\.[^@]+$'", + "name": "accounts_email_check", + "entityType": "checks", + "schema": "public", + "table": "accounts" + }, + { + "value": "\"max_instances\" >= 0", + "name": "accounts_max_instances_check", + "entityType": "checks", + "schema": "public", + "table": "accounts" + }, + { + "value": "trim(both from \"name\") <> ''", + "name": "accounts_name_check", + "entityType": "checks", + "schema": "public", + "table": "accounts" + }, + { + "value": "(\"direction\" = 'inbound' AND \"status\" IN ('received', 'acknowledged', 'unverified', 'rejected')) OR (\"direction\" = 'outbound' AND \"status\" IN ('queued', 'sent', 'failed', 'permanently_failed', 'abandoned'))", + "name": "activity_deliveries_direction_status_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "(\"completed\" IS NULL) = (\"status\" = 'queued')", + "name": "activity_deliveries_completed_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"status_code\" IS NULL OR \"status_code\" BETWEEN 100 AND 599", + "name": "activity_deliveries_status_code_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"direction\" <> 'outbound' OR \"verification_key_id\" IS NULL", + "name": "activity_deliveries_outbound_key_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "(\"direction\" = 'inbound') = (\"verification_result\" IS NOT NULL)", + "name": "activity_deliveries_verification_result_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"verification_mechanism\" IS NULL OR (\"direction\" = 'inbound' AND \"verification_result\" NOT IN ('unattempted', 'unobserved'))", + "name": "activity_deliveries_verification_mechanism_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "(\"direction\" = 'inbound') = (\"body\" IS NOT NULL)", + "name": "activity_deliveries_body_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"activity_id\" IS NULL OR \"direction\" = 'outbound' OR (\"verification_result\" = 'verified' AND \"status\" IN ('received', 'acknowledged'))", + "name": "activity_deliveries_activity_check", + "entityType": "checks", + "schema": "public", + "table": "activity_deliveries" + }, + { + "value": "\"inbox_owner\" OR \"addressed\" OR \"sender\"", + "name": "activity_delivery_actors_role_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "value": "NOT \"addressed_directly\" OR \"addressed\"", + "name": "activity_delivery_actors_addressed_directly_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_actors" + }, + { + "value": "\"status_code\" IS NULL OR \"status_code\" BETWEEN 100 AND 599", + "name": "activity_delivery_attempts_status_code_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "value": "\"succeeded\" = (\"error\" IS NULL)", + "name": "activity_delivery_attempts_error_check", + "entityType": "checks", + "schema": "public", + "table": "activity_delivery_attempts" + }, + { + "value": "\"local_id\" IS NULL OR \"username\" NOT LIKE '%@%'", + "name": "actors_username_check", + "entityType": "checks", + "schema": "public", + "table": "actors" + }, + { + "value": "\"local_id\" IS NULL OR \"username\" IS NOT NULL", + "name": "actors_local_username_check", + "entityType": "checks", + "schema": "public", + "table": "actors" + }, + { + "value": "\n \"suspended_until\" IS NULL OR (\n \"suspended\" IS NOT NULL AND\n \"suspended_until\" > \"suspended\"\n )\n ", + "name": "actors_suspended_check", + "entityType": "checks", + "schema": "public", + "table": "actors" + }, + { + "value": "\"last_seen\" >= \"first_seen\"", + "name": "key_versions_seen_check", + "entityType": "checks", + "schema": "public", + "table": "key_versions" + }, + { + "value": "NOT (\"public_key\" ?| array['d','p','q','dp','dq','qi','oth','k'])", + "name": "key_versions_public_key_check", + "entityType": "checks", + "schema": "public", + "table": "key_versions" + }, + { + "value": "jsonb_typeof(\"public_key\") = 'object' AND NOT (\"public_key\" ?| array['d','p','q','dp','dq','qi','oth','k'])", + "name": "local_actor_keys_public_key_check", + "entityType": "checks", + "schema": "public", + "table": "local_actor_keys" + }, + { + "value": "\"slug\" ~ '^[a-z0-9][a-z0-9-]{2,61}[a-z0-9]$'\n AND (\"slug\" !~ '^..--' OR \"slug\" ~ '^xn--')", + "name": "local_instances_slug_check", + "entityType": "checks", + "schema": "public", + "table": "local_instances" + }, + { + "value": "\"max_actors\" > 0", + "name": "instances_max_actors_check", + "entityType": "checks", + "schema": "public", + "table": "local_instances" + }, + { + "value": "trim(both from \"content_html\") <> ''", + "name": "objects_content_html_check", + "entityType": "checks", + "schema": "public", + "table": "objects" + }, + { + "value": "\"sequence\" > 0", + "name": "resource_revisions_sequence_check", + "entityType": "checks", + "schema": "public", + "table": "resource_revisions" + }, + { + "value": "(\"kind\" = 'snapshot' AND \"document\" IS NOT NULL)\n OR (\"kind\" IN ('unavailable', 'whiteout') AND \"document\" IS NULL)", + "name": "resource_revisions_document_check", + "entityType": "checks", + "schema": "public", + "table": "resource_revisions" + }, + { + "value": "(\"kind\" = 'whiteout' AND \"deleted\" IS NOT NULL AND \"former_types\" IS NOT NULL)\n OR (\"kind\" <> 'whiteout' AND \"deleted\" IS NULL AND \"former_types\" IS NULL)", + "name": "resource_revisions_deletion_check", + "entityType": "checks", + "schema": "public", + "table": "resource_revisions" + }, + { + "value": "\"position\" >= 0", + "name": "revision_addressing_position_check", + "entityType": "checks", + "schema": "public", + "table": "revision_addressing" + }, + { + "value": "jsonb_typeof(\"path\") = 'array' AND jsonb_array_length(\"path\") > 0", + "name": "revision_embeddings_path_check", + "entityType": "checks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "value": "\"source_revision_id\" <> \"revision_id\"", + "name": "revision_embeddings_source_check", + "entityType": "checks", + "schema": "public", + "table": "revision_embeddings" + }, + { + "value": "\"occurrence\" >= 0", + "name": "revision_relations_occurrence_check", + "entityType": "checks", + "schema": "public", + "table": "revision_relations" + }, + { + "value": "\"path\" IS NULL OR json_typeof(\"path\") = 'array'", + "name": "revision_relations_path_check", + "entityType": "checks", + "schema": "public", + "table": "revision_relations" + }, + { + "value": "\"representation\" <> 'reference' OR \"target_iri\" IS NOT NULL", + "name": "revision_relations_reference_check", + "entityType": "checks", + "schema": "public", + "table": "revision_relations" + } + ], + "renames": [] +} diff --git a/packages/models/migrations-manifest.json b/packages/models/migrations-manifest.json index 2d307ad9..de887f8c 100644 --- a/packages/models/migrations-manifest.json +++ b/packages/models/migrations-manifest.json @@ -116,6 +116,14 @@ { "name": "20261026192411_capture_legacy_resource_revisions", "sha256": "25deff8bc6684620fb679c1d339c8803cdcb1b5a8c5f9a9771c95411a185eee3" + }, + { + "name": "20261113080536_revision_embeddings", + "sha256": "52427c6e8a430652bbca4aa351bcb35d0933ac372b221e9dd13cd2a537c68084" + }, + { + "name": "20261113080537_guard_revision_embeddings", + "sha256": "565918b747d0a6d092cdb1d68cf709a729b705c17489b2e333aca294c692b8f5" } ] } diff --git a/packages/models/src/relations.ts b/packages/models/src/relations.ts index 31bd4c0b..ee770ec5 100644 --- a/packages/models/src/relations.ts +++ b/packages/models/src/relations.ts @@ -37,6 +37,11 @@ export const relations = defineRelations(schema, (r) => ({ from: r.resourceRevisions.id, to: r.revisionReceipts.revisionId, }), + embeddings: r.many.revisionEmbeddings({ + from: r.resourceRevisions.id, + to: r.revisionEmbeddings.revisionId, + alias: "embeddings", + }), }, resourceHeads: { resource: r.one.resources({ @@ -64,6 +69,19 @@ export const relations = defineRelations(schema, (r) => ({ optional: false, }), }, + revisionEmbeddings: { + revision: r.one.resourceRevisions({ + from: r.revisionEmbeddings.revisionId, + to: r.resourceRevisions.id, + optional: false, + alias: "embeddings", + }), + source: r.one.resourceRevisions({ + from: r.revisionEmbeddings.sourceRevisionId, + to: r.resourceRevisions.id, + optional: false, + }), + }, revisionReceipts: { revision: r.one.resourceRevisions({ from: r.revisionReceipts.revisionId, diff --git a/packages/models/src/resource-revision-embedding.test.ts b/packages/models/src/resource-revision-embedding.test.ts new file mode 100644 index 00000000..209ecdb1 --- /dev/null +++ b/packages/models/src/resource-revision-embedding.test.ts @@ -0,0 +1,379 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Writes in one test depend on the state left by the previous ones. +// oxlint-disable no-await-in-loop + +import assert from "node:assert/strict"; +import { it } from "node:test"; + +import { ensureResource, storeAddressing } from "@drfed/models/resource"; +import { + type RevisionEmbeddingInput, + appendResourceRevision, + captureLegacyResourceRevision, + loadCurrentResourceRevision, + writeTypedResourceRevision, +} from "@drfed/models/resource-revision"; +import { type Uuid, uuidV7 } from "@drfed/models/uuid"; + +import { + type RevisionFixture, + revisionBackends, + revisionPostgresUrl, + withRevisionDatabase, +} from "./resource-revision-fixture.ts"; + +const PUBLIC = "https://www.w3.org/ns/activitystreams#Public"; + +async function snapshot( + fixture: RevisionFixture, + document: Record, + embeddings?: readonly RevisionEmbeddingInput[], +) { + const resource = await ensureResource( + fixture.db, + `https://example.test/resources/${uuidV7()}`, + ); + const revision = await appendResourceRevision(fixture.db, { + resourceId: resource.id, + resourceKind: "object", + expectedRevisionId: null, + kind: "snapshot", + document, + capture: "local", + ...(embeddings === undefined ? {} : { embeddings }), + }); + return { resource, revision }; +} + +async function embeddingRows(fixture: RevisionFixture, revisionId: string) { + const { rows } = await fixture.query<{ + path: string; + source_revision_id: string; + relation: string; + }>( + "SELECT path::text AS path, source_revision_id, relation::text AS relation FROM revision_embeddings WHERE revision_id = $1 ORDER BY path::text", + [revisionId], + ); + return rows.map(({ path, source_revision_id, relation }) => ({ + path: JSON.parse(path) as unknown, + sourceRevisionId: source_revision_id, + relation, + })); +} + +// Drivers wrap database errors; the constraint name may sit on a cause. +function constraintOf(error: unknown): string | undefined { + let detail: unknown = error; + while (detail instanceof Error) { + for (const key of ["constraint", "constraint_name"]) { + const value = (detail as unknown as Record)[key]; + if (typeof value === "string") return value; + } + detail = detail.cause; + } + return undefined; +} + +async function rejectsWith( + run: () => Promise, + constraint: string, +): Promise { + await assert.rejects(run, (error) => { + assert.equal(constraintOf(error), constraint); + return true; + }); +} + +for (const backend of revisionBackends) { + const options = { skip: backend === "postgres" && !revisionPostgresUrl }; + + it( + `stores embeddings with an appended snapshot on ${backend}`, + options, + async () => { + await withRevisionDatabase(backend, async (fixture) => { + const note = await snapshot(fixture, { type: "Note", content: "a" }); + const like = await snapshot(fixture, { type: "Note", content: "b" }); + const parent = await snapshot(fixture, { type: "Create" }, [ + { + path: ["object", 0], + sourceRevisionId: note.revision.id, + relation: "snapshot", + }, + { + path: ["object", 1, "inReplyTo"], + sourceRevisionId: like.revision.id, + relation: "derived", + }, + ]); + assert.deepEqual(await embeddingRows(fixture, parent.revision.id), [ + { + path: ["object", 0], + sourceRevisionId: note.revision.id, + relation: "snapshot", + }, + { + path: ["object", 1, "inReplyTo"], + sourceRevisionId: like.revision.id, + relation: "derived", + }, + ]); + // The relations reach the rows from either side. + const loaded = await fixture.db.query.resourceRevisions.findFirst({ + where: { id: parent.revision.id }, + with: { embeddings: { with: { source: true } } }, + }); + assert.deepEqual( + loaded?.embeddings + .map(({ source }) => source.id) + .toSorted((left, right) => left.localeCompare(right)), + [note.revision.id, like.revision.id].toSorted((left, right) => + left.localeCompare(right), + ), + ); + // A snapshot without embeddings stores none. + assert.deepEqual(await embeddingRows(fixture, note.revision.id), []); + }); + }, + ); + + it(`stores embeddings with a typed edit on ${backend}`, options, async () => { + await withRevisionDatabase(backend, async (fixture) => { + const instanceId = uuidV7(); + const actorId = uuidV7(); + const objectId = uuidV7() as Uuid; + const iri = `https://typed.example/objects/${objectId}`; + const document = { id: iri, type: "Note", content: "first" }; + await fixture.query("INSERT INTO instances (id, host) VALUES ($1, $2)", [ + instanceId, + `${instanceId}.example`, + ]); + await fixture.query( + "INSERT INTO resources (id, iri, kind) VALUES ($1, $2, 'actor'), ($3, $4, 'object')", + [actorId, `https://typed.example/actors/${actorId}`, objectId, iri], + ); + await fixture.query( + "INSERT INTO actors (id, type, instance_id, inbox_url) VALUES ($1, 'Person', $2, 'https://typed.example/inbox')", + [actorId, instanceId], + ); + await fixture.query( + "INSERT INTO objects (id, actor_id, type, content_html, document) VALUES ($1, $2, 'Note', 'first', $3::json)", + [objectId, actorId, JSON.stringify(document)], + ); + const revisionId = await fixture.db.transaction(async (tx) => { + await storeAddressing(tx, objectId, { to: [PUBLIC] }); + return await captureLegacyResourceRevision(tx, objectId); + }); + const attachment = await snapshot(fixture, { + type: "Document", + name: "attached", + }); + const edited = await writeTypedResourceRevision(fixture.db, { + resourceId: objectId, + expectedRevisionId: revisionId, + kind: "snapshot", + document: { + ...document, + content: "second", + attachment: { type: "Document", name: "attached" }, + }, + columns: { + url: null, + name: null, + summary: null, + contentHtml: "second", + language: null, + sensitive: false, + published: Temporal.Instant.from("2026-11-01T00:00:00Z"), + updated: Temporal.Instant.from("2026-11-02T00:00:00Z"), + }, + addressingOccurrences: [{ property: "to", position: 0, iri: PUBLIC }], + embeddings: [ + { + path: ["attachment"], + sourceRevisionId: attachment.revision.id, + relation: "snapshot", + }, + ], + }); + assert.equal(edited.sequence, 2); + assert.deepEqual(await embeddingRows(fixture, edited.id), [ + { + path: ["attachment"], + sourceRevisionId: attachment.revision.id, + relation: "snapshot", + }, + ]); + }); + }); + + it( + `rejects embedding sources that are no other resource's snapshot on ${backend}`, + options, + async () => { + await withRevisionDatabase(backend, async (fixture) => { + const deleted = await snapshot(fixture, { type: "Note" }); + const whiteout = await appendResourceRevision(fixture.db, { + resourceId: deleted.resource.id, + resourceKind: "object", + expectedRevisionId: deleted.revision.id, + kind: "whiteout", + deleted: Temporal.Now.instant(), + formerTypes: ["Note"], + }); + const embedding = (sourceRevisionId: Uuid): RevisionEmbeddingInput => ({ + path: ["object"], + sourceRevisionId, + relation: "snapshot", + }); + await rejectsWith( + () => snapshot(fixture, { type: "Create" }, [embedding(whiteout.id)]), + "revision_embeddings_source_kind_guard", + ); + await rejectsWith( + () => + snapshot(fixture, { type: "Create" }, [ + embedding(uuidV7() as Uuid), + ]), + "revision_embeddings_source_revision_fkey", + ); + const edited = await snapshot(fixture, { type: "Note" }); + await rejectsWith( + () => + appendResourceRevision(fixture.db, { + resourceId: edited.resource.id, + resourceKind: "object", + expectedRevisionId: edited.revision.id, + kind: "snapshot", + document: { type: "Note", content: "again" }, + capture: "local", + embeddings: [embedding(edited.revision.id)], + }), + "revision_embeddings_source_resource_guard", + ); + // A rejected embedding leaves no part of the revision behind. + const head = await loadCurrentResourceRevision( + fixture.db, + edited.resource.id, + ); + assert.equal(head?.id, edited.revision.id); + const { rows } = await fixture.query<{ count: number }>( + "SELECT count(*)::int AS count FROM resource_revisions WHERE kind = 'snapshot' AND document::text = $1", + [JSON.stringify({ type: "Create" })], + ); + assert.equal(Number(rows[0]?.count), 0); + }); + }, + ); + + it( + `seals embeddings with their published revision on ${backend}`, + options, + async () => { + await withRevisionDatabase(backend, async (fixture) => { + const note = await snapshot(fixture, { type: "Note" }); + const other = await snapshot(fixture, { type: "Note" }); + const parent = await snapshot(fixture, { type: "Create" }, [ + { + path: ["object"], + sourceRevisionId: note.revision.id, + relation: "snapshot", + }, + ]); + await rejectsWith( + () => + fixture.query( + `INSERT INTO revision_embeddings (revision_id, path, source_revision_id, relation) VALUES ($1, '["target"]', $2, 'derived')`, + [parent.revision.id, other.revision.id], + ), + "revision_embeddings_sealed", + ); + await rejectsWith( + () => + fixture.query( + "UPDATE revision_embeddings SET relation = 'derived' WHERE revision_id = $1", + [parent.revision.id], + ), + "revision_embeddings_immutable", + ); + await rejectsWith( + () => + fixture.query( + "DELETE FROM revision_embeddings WHERE revision_id = $1", + [parent.revision.id], + ), + "revision_embeddings_immutable", + ); + await rejectsWith( + () => fixture.query("TRUNCATE revision_embeddings"), + "revision_embeddings_immutable", + ); + assert.equal( + (await embeddingRows(fixture, parent.revision.id)).length, + 1, + ); + }); + }, + ); + + it( + `validates embedding input before writing on ${backend}`, + options, + async () => { + await withRevisionDatabase(backend, async (fixture) => { + const note = await snapshot(fixture, { type: "Note" }); + const sourceRevisionId = note.revision.id; + const invalid: unknown[] = [ + "not a list", + [{ path: [], sourceRevisionId, relation: "snapshot" }], + [{ path: "object", sourceRevisionId, relation: "snapshot" }], + [{ path: ["object", -1], sourceRevisionId, relation: "snapshot" }], + [{ path: ["object", 1.5], sourceRevisionId, relation: "snapshot" }], + [{ path: [true], sourceRevisionId, relation: "snapshot" }], + [ + { path: ["object"], sourceRevisionId, relation: "snapshot" }, + { path: ["object"], sourceRevisionId, relation: "derived" }, + ], + [ + { + path: ["object"], + sourceRevisionId: "not-a-uuid", + relation: "snapshot", + }, + ], + [{ path: ["object"], sourceRevisionId, relation: "copy" }], + ]; + for (const embeddings of invalid) { + await assert.rejects( + () => + snapshot( + fixture, + { type: "Create" }, + embeddings as readonly RevisionEmbeddingInput[], + ), + TypeError, + ); + } + const { rows } = await fixture.query<{ count: number }>( + "SELECT count(*)::int AS count FROM revision_embeddings", + ); + assert.equal(Number(rows[0]?.count), 0); + }); + }, + ); +} diff --git a/packages/models/src/resource-revision.ts b/packages/models/src/resource-revision.ts index 0c2ad7b8..54aaa4e7 100644 --- a/packages/models/src/resource-revision.ts +++ b/packages/models/src/resource-revision.ts @@ -31,6 +31,7 @@ import { type NewActivityPubObject, type ResourceRevision, type RevisionAddressing, + type RevisionEmbedding, type RevisionRelation, activities, addressingPropertyEnum, @@ -42,6 +43,8 @@ import { resourceRevisions, resources, revisionAddressing, + revisionEmbeddingRelationEnum, + revisionEmbeddings, revisionRelations, } from "./schema.ts"; import { storableText } from "./text.ts"; @@ -67,6 +70,19 @@ export interface RevisionRelationInput { readonly targetIri?: string | null; } +/** + * Where an embedded document of a new snapshot came from, as + * `revisionEmbeddings` records it. The caller decides the relation by + * comparing the documents; nothing is compared here. + */ +export interface RevisionEmbeddingInput { + /** The embedded document's source path from the root; never `[]`. */ + readonly path: readonly (string | number)[]; + /** A snapshot of another resource, stored before this revision. */ + readonly sourceRevisionId: Uuid; + readonly relation: RevisionEmbedding["relation"]; +} + interface AppendBase { readonly resourceId: Uuid; readonly resourceKind: "object" | "activity"; @@ -86,6 +102,8 @@ export type AppendResourceRevisionInput = AppendBase & */ readonly addressingOccurrences?: readonly AddressingOccurrence[]; readonly relations?: readonly RevisionRelationInput[]; + /** Embedded documents whose source is known, each path once. */ + readonly embeddings?: readonly RevisionEmbeddingInput[]; readonly projection?: ResourceRevision["projection"]; } | { @@ -241,6 +259,44 @@ function relationRows( }); } +function embeddingRows( + input: readonly RevisionEmbeddingInput[] = [], +): Omit[] { + if (!Array.isArray(input)) { + throw new TypeError("Embedding projections must be arrays."); + } + const paths = new Set(); + return input.map(({ path, sourceRevisionId, relation }) => { + if ( + !Array.isArray(path) || + path.length < 1 || + Array.from(path).some( + (part) => + typeof part !== "string" && + !(Number.isSafeInteger(part) && part >= 0), + ) + ) { + throw new TypeError( + "An embedding path must name a nonempty list of field names and " + + "nonnegative indexes.", + ); + } + for (const part of path) if (typeof part === "string") text(part); + const key = JSON.stringify(path); + if (paths.has(key)) { + throw new TypeError("Each embedding path must be given once."); + } + paths.add(key); + if (!validateUuid(sourceRevisionId)) { + throw new TypeError("Expected a source revision UUID."); + } + if (!revisionEmbeddingRelationEnum.enumValues.includes(relation)) { + throw new TypeError("Invalid embedding relation."); + } + return { path: [...path], sourceRevisionId, relation }; + }); +} + async function current( db: Database | Transaction, resourceId: Uuid, @@ -286,6 +342,7 @@ interface PreparedRevision extends AppendBase { readonly projection: ResourceRevision["projection"] | undefined; readonly addressing: Omit[]; readonly relations: Omit[]; + readonly embeddings: Omit[]; readonly deleted: Temporal.Instant | null; readonly formerTypes: string[] | null; } @@ -330,6 +387,7 @@ function prepareSnapshot( projection, addressing, relations: relationRows(input.relations), + embeddings: embeddingRows(input.embeddings), deleted: null, formerTypes: null, }; @@ -353,6 +411,7 @@ function prepareWhiteout( projection: undefined, addressing: [], relations: [], + embeddings: [], deleted: input.deleted, formerTypes, }; @@ -473,6 +532,7 @@ async function appendPrepared( formerTypes, addressing, relations, + embeddings, } = input; const id = uuidV7(); const [revision] = await tx @@ -511,6 +571,11 @@ async function appendPrepared( .insert(revisionRelations) .values(relations.map((row) => ({ ...row, revisionId: id }))); } + if (embeddings.length > 0) { + await tx + .insert(revisionEmbeddings) + .values(embeddings.map((row) => ({ ...row, revisionId: id }))); + } if (previous === null) { await tx.insert(resourceHeads).values({ resourceId, revisionId: id }); } else { @@ -661,6 +726,8 @@ export type TypedResourceRevisionInput = TypedRevisionBase & Partial>; readonly addressingOccurrences: readonly AddressingOccurrence[]; readonly relations?: readonly RevisionRelationInput[]; + /** Embedded documents whose source is known, each path once. */ + readonly embeddings?: readonly RevisionEmbeddingInput[]; readonly projection?: ResourceRevision["projection"]; } | { @@ -740,6 +807,9 @@ export async function writeTypedResourceRevision( ...(input.relations === undefined ? {} : { relations: input.relations }), + ...(input.embeddings === undefined + ? {} + : { embeddings: input.embeddings }), ...(input.projection === undefined ? {} : { projection: input.projection }), diff --git a/packages/models/src/schema.ts b/packages/models/src/schema.ts index 38240612..6d4a7839 100644 --- a/packages/models/src/schema.ts +++ b/packages/models/src/schema.ts @@ -1064,6 +1064,47 @@ export const revisionRelations = pgTable( ], ); +export const revisionEmbeddingRelationEnum = pgEnum( + "revision_embedding_relation", + ["snapshot", "derived"], +); +/** + * Where an embedded document of a revision came from, recorded when the + * revision was saved: the revision of another resource whose contents it + * keeps, apart from the context it inherits, or from which it was derived. + * An embedded document without a row has an unknown source. Rows are part + * of the immutable history of their revision. + */ +export const revisionEmbeddings = pgTable( + "revision_embeddings", + { + revisionId: uuid("revision_id") + .$type() + .notNull() + .references(() => resourceRevisions.id, { onDelete: "restrict" }), + path: jsonb().$type().notNull(), + sourceRevisionId: uuid("source_revision_id").$type().notNull(), + relation: revisionEmbeddingRelationEnum().notNull(), + }, + (t) => [ + primaryKey({ columns: [t.revisionId, t.path] }), + foreignKey({ + name: "revision_embeddings_source_revision_fkey", + columns: [t.sourceRevisionId], + foreignColumns: [resourceRevisions.id], + }).onDelete("restrict"), + check( + "revision_embeddings_path_check", + sql`jsonb_typeof(${t.path}) = 'array' AND jsonb_array_length(${t.path}) > 0`, + ), + check( + "revision_embeddings_source_check", + sql`${t.sourceRevisionId} <> ${t.revisionId}`, + ), + index("revision_embeddings_source_index").on(t.sourceRevisionId), + ], +); + export const revisionReceiptRoleEnum = pgEnum("revision_receipt_role", [ "activity", "object", @@ -1094,3 +1135,4 @@ export type ResourceHead = typeof resourceHeads.$inferSelect; export type RevisionAddressing = typeof revisionAddressing.$inferSelect; export type RevisionRelation = typeof revisionRelations.$inferSelect; export type RevisionReceipt = typeof revisionReceipts.$inferSelect; +export type RevisionEmbedding = typeof revisionEmbeddings.$inferSelect; From 06db7aa20aefd9917769fd231b4848971ad300ed Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Fri, 13 Nov 2026 17:57:09 +0900 Subject: [PATCH 03/10] Add a seed script of resource revisions for UI work mise run seed:revisions fills a development PGlite store with the revisions the resource detail UI has to present, then reads each seeded resource through GraphQL as every kind of viewer and prints what they see, so that the UI can be designed against known data. The script creates two workspaces, each with one member and one actor, and an administrator. Local resources are saved through the common write operations. Received revisions of a remote Note are written to the tables directly with their receipts, since no write path stores received documents as revisions yet. The 20 cases cover nested and anonymous embeddings, references, an intransitive activity, edits, whiteouts, uninterpreted documents, snapshot and derived sources and whether they are current, superseded, or deleted, unknown sources, and revisions hidden from viewers who could not read what they embed. For an embedded document without a recorded source, the report tells from fields the API already returns whether it is anonymous, has no readable revision to compare with, or has revisions none of which was recorded. A store that was seeded before is refused, since revisions cannot be replaced. https://github.com/fedify-dev/drfed/issues/154 AI assistance: Claude Code wrote the seed script, its mise task, and the report of what each viewer reads, from the cases discussed in the issue thread. The maintainer reviewed the output against a running development server. Assisted-by: Delta:claude-fable-5-2 Assisted-by: Delta:claude-opus-5-5 --- mise.toml | 8 + package.json | 2 + pnpm-lock.yaml | 7 + scripts/seed-revisions/case.mts | 68 ++++++ scripts/seed-revisions/cases-access.mts | 113 ++++++++++ scripts/seed-revisions/cases-documents.mts | 157 ++++++++++++++ scripts/seed-revisions/cases-sources.mts | 207 ++++++++++++++++++ scripts/seed-revisions/environment.mts | 238 +++++++++++++++++++++ scripts/seed-revisions/main.mts | 107 +++++++++ scripts/seed-revisions/received.mts | 88 ++++++++ scripts/seed-revisions/report.mts | 174 +++++++++++++++ scripts/seed-revisions/writer.mts | 153 +++++++++++++ 12 files changed, 1322 insertions(+) create mode 100644 scripts/seed-revisions/case.mts create mode 100644 scripts/seed-revisions/cases-access.mts create mode 100644 scripts/seed-revisions/cases-documents.mts create mode 100644 scripts/seed-revisions/cases-sources.mts create mode 100644 scripts/seed-revisions/environment.mts create mode 100644 scripts/seed-revisions/main.mts create mode 100644 scripts/seed-revisions/received.mts create mode 100644 scripts/seed-revisions/report.mts create mode 100644 scripts/seed-revisions/writer.mts diff --git a/mise.toml b/mise.toml index 6f804a46..7e9c98ab 100644 --- a/mise.toml +++ b/mise.toml @@ -394,6 +394,14 @@ $env.name = $env.usage_name node scripts/create-account.mts ''' +[tasks."seed:revisions"] +description = "Seed resource revisions for UI work into a development PGlite database" +depends = ["build:backend"] +usage = ''' +flag "-d --data-path " default=".pgdata" help="PGlite data directory; it must not be seeded yet" +''' +run = "node scripts/seed-revisions/main.mts" + [tasks."generate:migrate"] description = "Generate database migration files" usage = """ diff --git a/package.json b/package.json index 4ef86fa5..597490b0 100644 --- a/package.json +++ b/package.json @@ -3,9 +3,11 @@ "devDependencies": { "@chillicream/agent-skills": "github:ChilliCream/agent-skills#23b4e12f696885fb5a71dacddddec69124207f94", "@dahlia/sacho": "github:dahlia/sacho#0.3.2", + "@drfed/federation": "workspace:*", "@drfed/graphql": "workspace:*", "@drfed/models": "workspace:*", "@electric-sql/pglite": "catalog:", + "@fedify/fedify": "catalog:", "@logtape/logtape": "catalog:", "@open-circle/agent-skills": "github:open-circle/agent-skills#21d123742218d3cd748056fad78aa88d7da3dc96", "@sigstore/oci": "0.7.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8fb6fd05..2ea61361 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -136,6 +136,9 @@ importers: '@dahlia/sacho': specifier: github:dahlia/sacho#0.3.2 version: https://codeload.github.com/dahlia/sacho/tar.gz/e8cb82260b34a29685fbe341e9c196d919cf9e9c + '@drfed/federation': + specifier: workspace:* + version: link:packages/federation '@drfed/graphql': specifier: workspace:* version: link:packages/graphql @@ -145,6 +148,9 @@ importers: '@electric-sql/pglite': specifier: 'catalog:' version: 0.5.3 + '@fedify/fedify': + specifier: 'catalog:' + version: 2.4.3 '@logtape/logtape': specifier: 'catalog:' version: 2.3.0-dev.840 @@ -1558,6 +1564,7 @@ packages: '@opentelemetry/sdk-trace-base@2.11.0': resolution: {integrity: sha512-H19x/TX/LZdqiYOjM7fqtSxwlplC5pgelavqbQdHbhdq0q/AI/TGkM2dfGuuynTXmJPeF2HoZVoPDu+TGoW78A==} engines: {node: ^18.19.0 || >=20.6.0} + deprecated: Use @opentelemetry/sdk-trace package peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' diff --git a/scripts/seed-revisions/case.mts b/scripts/seed-revisions/case.mts new file mode 100644 index 00000000..c40cbd0e --- /dev/null +++ b/scripts/seed-revisions/case.mts @@ -0,0 +1,68 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import type { LocalWriteEnvironment } from "@drfed/federation/local-write"; +import type { Database } from "@drfed/models"; +import type { Uuid } from "@drfed/models/uuid"; + +import type { Workspace } from "./environment.mts"; +import type { Writer } from "./writer.mts"; + +export const CAROL_IRI = "https://mastodon.example/users/carol"; +export const CAROL_FOLLOWERS_IRI = `${CAROL_IRI}/followers`; + +/** + * Composes the IRI of one of Carol's notes. + * @returns The IRI. + */ +export const carolNote = (name: string): string => + `https://mastodon.example/users/carol/statuses/${name}`; + +/** What every case works with. */ +export interface CaseContext { + readonly db: Database; + readonly env: LocalWriteEnvironment; + /** Workspace A, whose actor writes every local resource. */ + readonly alice: Workspace; + /** Workspace B, which only receives. */ + readonly bob: Workspace; + /** Writes as the actor of workspace A. */ + readonly writer: Writer; +} + +/** A resource to open in the UI to see a case. */ +export interface SeededResource { + readonly label: string; + readonly id: Uuid; + readonly iri: string; +} + +export interface SeededCase { + readonly number: number; + readonly title: string; + readonly resources: readonly SeededResource[]; +} + +export type SeedCase = (context: CaseContext) => Promise; + +/** + * Labels a saved resource for the report. + * @returns The labelled resource. + */ +export const labelled = ( + label: string, + { id, iri }: { readonly id: Uuid; readonly iri: string }, +): SeededResource => ({ label, id, iri }); diff --git a/scripts/seed-revisions/cases-access.mts b/scripts/seed-revisions/cases-access.mts new file mode 100644 index 00000000..ef370afd --- /dev/null +++ b/scripts/seed-revisions/cases-access.mts @@ -0,0 +1,113 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { PUBLIC_IRI } from "@drfed/models/resource"; + +import { + CAROL_FOLLOWERS_IRI, + CAROL_IRI, + type SeedCase, + carolNote, + labelled, +} from "./case.mts"; +import { receiveNote } from "./received.mts"; +import { ACTIVITY, loadHead, withoutContext } from "./writer.mts"; + +const privateEmbedding: SeedCase = async ({ db, alice, writer }) => { + const iri = carolNote("followers-only"); + const note = await receiveNote(db, { + iri, + attributedTo: CAROL_IRI, + content: "For my followers only", + to: [CAROL_FOLLOWERS_IRI], + deliveredTo: [alice], + }); + const announce = await writer.save( + { type: "Announce", object: withoutContext(note.document) }, + ACTIVITY, + ); + const head = await loadHead(db, announce.id); + const undo = await writer.save( + { type: "Undo", object: withoutContext(head.document) }, + ACTIVITY, + ); + return { + number: 16, + title: + "Announce embedding a private Note only A received (17: the Undo " + + "embedding that Announce)", + resources: [ + labelled("Announce", announce), + labelled("Undo (case 17)", undo), + { label: "Carol's Note", id: note.resourceId, iri }, + ], + }; +}; + +const laterRestricted: SeedCase = async ({ db, alice, bob, writer }) => { + const iri = carolNote("public-then-private"); + const first = await receiveNote(db, { + iri, + attributedTo: CAROL_IRI, + content: "Public at first", + to: [PUBLIC_IRI], + deliveredTo: [alice, bob], + }); + const liked = await writer.save( + { type: "Like", object: withoutContext(first.document) }, + ACTIVITY, + ); + await receiveNote(db, { + iri, + attributedTo: CAROL_IRI, + content: "Restricted to followers later", + to: [CAROL_FOLLOWERS_IRI], + deliveredTo: [alice], + }); + return { + number: 18, + title: + "Like embedding a public revision whose Note A alone later received " + + "a private revision of (19: the Note's history)", + resources: [ + labelled("Like", liked), + { label: "Carol's Note (case 19)", id: first.resourceId, iri }, + ], + }; +}; + +const receivedByBoth: SeedCase = async ({ db, alice, bob }) => { + const iri = carolNote("followers-only-both"); + const note = await receiveNote(db, { + iri, + attributedTo: CAROL_IRI, + content: "For my followers on both instances", + to: [CAROL_FOLLOWERS_IRI], + deliveredTo: [alice, bob], + }); + return { + number: 20, + title: "A private Note both A and B received", + resources: [{ label: "Carol's Note", id: note.resourceId, iri }], + }; +}; + +/** Cases 16 to 20: who may read a revision. */ +export const ACCESS_CASES: readonly SeedCase[] = [ + privateEmbedding, + laterRestricted, + receivedByBoth, +]; diff --git a/scripts/seed-revisions/cases-documents.mts b/scripts/seed-revisions/cases-documents.mts new file mode 100644 index 00000000..94461da7 --- /dev/null +++ b/scripts/seed-revisions/cases-documents.mts @@ -0,0 +1,157 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { ensureResource } from "@drfed/models/resource"; +import { appendResourceRevision } from "@drfed/models/resource-revision"; +import { uuidV7 } from "@drfed/models/uuid"; + +import { type SeedCase, labelled } from "./case.mts"; +import { ACTIVITY, AS } from "./writer.mts"; + +const UNREGISTERED_IRI = "https://remote.example/unregistered"; +const UNKNOWN_IRI = "https://remote.example/unknown"; + +const nestedUndo: SeedCase = async ({ alice, writer }) => { + const note = await writer.save({ type: "Note", content: "A liked note" }); + const undo = await writer.save( + { + type: "Undo", + object: { type: "Like", actor: alice.actorIri, object: note.iri }, + }, + ACTIVITY, + ); + return { + number: 1, + title: "Undo(Like(Note)) nesting", + resources: [labelled("Undo", undo), labelled("Note", note)], + }; +}; + +const addTarget: SeedCase = async ({ alice, writer }) => { + const note = await writer.save({ type: "Note", content: "A featured note" }); + const add = await writer.save( + { + type: "Add", + object: note.iri, + target: { type: "OrderedCollection", id: `${alice.actorIri}/featured` }, + }, + ACTIVITY, + ); + return { + number: 2, + title: "Add with a collection target", + resources: [labelled("Add", add)], + }; +}; + +const unresolvedReferences: SeedCase = async ({ db, writer }) => { + await ensureResource(db, UNKNOWN_IRI); + const undo = await writer.save( + { + type: "Undo", + object: [ + { type: "Like", object: UNREGISTERED_IRI }, + { type: "Like", object: UNKNOWN_IRI }, + ], + }, + ACTIVITY, + ); + return { + number: 3, + title: "References to an unregistered IRI and one of an unknown kind", + resources: [labelled("Undo", undo)], + }; +}; + +const intransitive: SeedCase = async ({ writer }) => ({ + number: 4, + title: "Arrive without an object", + resources: [ + labelled("Arrive", await writer.save({ type: "Arrive" }, ACTIVITY)), + ], +}); + +const editedAfterCreate: SeedCase = async ({ writer }) => { + const [note, create] = await writer.saveAll( + { type: "Create", object: { type: "Note", content: "First version" } }, + [ + { path: ["object"], kind: "object", representation: "embedded" }, + ...ACTIVITY, + ], + ); + if (note == null || create == null) throw new Error("Missing a resource."); + await writer.edit(note.id, { content: "Second version" }); + return { + number: 5, + title: "Create(Note), then the Note edited", + resources: [labelled("Create", create), labelled("Note", note)], + }; +}; + +const extensionsAndUninterpreted: SeedCase = async ({ db, alice, writer }) => { + const extended = await writer.save({ + "@context": [AS, { ex: "https://ext.example/ns#" }], + type: "Note", + content: "A note with an extension property", + "ex:mood": { level: 3 }, + }); + const tagged = await ensureResource(db, `${alice.actorIri}/seed/${uuidV7()}`); + // The validator refuses `tag`, so the common write cannot save this one. + await appendResourceRevision(db, { + resourceId: tagged.id, + resourceKind: "object", + expectedRevisionId: null, + kind: "snapshot", + capture: "local", + document: { + "@context": AS, + id: tagged.iri, + type: "Note", + content: "A note that is not interpreted", + tag: [{ type: "Mention", href: alice.actorIri }], + }, + }); + return { + number: 6, + title: "Extension properties, and a document that is not interpreted", + resources: [ + labelled("Note with an extension", extended), + labelled("Uninterpreted Note", tagged), + ], + }; +}; + +const deleted: SeedCase = async ({ writer }) => { + const note = await writer.save({ type: "Note", content: "Soon deleted" }); + await writer.edit(note.id, { content: "Edited before deletion" }); + await writer.remove(note.id); + return { + number: 7, + title: "A deleted object: a whiteout after two snapshots", + resources: [labelled("Note", note)], + }; +}; + +/** Cases 1 to 7: how documents and histories are read. */ +export const DOCUMENT_CASES: readonly SeedCase[] = [ + nestedUndo, + addTarget, + unresolvedReferences, + intransitive, + editedAfterCreate, + extensionsAndUninterpreted, + deleted, +]; diff --git a/scripts/seed-revisions/cases-sources.mts b/scripts/seed-revisions/cases-sources.mts new file mode 100644 index 00000000..ada7b0b1 --- /dev/null +++ b/scripts/seed-revisions/cases-sources.mts @@ -0,0 +1,207 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { + type JsonObject, + createLegacyObject, + isLocalWriteError, +} from "@drfed/federation/local-write"; +import { PUBLIC_IRI } from "@drfed/models/resource"; +import type { Uuid } from "@drfed/models/uuid"; + +import { type CaseContext, type SeedCase, labelled } from "./case.mts"; +import { ACTIVITY, AS, loadHead, withoutContext } from "./writer.mts"; + +interface SavedNote { + readonly id: Uuid; + readonly iri: string; + /** The revision an editor would have loaded the note from. */ + readonly revisionId: Uuid; + /** The note as another document embeds it. */ + readonly embedded: JsonObject; +} + +async function saveNote( + { db, writer }: CaseContext, + content: string, +): Promise { + const { id, iri } = await writer.save({ type: "Note", content }); + const head = await loadHead(db, id); + return { + id, + iri, + revisionId: head.revisionId, + embedded: withoutContext(head.document), + }; +} + +const like = (object: JsonObject): JsonObject => ({ type: "Like", object }); + +const declared = (note: SavedNote) => [ + { path: ["object"], revisionId: note.revisionId }, +]; + +const snapshotCurrent: SeedCase = async (context) => { + const note = await saveNote(context, "Embedded as it is"); + const saved = await context.writer.save(like(note.embedded), ACTIVITY); + return { + number: 8, + title: "Snapshot of a source that is still current", + resources: [labelled("Like", saved), labelled("Note", note)], + }; +}; + +const snapshotSuperseded: SeedCase = async (context) => { + const note = await saveNote(context, "Embedded, then edited"); + const saved = await context.writer.save(like(note.embedded), ACTIVITY); + await context.writer.edit(note.id, { content: "Edited after the Like" }); + return { + number: 9, + title: "Snapshot of a source with a newer revision", + resources: [labelled("Like", saved), labelled("Note", note)], + }; +}; + +const snapshotDeleted: SeedCase = async (context) => { + const note = await saveNote(context, "Embedded, then deleted"); + const saved = await context.writer.save(like(note.embedded), ACTIVITY); + await context.writer.remove(note.id); + return { + number: 10, + title: "Snapshot of a source that was deleted", + resources: [labelled("Like", saved), labelled("Note", note)], + }; +}; + +const derivedCurrent: SeedCase = async (context) => { + const note = await saveNote(context, "Loaded by an editor"); + const saved = await context.writer.save( + like({ ...note.embedded, content: "Changed before embedding" }), + ACTIVITY, + declared(note), + ); + return { + number: 11, + title: "Derived from a declared source that is still current", + resources: [labelled("Like", saved), labelled("Note", note)], + }; +}; + +const derivedSuperseded: SeedCase = async (context) => { + const note = await saveNote(context, "Loaded, then edited apart"); + const saved = await context.writer.save( + like({ ...note.embedded, content: "Changed before embedding" }), + ACTIVITY, + declared(note), + ); + await context.writer.edit(note.id, { content: "Edited after the Like" }); + return { + number: 12, + title: "Derived from a declared source with a newer revision", + resources: [labelled("Like", saved), labelled("Note", note)], + }; +}; + +const unknownSource: SeedCase = async (context) => { + const { env, alice, writer } = context; + const note = await saveNote(context, "Read by a script"); + await writer.edit(note.id, { content: "Edited before the script saved" }); + // The stale version matches no current revision, and nothing is declared. + const stale = await writer.save(like(note.embedded), ACTIVITY); + const legacy = await createLegacyObject( + env, + { accountId: alice.member.accountId }, + { + actorId: alice.actorId, + type: "Note", + contentHtml: "

Created through createObject

", + name: null, + summary: null, + language: null, + sensitive: false, + addressing: { to: [PUBLIC_IRI] }, + }, + ); + if (isLocalWriteError(legacy)) throw new Error(JSON.stringify(legacy)); + if (legacy.activityId == null) throw new Error("Missing the legacy Create."); + return { + number: 13, + title: "Unknown sources: an undeclared stale copy and a legacy Create", + resources: [ + labelled("Like of a stale copy", stale), + labelled("Note", note), + { label: "Legacy Create", id: legacy.activityId, iri: "" }, + { label: "Legacy Note", id: legacy.id, iri: "" }, + ], + }; +}; + +const reserialized: SeedCase = async (context) => { + const note = await saveNote(context, "Serialized differently"); + const reordered = Object.fromEntries( + Object.entries(note.embedded).toReversed(), + ); + const kept = await context.writer.save(like(reordered), ACTIVITY); + const recontextualized = await context.writer.save( + like({ + "@context": [AS, { ex: "https://ext.example/ns#" }], + ...note.embedded, + }), + ACTIVITY, + declared(note), + ); + return { + number: 14, + title: "Reordered keys stay a snapshot; another context is derived", + resources: [ + labelled("Like with reordered keys", kept), + labelled("Like with another context", recontextualized), + labelled("Note", note), + ], + }; +}; + +const deepSources: SeedCase = async (context) => { + const { db, writer } = context; + const note = await saveNote(context, "Embedded two levels deep"); + const liked = await writer.save(like(note.embedded), ACTIVITY); + const head = await loadHead(db, liked.id); + const undo = await writer.save( + { type: "Undo", object: withoutContext(head.document) }, + ACTIVITY, + ); + return { + number: 15, + title: "Undo(Like(Note)) with a source at both depths", + resources: [ + labelled("Undo", undo), + labelled("Like", liked), + labelled("Note", note), + ], + }; +}; + +/** Cases 8 to 15: where embedded documents came from. */ +export const SOURCE_CASES: readonly SeedCase[] = [ + snapshotCurrent, + snapshotSuperseded, + snapshotDeleted, + derivedCurrent, + derivedSuperseded, + unknownSource, + reserialized, + deepSources, +]; diff --git a/scripts/seed-revisions/environment.mts b/scripts/seed-revisions/environment.mts new file mode 100644 index 00000000..86cdb07c --- /dev/null +++ b/scripts/seed-revisions/environment.mts @@ -0,0 +1,238 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Keep dependent database writes sequential. +// oxlint-disable no-await-in-loop + +import createFederation from "@drfed/federation"; +import type { LocalWriteEnvironment } from "@drfed/federation/local-write"; +import { createYogaServer } from "@drfed/graphql"; +import { + type Database, + migrate, + openPersistentPglite, + relations, + schema, +} from "@drfed/models"; +import { type Uuid, uuidV7 } from "@drfed/models/uuid"; +import { MemoryKvStore } from "@fedify/fedify"; +import { eq } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/pglite"; + +const SLUG_A = "seed-a"; +const SLUG_B = "seed-b"; +const ACCOUNTS = [ + { key: "alice", name: "Alice", email: "alice@example.com", admin: false }, + { key: "bob", name: "Bob", email: "bob@example.com", admin: false }, + { key: "admin", name: "Admin", email: "admin@example.com", admin: true }, +] as const; + +/** An account the seed created, with an access token of its session. */ +export interface Member { + readonly accountId: Uuid; + readonly name: string; + readonly email: string; + readonly token: string; +} + +/** A local instance with its one member and one actor. */ +export interface Workspace { + readonly instanceId: Uuid; + readonly host: string; + readonly actorId: Uuid; + readonly actorIri: string; + /** Generated at random, so the report names it. */ + readonly actorUsername: string; + readonly member: Member; +} + +/** A GraphQL response body. */ +export interface GraphqlBody { + // oxlint-disable-next-line typescript/no-explicit-any + readonly data?: Record; + readonly errors?: readonly unknown[]; +} + +/** Sends a GraphQL request as a member, or anonymously for null. */ +export type GraphqlRequest = ( + member: Member | null, + query: string, + variables?: Record, +) => Promise; + +export interface SeedEnvironment { + readonly db: Database; + readonly write: LocalWriteEnvironment; + readonly graphql: GraphqlRequest; + readonly alice: Workspace; + readonly bob: Workspace; + readonly admin: Member; + close(): Promise; +} + +/** + * Encodes a Relay global ID. + * @returns The ID. + */ +export const globalId = (type: string, id: string): string => + Buffer.from(`${type}:${id}`).toString("base64"); + +const hashToken = async (token: string): Promise => + new Uint8Array( + await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)), + ).toHex(); + +async function createMembers(db: Database): Promise> { + const created = Temporal.Now.instant(); + const members: Record = {}; + for (const { key, name, email, admin } of ACCOUNTS) { + const accountId = uuidV7(); + const token = `seed-${key}-token`; + await db + .insert(schema.accounts) + .values({ id: accountId, email, name, admin, created }); + await db.insert(schema.sessions).values({ + id: uuidV7(), + accountId, + tokenHash: await hashToken(token), + }); + members[key] = { accountId, name, email, token }; + } + return members; +} + +async function createWorkspace( + db: Database, + graphql: GraphqlRequest, + member: Member, + slug: string, +): Promise { + const mutate = async (query: string, variables: Record) => { + const body = await graphql(member, query, variables); + if (body.errors != null) throw new Error(JSON.stringify(body.errors)); + }; + await mutate( + "mutation($slug: String!) { createInstance(slug: $slug) { __typename } }", + { slug }, + ); + const [instance] = await db + .select({ id: schema.instances.id, host: schema.instances.host }) + .from(schema.instances) + .innerJoin( + schema.localInstances, + eq(schema.localInstances.id, schema.instances.localId), + ) + .where(eq(schema.localInstances.slug, slug)); + if (instance == null) throw new Error(`Instance ${slug} was not created.`); + await mutate( + `mutation($instance: ID!) { + generateActors(instance: $instance, size: 1) { __typename } + }`, + { instance: globalId("Instance", instance.id) }, + ); + const [actor] = await db + .select({ + id: schema.actors.id, + iri: schema.resources.iri, + username: schema.actors.username, + }) + .from(schema.actors) + .innerJoin(schema.resources, eq(schema.resources.id, schema.actors.id)) + .where(eq(schema.actors.instanceId, instance.id)); + if (actor == null) throw new Error(`No actor was created on ${slug}.`); + return { + instanceId: instance.id, + host: instance.host, + actorId: actor.id, + actorIri: actor.iri, + actorUsername: actor.username ?? "", + member, + }; +} + +/** + * Opens the PGlite store, migrates it, and creates the accounts, instances + * and actors every case shares. A store that was seeded before is refused, + * because revisions cannot be replaced. + * @returns The environment; close it when done. + */ +export async function openSeedEnvironment( + dataPath: string, + rootOrigin: URL, +): Promise { + const store = await openPersistentPglite(dataPath); + try { + await store.ready; + const { client } = store; + await migrate({ credentials: { driver: "pglite", client } }); + const db: Database = drizzle({ client, relations, schema }); + const seeded = await db.$count( + schema.localInstances, + eq(schema.localInstances.slug, SLUG_A), + ); + if (seeded > 0) { + throw new Error( + `${dataPath} is already seeded. Revisions are immutable, so ` + + "remove the directory and run the seed again.", + ); + } + const federation = await createFederation(db, { kv: new MemoryKvStore() }); + const yoga = createYogaServer(db, federation, { + rootOrigin, + loginOrigins: new Set(), + }); + const endpoint = new URL("/graphql", rootOrigin).href; + const graphql: GraphqlRequest = async (member, query, variables = {}) => { + const response = await yoga.fetch(endpoint, { + method: "POST", + headers: { + "content-type": "application/json", + ...(member == null + ? {} + : { authorization: `Bearer ${member.token}` }), + }, + body: JSON.stringify({ query, variables }), + }); + return (await response.json()) as GraphqlBody; + }; + const members = await createMembers(db); + const { alice, bob, admin } = members; + if (alice == null || bob == null || admin == null) { + throw new Error("Missing a seeded account."); + } + return { + db, + graphql, + write: { + db, + federation, + rootOrigin, + previewKey: await crypto.subtle.generateKey( + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign", "verify"], + ), + }, + alice: await createWorkspace(db, graphql, alice, SLUG_A), + bob: await createWorkspace(db, graphql, bob, SLUG_B), + admin, + close: () => store.close(), + }; + } catch (error) { + await store.close(); + throw error; + } +} diff --git a/scripts/seed-revisions/main.mts b/scripts/seed-revisions/main.mts new file mode 100644 index 00000000..000fd2c6 --- /dev/null +++ b/scripts/seed-revisions/main.mts @@ -0,0 +1,107 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Seeds resource revisions for UI work into the development PGlite store. +// Run it through `mise run seed:revisions` while `mise run dev` is stopped: +// only one process can open the store. +// +// oxlint-disable no-console no-await-in-loop +import { join } from "node:path"; +import process from "node:process"; + +import type { SeedCase, SeededCase } from "./case.mts"; +import { ACCESS_CASES } from "./cases-access.mts"; +import { DOCUMENT_CASES } from "./cases-documents.mts"; +import { SOURCE_CASES } from "./cases-sources.mts"; +import { openSeedEnvironment } from "./environment.mts"; +import { type Viewer, reportCases } from "./report.mts"; +import { createWriter } from "./writer.mts"; + +const DEFAULT_DATA_PATH = ".pgdata"; +const DEFAULT_ROOT_ORIGIN = "http://drfed.localhost:8888"; +const CASES: readonly SeedCase[] = [ + ...DOCUMENT_CASES, + ...SOURCE_CASES, + ...ACCESS_CASES, +]; + +// The development server reads its origins from this file; use the same. +try { + process.loadEnvFile( + join(import.meta.dirname, "..", "..", "packages", "drfed", ".env"), + ); +} catch { + // Use the development default when the file is unavailable. +} + +async function main(): Promise { + const dataPath = process.env.usage_data_path ?? DEFAULT_DATA_PATH; + const rootOrigin = new URL( + process.env.DRFED_ROOT_ORIGIN ?? DEFAULT_ROOT_ORIGIN, + ); + const seed = await openSeedEnvironment(dataPath, rootOrigin); + try { + const { db, alice, bob, admin } = seed; + const context = { + db, + env: seed.write, + alice, + bob, + writer: createWriter(seed.write, alice), + }; + const seeded: SeededCase[] = []; + for (const run of CASES) seeded.push(await run(context)); + const viewers: readonly Viewer[] = [ + { label: "Alice (A)", member: alice.member }, + { label: "Bob (B)", member: bob.member }, + { label: "Admin", member: admin }, + { label: "Anonymous", member: null }, + ]; + console.log(`Seeded ${dataPath} under ${rootOrigin.origin}.`); + console.log(""); + console.log( + "Accounts. The web UI lists only the instances of the account logged " + + "in, so log in by email as Alice or Bob to see a workspace; the admin " + + "is a member of none. The tokens are for GraphQL requests only:", + ); + for (const { name, email, token } of [alice.member, bob.member, admin]) { + console.log(` ${name} <${email}>: ${token}`); + } + for (const [label, workspace] of [ + ["A", alice], + ["B", bob], + ] as const) { + console.log( + `Workspace ${label}: ${workspace.host}, member ${workspace.member.email}, ` + + `actor @${workspace.actorUsername} ${workspace.actorIri}`, + ); + } + console.log(""); + console.log("Each resource below is followed by what every viewer reads."); + for (const line of await reportCases(seed.graphql, viewers, seeded)) { + console.log(line); + } + } finally { + await seed.close(); + } +} + +try { + await main(); +} catch (error) { + console.error(error); + process.exitCode = 1; +} diff --git a/scripts/seed-revisions/received.mts b/scripts/seed-revisions/received.mts new file mode 100644 index 00000000..846ff315 --- /dev/null +++ b/scripts/seed-revisions/received.mts @@ -0,0 +1,88 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Keep dependent database writes sequential. +// oxlint-disable no-await-in-loop + +import type { JsonObject } from "@drfed/federation/local-write"; +import { type Database, schema } from "@drfed/models"; +import { ensureResource } from "@drfed/models/resource"; +import { + appendResourceRevision, + loadCurrentResourceRevision, +} from "@drfed/models/resource-revision"; +import { type Uuid, uuidV7 } from "@drfed/models/uuid"; + +import type { Workspace } from "./environment.mts"; +import { AS } from "./writer.mts"; + +/** A remote `Note` as an inbound delivery would carry it. */ +export interface ReceivedNote { + readonly iri: string; + readonly attributedTo: string; + readonly content: string; + readonly to: readonly string[]; + /** The workspaces whose inboxes received it. */ + readonly deliveredTo: readonly Workspace[]; +} + +/** + * Stores a version of a remote `Note` as a received revision, with a receipt + * for each workspace it was delivered to. No write path stores received + * documents as revisions yet, so the rows are written directly. + * @returns The note's resource ID and the new revision's ID. + */ +export async function receiveNote( + db: Database, + { iri, attributedTo, content, to, deliveredTo }: ReceivedNote, +): Promise<{ resourceId: Uuid; revisionId: Uuid; document: JsonObject }> { + const resource = await ensureResource(db, iri); + const current = await loadCurrentResourceRevision(db, resource.id); + const document: JsonObject = { + "@context": AS, + id: iri, + type: "Note", + attributedTo, + content, + to: [...to], + }; + const revision = await appendResourceRevision(db, { + resourceId: resource.id, + resourceKind: "object", + expectedRevisionId: current?.id ?? null, + kind: "snapshot", + capture: "received", + document, + addressing: { to: [...to] }, + }); + for (const { instanceId, actorIri } of deliveredTo) { + const deliveryId = uuidV7(); + await db.insert(schema.activityDeliveries).values({ + id: deliveryId, + instanceId, + direction: "inbound", + status: "received", + verificationResult: "verified", + inboxUrl: `${actorIri}/inbox`, + body: Buffer.from(JSON.stringify(document)), + completed: Temporal.Now.instant(), + }); + await db + .insert(schema.revisionReceipts) + .values({ deliveryId, revisionId: revision.id, role: "object" }); + } + return { resourceId: resource.id, revisionId: revision.id, document }; +} diff --git a/scripts/seed-revisions/report.mts b/scripts/seed-revisions/report.mts new file mode 100644 index 00000000..2e6ca822 --- /dev/null +++ b/scripts/seed-revisions/report.mts @@ -0,0 +1,174 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Keep the viewers' requests in a fixed order. +// oxlint-disable no-await-in-loop + +import type { SeededCase } from "./case.mts"; +import { type GraphqlRequest, type Member, globalId } from "./environment.mts"; + +const NODE = "type iri source { relation status revision { sequence } }"; +const RELATION = + "path representation resource { currentRevision { sequence } }"; +const QUERY = `query($id: ID!) { node(id: $id) { ... on Resource { + iri kind + currentRevision { sequence kind capture interpreted root { + ${NODE} relations { ${RELATION} node { + ${NODE} relations { ${RELATION} node { + ${NODE} + } } + } } + } } + revisions(first: 50) { edges { node { sequence kind capture } } } +} } }`; + +/** Who reads the seeded data, by a label for the report. */ +export interface Viewer { + readonly label: string; + readonly member: Member | null; +} + +interface NodeView { + readonly type: string | null; + readonly iri: string | null; + readonly source: { + readonly relation: string; + readonly status: string | null; + readonly revision: { readonly sequence: number }; + } | null; + readonly relations?: readonly { + readonly path: readonly (string | number)[]; + readonly representation: string; + readonly resource: { + readonly currentRevision: { readonly sequence: number } | null; + } | null; + readonly node: NodeView | null; + }[]; +} + +type Relation = NonNullable[number]; + +/** + * How a client may present where an embedded document came from, told from + * fields a reader already has: + * + * - `recorded`: the revision recorded its source. + * - `anonymous`: the document has no `id`, so it can have no source, and + * nothing needs to be shown. + * - `no-revisions`: no revision of the resource under its `id` is readable + * by the viewer, usually because none exists, as for a collection, so + * there was nothing to compare it with. + * - `unrecorded`: the resource has revisions, but none was recorded as the + * source. The document may still equal one of them; this is not a + * warning. + */ +export type SourceDisplay = + | "recorded" + | "anonymous" + | "no-revisions" + | "unrecorded"; + +/** + * Classifies an embedded document by {@link SourceDisplay}. + * @returns The class. + */ +export function sourceDisplay({ node, resource }: Relation): SourceDisplay { + if (node?.source != null) return "recorded"; + if (node?.iri == null) return "anonymous"; + return resource?.currentRevision == null ? "no-revisions" : "unrecorded"; +} + +const shortType = (type: string | null): string => + type?.split("#").at(-1) ?? "?"; + +/** + * Lists the embedded documents under a node with their sources. + * @returns One line per embedded document, parents first. + */ +function embeddedSources(parent: NodeView): string[] { + return (parent.relations ?? []).flatMap((relation) => { + const { path, representation, node } = relation; + if (representation !== "embedded" || node == null) return []; + const { source } = node; + const described = + source == null + ? `no source (${sourceDisplay(relation)})` + : `${source.relation} of #${source.revision.sequence}, status ${source.status ?? "null"}`; + return [ + `${path.join(".")} (${shortType(node.type)}): ${described}`, + ...embeddedSources(node), + ]; + }); +} + +// oxlint-disable-next-line typescript/no-explicit-any +function describe(node: Record | null | undefined): string[] { + if (node == null || node.kind == null) return ["resource: null"]; + const revisions = ( + node.revisions.edges as { node: { sequence: number; kind: string } }[] + ).map(({ node: { sequence, kind } }) => + kind === "snapshot" ? `#${sequence}` : `#${sequence} ${kind}`, + ); + const current = node.currentRevision; + const uninterpreted = + current?.kind === "snapshot" && !current.interpreted + ? " (not interpreted)" + : ""; + const head = + current == null + ? "null" + : `#${current.sequence} ${current.kind} ${current.capture}${uninterpreted}`; + const lines = [ + `kind ${node.kind}; revisions [${revisions.join(", ")}]; current ${head}`, + ]; + const root = current?.root as NodeView | null | undefined; + return root == null ? lines : [...lines, ...embeddedSources(root)]; +} + +/** + * Reads every seeded resource as every viewer through GraphQL. + * @returns The report as text lines. + */ +export async function reportCases( + graphql: GraphqlRequest, + viewers: readonly Viewer[], + cases: readonly SeededCase[], +): Promise { + const lines: string[] = []; + for (const { number, title, resources } of cases) { + lines.push("", `## ${number}. ${title}`); + for (const { label, id, iri } of resources) { + lines.push("", `${label}: ${globalId("Resource", id)}`); + if (iri !== "") lines.push(` ${iri}`); + for (const viewer of viewers) { + const body = await graphql(viewer.member, QUERY, { + id: globalId("Resource", id), + }); + const described = + body.errors == null + ? describe(body.data?.node) + : [`errors: ${JSON.stringify(body.errors)}`]; + lines.push( + ...described.map( + (line, index) => + ` ${index === 0 ? viewer.label.padEnd(10) : " ".repeat(10)} ${line}`, + ), + ); + } + } + } + return lines; +} diff --git a/scripts/seed-revisions/writer.mts b/scripts/seed-revisions/writer.mts new file mode 100644 index 00000000..7cc9ff26 --- /dev/null +++ b/scripts/seed-revisions/writer.mts @@ -0,0 +1,153 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { + type CreateRequest, + type EmbeddedSource, + type JsonObject, + type LocalWriteEnvironment, + type LocalWriteRequest, + type LocalWriteResult, + type SavedResource, + commitLocalWrite, + previewLocalWrite, +} from "@drfed/federation/local-write"; +import type { Database } from "@drfed/models"; +import { loadCurrentResourceRevision } from "@drfed/models/resource-revision"; +import type { Uuid } from "@drfed/models/uuid"; + +import type { Workspace } from "./environment.mts"; + +export const AS = "https://www.w3.org/ns/activitystreams"; +export const ACTIVITY: CreateRequest["resources"] = [ + { path: [], kind: "activity" }, +]; +const OBJECT: CreateRequest["resources"] = [{ path: [], kind: "object" }]; + +/** The current snapshot of a resource. */ +export interface Head { + readonly revisionId: Uuid; + readonly document: JsonObject; +} + +/** Local writes of one actor, through the common write operations. */ +export interface Writer { + /** Saves new resources. @returns The root resource, saved last. */ + save( + document: JsonObject, + resources?: CreateRequest["resources"], + sources?: readonly EmbeddedSource[], + ): Promise; + /** Saves new resources. @returns All of them, the root last. */ + saveAll( + document: JsonObject, + resources: CreateRequest["resources"], + sources?: readonly EmbeddedSource[], + ): Promise; + /** Edits an object by changing its current document. */ + edit(objectId: Uuid, changes: JsonObject): Promise; + /** Deletes an object, appending a whiteout. */ + remove(objectId: Uuid): Promise; +} + +/** + * Drops the `@context` of a stored document, to embed it in another. + * @returns The rest of the document. + */ +export const withoutContext = ({ + "@context": _, + ...rest +}: JsonObject): JsonObject => rest; + +/** + * Reads the current snapshot of a resource. + * @returns Its revision ID and document. + */ +export async function loadHead(db: Database, resourceId: Uuid): Promise { + const revision = await loadCurrentResourceRevision(db, resourceId); + if (revision?.document == null) { + throw new Error(`Resource ${resourceId} has no current snapshot.`); + } + return { + revisionId: revision.id, + document: revision.document as JsonObject, + }; +} + +/** + * Makes the writer of a workspace's actor. Nothing it saves is delivered: + * edits and deletions get a reservation that does nothing. + * @returns The writer. + */ +export function createWriter( + env: LocalWriteEnvironment, + { actorId, member }: Workspace, +): Writer { + const principal = { accountId: member.accountId }; + const commit = async ( + request: LocalWriteRequest, + ): Promise => { + const preview = await previewLocalWrite(env, principal, request); + if (!preview.ok) throw new Error(JSON.stringify(preview.error)); + const outcome = await commitLocalWrite(env, principal, request, { + previewToken: preview.preview.token, + ...(request.operation === "create" + ? {} + : { reserveDispatch: () => Promise.resolve() }), + }); + if (!outcome.ok) throw new Error(JSON.stringify(outcome.error)); + return outcome.result; + }; + const saveAll: Writer["saveAll"] = async (document, resources, sources) => { + const result = await commit({ + operation: "create", + actorId, + document: { "@context": AS, ...document }, + resources, + ...(sources == null ? {} : { sources }), + }); + return result.resources; + }; + return { + saveAll, + async save(document, resources, sources) { + const saved = (await saveAll(document, resources ?? OBJECT, sources)).at( + -1, + ); + if (saved == null) throw new Error("Nothing was saved."); + return saved; + }, + async edit(objectId, changes) { + const head = await loadHead(env.db, objectId); + await commit({ + operation: "edit", + actorId, + objectId, + expectedRevisionId: head.revisionId, + document: { ...head.document, ...changes }, + }); + }, + async remove(objectId) { + const head = await loadHead(env.db, objectId); + await commit({ + operation: "delete", + actorId, + objectId, + expectedRevisionId: head.revisionId, + }); + }, + }; +} From 858169affb860d6643f023f4aa8087e20989a40a Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Sun, 15 Nov 2026 20:54:54 +0900 Subject: [PATCH 04/10] Read revisions without regard to their sources Whether a revision is readable no longer depends on the revisions its embedded documents came from. A local document that records the revision of a private received Note as its source now reads as the same document pasted without one, rather than being hidden as a whole from those who may not read that Note. The received revision itself stays readable only by its own evidence: local capture, public addressing, a receipt for an instance the viewer belongs to, or being the current revision of a readable resource with a legacy typed row. Only following a source checks the source revision. DocumentNode.source is null when the viewer may not read it, together with its relation and status, while the embedded node, the root, and the raw document read as the revision embedding them does. The status of a readable source is null when the current revision of its resource is not readable. Resource.revision(sequence:) returns one revision by its sequence, and null both for a missing sequence and for an unreadable revision. unreadableRevisions() in readable.ts applies the same rule to a set of revision IDs. https://github.com/fedify-dev/drfed/issues/154 https://github.com/fedify-dev/drfed/issues/154#issuecomment-6850587268 AI assistance: the maintainer asked Claude Code to complete the GraphQL chapters of the issue's plan, following the review comment above that rejected sources as a read condition. Claude Code wrote the access rule, the fields, the tests across two workspaces, and the documentation and changelog. The maintainer reviewed the result against the comment point by point. The build, checks, and test suite were run with PGlite; the PostgreSQL variants were skipped. Assisted-by: Claude Code:claude-opus-5-5 --- CHANGES.md | 13 +- CONTRIBUTING.md | 6 + changes.d/graphql/resource-revisions.md | 13 +- docs/internals/resource-revisions.md | 39 +-- packages/graphql/README.md | 14 +- packages/graphql/src/readable.ts | 154 ++++++------ packages/graphql/src/revision.test.ts | 314 ++++++++++++++++++------ packages/graphql/src/revision.ts | 201 +++++++++------ 8 files changed, 499 insertions(+), 255 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 95526134..0eab9c67 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -45,9 +45,10 @@ To be released. ### GraphQL APIs - - Added `Resource.currentRevision` and `Resource.revisions`, newest first, - and the `ResourceRevision` node, which return the saved revisions of a - resource, including those of resources saved without legacy details. + - Added `Resource.currentRevision`, `Resource.revisions`, newest first, + `Resource.revision(sequence:)`, and the `ResourceRevision` node, which + return the saved revisions of a resource, including those of resources + saved without legacy details. Each revision returns its saved JSON, whiteout deletion details, and what the current validator finds in it. When the validator reads the document, `root` describes it by meaning, whatever keys spell its @@ -59,9 +60,9 @@ To be released. received them. `DocumentNode.source` tells which revision an embedded document came from, whether it keeps that revision's contents or was derived from it, and whether that revision is still current, superseded, or - deleted. A revision that embeds documents from revisions the viewer may - not read is hidden as a whole. Deleting a resource or its author hides - none of its revisions by itself. [[#154]] + deleted; it is null when the viewer may not read that revision, and the + embedded document itself stays readable. Deleting a resource or its + author hides none of its revisions by itself. [[#154]] - Fixed `Resource.detail` to return `null` without a field error when the resource has no corresponding detail record. [[#150], [#164] by Hong Minhee\] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3e0592ae..27c8939f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -715,6 +715,12 @@ The GraphQL types for activity deliveries live in *src/activity-delivery/entry.ts*. Delivery contents are private to local instance members and administrators, including Relay node lookups. +The GraphQL types for resource revisions live in *src/revision.ts*. Each +revision is read by evidence of its own, through `readableRevision()` in +*src/readable.ts*, never by the current state of its resource nor by where +its embedded documents came from; only `DocumentNode.source` checks a source +revision. Filter revisions by it before paging. + CLI and server changes ---------------------- diff --git a/changes.d/graphql/resource-revisions.md b/changes.d/graphql/resource-revisions.md index 7a349aae..732b006c 100644 --- a/changes.d/graphql/resource-revisions.md +++ b/changes.d/graphql/resource-revisions.md @@ -2,9 +2,10 @@ links: '#154': https://github.com/fedify-dev/drfed/issues/154 --- - - Added `Resource.currentRevision` and `Resource.revisions`, newest first, - and the `ResourceRevision` node, which return the saved revisions of a - resource, including those of resources saved without legacy details. + - Added `Resource.currentRevision`, `Resource.revisions`, newest first, + `Resource.revision(sequence:)`, and the `ResourceRevision` node, which + return the saved revisions of a resource, including those of resources + saved without legacy details. Each revision returns its saved JSON, whiteout deletion details, and what the current validator finds in it. When the validator reads the document, `root` describes it by meaning, whatever keys spell its @@ -16,6 +17,6 @@ links: received them. `DocumentNode.source` tells which revision an embedded document came from, whether it keeps that revision's contents or was derived from it, and whether that revision is still current, superseded, or - deleted. A revision that embeds documents from revisions the viewer may - not read is hidden as a whole. Deleting a resource or its author hides - none of its revisions by itself. [[#154]] + deleted; it is null when the viewer may not read that revision, and the + embedded document itself stays readable. Deleting a resource or its + author hides none of its revisions by itself. [[#154]] diff --git a/docs/internals/resource-revisions.md b/docs/internals/resource-revisions.md index ea674777..ec58a073 100644 --- a/docs/internals/resource-revisions.md +++ b/docs/internals/resource-revisions.md @@ -181,7 +181,9 @@ other addressing. An embedded document without a row has an unknown source, which proves neither that it was nor that it was never saved as a revision: older data and pasted documents lack the record. An IRI reference is a separate choice, recorded as the `reference` representation of a relation, -and has no source. +and has no source. A source is no condition on reading the revision that +records it: who may read an embedded document is decided by the revision +embedding it alone. Rows are written with the revision through the `embeddings` input of `appendResourceRevision()` and `writeTypedResourceRevision()`, and like other @@ -229,8 +231,8 @@ Fetched evidence is recomputed when `recordFetchedObject` changes. Deleting a typed object row removes its object receipts; deleting an activity or removing a delivery linkage removes that delivery's receipts; deleting a delivery cascades them. Unavailable and whiteout revisions receive no legacy receipt. -Existing GraphQL permission checks still use their current evidence rules; the -new index does not expose historical content. +GraphQL reads each revision by this evidence, as +[GraphQL reads](#graphql-reads) describe. Application boundaries @@ -242,7 +244,9 @@ generic canonical resource can have no typed detail; its GraphQL such a resource from its current revision. The common write operations described in [local writes](local-writes.md) save new resources as revisions only and keep legacy typed objects in step when editing or deleting -them. The other federation surfaces are separate work. +them. GraphQL reads every revision by its own evidence, as +[GraphQL reads](#graphql-reads) describe. The other federation surfaces are +separate work. Appending a whiteout does not create or send a `Delete` activity. The common delete operation appends it together with the `Delete`, outbox entry and the @@ -292,15 +296,14 @@ resource does not hide an earlier public one. A Relay node lookup of a revision checks the revision itself, and `Resource.revisions` leaves out the ones the viewer may not read, so their sequences can skip. -A revision is also readable only when the viewer may read, by the same -evidence, every revision it carries through its -[embedded document sources](#embedded-document-sources), directly or through -the local revisions it embeds. A local `Announce` that embeds a `Note` -received only by one instance is thus readable only by that instance's -members and administrators; anyone else reads it as if it did not exist. The -whole revision is hidden rather than the embedded part, so that the same saved -JSON is never read differently by different viewers, and a reader of a -revision may always read its sources. +What a revision embeds never decides whether it is readable. A local +`Announce` that embeds a `Note` only one instance received is readable by +anyone, as every local revision is, whether it records that `Note`'s revision +as its source or was pasted without one: recording a source never makes a +document harder to read. Only following the source checks the source +revision, as `DocumentNode.source` does below. Received content stays +protected where it is read: the received revision itself is readable only by +the evidence above. Deletion hides no revision by itself: deleting a resource appends a whiteout, and its earlier revisions, like those of a resource whose author is deleted, @@ -316,4 +319,12 @@ a whiteout, and `superseded` otherwise. The status compares revisions only, not contents. It is null when the viewer may not read the current revision, which would otherwise tell of a revision they may not read. `source` is null for the root, for an embedded document whose source is unknown, and when the -viewer may not read the source revision. +viewer may not read the source revision; these are not told apart, and +`relation` is not kept alone either, since `snapshot` next to the embedded +contents would tell those of a revision the viewer may not read. Whatever +`source` is, the embedded `node`, the `root` and the raw `document` read as +the revision embedding them does. + +`Resource.revision(sequence:)` returns one revision by its sequence, and null +both for a sequence with no revision and for a revision the viewer may not +read. diff --git a/packages/graphql/README.md b/packages/graphql/README.md index 6df0132d..a47f1c81 100644 --- a/packages/graphql/README.md +++ b/packages/graphql/README.md @@ -101,12 +101,14 @@ Each revision is read by evidence of its own: anyone reads local revisions, blind recipients included, and revisions addressed to the public; members of a local instance read what a delivery to it carried; and a revision without such evidence is readable only while it is current and its resource is, as -above. A revision whose embedded documents came from revisions the viewer -may not read is hidden as a whole. Deletion hides no revision by itself, -while `Resource.detail` and the other existing fields keep hiding what was -deleted. `DocumentNode.source` names the revision an embedded document came -from, whether it keeps that revision's contents or was derived from it, and -whether that revision is still current, superseded, or deleted. See +above. Where a revision's embedded documents came from never hides it. +Deletion hides no revision by itself, while `Resource.detail` and the other +existing fields keep hiding what was deleted. `Resource.revision(sequence:)` +returns one revision by its sequence. `DocumentNode.source` names the +revision an embedded document came from, whether it keeps that revision's +contents or was derived from it, and whether that revision is still current, +superseded, or deleted; it is null when the viewer may not read the source +revision, and nothing else of the document changes. See [resource revision internals]. [resource revision internals]: https://drfed.org/internals/resource-revisions#graphql-reads diff --git a/packages/graphql/src/readable.ts b/packages/graphql/src/readable.ts index 9a984ac6..1c6e89d5 100644 --- a/packages/graphql/src/readable.ts +++ b/packages/graphql/src/readable.ts @@ -30,7 +30,6 @@ import { resourceRevisions, resources, revisionAddressing, - revisionEmbeddings, revisionReceipts, } from "@drfed/models/schema"; import { type Uuid, validateUuid } from "@drfed/models/uuid"; @@ -135,8 +134,6 @@ const evidencedAddressing = alias(revisionAddressing, "evidenced_addressing"); const evidencedReceipts = alias(revisionReceipts, "evidenced_receipts"); const receiptDeliveries = alias(activityDeliveries, "receipt_deliveries"); const evidencedHeads = alias(resourceHeads, "evidenced_heads"); -const embedded = alias(revisionEmbeddings, "embedded_sources"); -const transitive = alias(revisionEmbeddings, "transitive_sources"); const remoteActivity = (id: SQLWrapper): SQL => sql`exists ( select 1 from ${activities} ${remoteActivities} @@ -269,53 +266,25 @@ function legacyTypedRow(id: SQLWrapper): SQL { ))`; } -// What a revision itself proves of who may read it, whatever it embeds. -const ownEvidence = (viewer: Viewer, id: SQLWrapper): SQL => sql`exists ( - select 1 from ${resourceRevisions} ${evidenced} - where ${evidenced.id} = ${id} and ( - ${evidenced.capture} = 'local' - or exists ( - select 1 from ${revisionAddressing} ${evidencedAddressing} - where ${evidencedAddressing.revisionId} = ${evidenced.id} - and ${inArray(evidencedAddressing.iri, PUBLIC_IRIS)} - ) - or exists ( - select 1 from ${revisionReceipts} ${evidencedReceipts} - join ${activityDeliveries} ${receiptDeliveries} - on ${receiptDeliveries.id} = ${evidencedReceipts.deliveryId} - where ${evidencedReceipts.revisionId} = ${evidenced.id} - and ${receiptDeliveries.direction} = 'inbound' - and ${viewableInstance(viewer, receiptDeliveries.instanceId)} - ) - or ( - exists ( - select 1 from ${resourceHeads} ${evidencedHeads} - where ${evidencedHeads.resourceId} = ${evidenced.resourceId} - and ${evidencedHeads.revisionId} = ${evidenced.id} - ) - and ${legacyTypedRow(evidenced.resourceId)} - and ${readableResource(viewer, evidenced.resourceId)} - ) - ) -)`; - /** * Restricts revisions to those the viewer may read. An administrator reads * every revision. Anyone else reads a revision by evidence of that * particular revision, never by the current state of its resource: * - * - Its own evidence: DrFed saved it for a local actor, so it is readable - * by anyone, with its blind recipients and whether published or not, as - * `Object.document` is; its own addressing is public; a receipt links it - * to an inbound delivery to a local instance the viewer may read, as - * {@link viewableInstance} tells; or it is the current revision of a - * resource with a legacy typed row that {@link readableResource} lets - * the viewer read, since that row describes only its current version. - * - The evidence of what it embeds: every revision its recorded - * embeddings name as their sources, and theirs in turn, must have its - * own evidence too. A local document embedding a private received - * revision is thus readable only by those who could read that revision, - * including when it was derived from it. + * - DrFed saved it for a local actor, so it is readable by anyone, with + * its blind recipients and whether published or not, as + * `Object.document` is. + * - Its own addressing is public. + * - A receipt links it to an inbound delivery to a local instance the + * viewer may read, as {@link viewableInstance} tells. + * - It is the current revision of a resource with a legacy typed row that + * {@link readableResource} lets the viewer read, since that row + * describes only its current version. + * + * What a revision embeds, and the revisions its embedded documents came + * from, never decide whether it is readable: a document recording its + * sources reads as the same document pasted without them. Only following + * a source to its revision checks that revision. * * A later revision being restricted, or deleted, hides no earlier one that * was public, and a later delivery or public revision of the same IRI opens @@ -327,19 +296,59 @@ const ownEvidence = (viewer: Viewer, id: SQLWrapper): SQL => sql`exists ( */ export function readableRevision(viewer: Viewer, id: SQLWrapper): SQL { if (viewer.account?.admin === true) return sql`true`; - // Sources are stored before what embeds them, so the recursion ends; the - // union stops it on a cycle all the same. - return sql`(${ownEvidence(viewer, id)} and not exists ( - with recursive readable_sources(id) as ( - select ${embedded.sourceRevisionId} from ${revisionEmbeddings} ${embedded} - where ${embedded.revisionId} = ${id} - union - select ${transitive.sourceRevisionId} from ${revisionEmbeddings} ${transitive} - join readable_sources on readable_sources.id = ${transitive.revisionId} + return sql`exists ( + select 1 from ${resourceRevisions} ${evidenced} + where ${evidenced.id} = ${id} and ( + ${evidenced.capture} = 'local' + or exists ( + select 1 from ${revisionAddressing} ${evidencedAddressing} + where ${evidencedAddressing.revisionId} = ${evidenced.id} + and ${inArray(evidencedAddressing.iri, PUBLIC_IRIS)} + ) + or exists ( + select 1 from ${revisionReceipts} ${evidencedReceipts} + join ${activityDeliveries} ${receiptDeliveries} + on ${receiptDeliveries.id} = ${evidencedReceipts.deliveryId} + where ${evidencedReceipts.revisionId} = ${evidenced.id} + and ${receiptDeliveries.direction} = 'inbound' + and ${viewableInstance(viewer, receiptDeliveries.instanceId)} + ) + or ( + exists ( + select 1 from ${resourceHeads} ${evidencedHeads} + where ${evidencedHeads.resourceId} = ${evidenced.resourceId} + and ${evidencedHeads.revisionId} = ${evidenced.id} + ) + and ${legacyTypedRow(evidenced.resourceId)} + and ${readableResource(viewer, evidenced.resourceId)} + ) ) - select 1 from readable_sources - where not ${ownEvidence(viewer, sql`readable_sources.id`)} - ))`; + )`; +} + +/** + * Finds the revisions among the given IDs that the viewer may not read, as + * {@link readableRevision} decides. IDs of no stored revision are never + * among them. A local write takes it to check the sources a writer + * declares, so that a writer embeds as a snapshot or derivation only what + * they may read. + * @returns The IDs the viewer may not read. + */ +export async function unreadableRevisions( + viewer: Viewer, + ids: readonly Uuid[], +): Promise> { + if (ids.length === 0 || viewer.account?.admin === true) return new Set(); + const rows = await viewer.db + .select({ id: resourceRevisions.id }) + .from(resourceRevisions) + .where( + and( + inArray(resourceRevisions.id, [...new Set(ids)]), + not(readableRevision(viewer, resourceRevisions.id)), + ), + ); + return new Set(rows.map(({ id }) => id)); } /** @@ -404,37 +413,26 @@ export async function hideUnreadableNodes( viewer: Viewer, nodes: readonly unknown[], ): Promise { - const owned = nodes.map((node) => + const revisionIds = nodes.map((node) => owningResourceOf(node) == null ? null : uuidOf(node, "id"), ); - const ids = nodes.map((node, index) => - owned[index] == null && owningResourceOf(node) == null - ? uuidOf(node, "id") - : null, + const ids = nodes.map((node) => + owningResourceOf(node) == null ? uuidOf(node, "id") : null, ); - const revisionIds = [...new Set(owned.filter((id) => id != null))]; - const [hidden, readableRevisions] = await Promise.all([ + const [hidden, hiddenRevisions] = await Promise.all([ unreadableResources( viewer, ids.filter((id) => id != null), ), - revisionIds.length === 0 - ? [] - : viewer.db - .select({ id: resourceRevisions.id }) - .from(resourceRevisions) - .where( - and( - inArray(resourceRevisions.id, revisionIds), - readableRevision(viewer, resourceRevisions.id), - ), - ), + unreadableRevisions( + viewer, + revisionIds.filter((id) => id != null), + ), ]); - const open = new Set(readableRevisions.map(({ id }) => id)); return nodes.map((node, index) => { if (owningResourceOf(node) != null) { - const id = owned[index]; - return id != null && open.has(id) ? node : null; + const id = revisionIds[index]; + return id == null || hiddenRevisions.has(id) ? null : node; } const id = ids[index]; return id != null && hidden.has(id) ? null : node; diff --git a/packages/graphql/src/revision.test.ts b/packages/graphql/src/revision.test.ts index fb5222a5..832f96df 100644 --- a/packages/graphql/src/revision.test.ts +++ b/packages/graphql/src/revision.test.ts @@ -35,6 +35,7 @@ import { loadCurrentResourceRevision, writeTypedResourceRevision, } from "@drfed/models/resource-revision"; +import type { Account } from "@drfed/models/schema"; import { type Uuid, uuidV7 } from "@drfed/models/uuid"; import { eq } from "drizzle-orm"; @@ -43,6 +44,7 @@ import { type TestHarness, withTestHarness } from "./harness.test.ts"; import { accountId, created, + expires, globalId, localActorId, localInstanceId, @@ -58,6 +60,7 @@ const ACTOR_IRI = `https://test-instance.drfed.org/users/${localActorId}`; const FEATURED_IRI = `${ACTOR_IRI}/featured`; const BLIND = "https://remote.example/users/blind"; const PRINCIPAL = { accountId: accountId as Uuid }; +const CAROL = "https://remote.example/users/carol"; const revisionId = (id: string): string => Buffer.from(`ResourceRevision:${id}`).toString("base64"); @@ -877,26 +880,56 @@ describe("Access to revisions", () => { }); /** - * Signs in an account that is no member of the local instance, or an - * administrator. - * @returns The request options that authenticate as it. + * Signs in an account: an administrator, an accepted member of the given + * local instance, or one that is neither. + * @returns Its account and the request options that authenticate as it. */ -async function seedViewer(db: Database, admin: boolean): Promise { +async function seedViewer( + db: Database, + { admin = false, memberOf }: { admin?: boolean; memberOf?: Uuid } = {}, +): Promise<{ account: Account; auth: RequestInit }> { const id = uuidV7(); const token = `token-${id}`; - await db.insert(schema.accounts).values({ - id, - email: `${id}@example.com`, - name: admin ? "Admin" : "Outsider", - admin, - created, - }); + const [account] = await db + .insert(schema.accounts) + .values({ + id, + email: `${id}@example.com`, + name: admin ? "Admin" : "Viewer", + admin, + created, + }) + .returning(); + assert.ok(account != null); await db.insert(schema.sessions).values({ id: uuidV7(), accountId: id, tokenHash: await hashSecret(token), }); - return { headers: { authorization: `Bearer ${token}` } }; + if (memberOf != null) { + await db.insert(schema.instanceMembers).values({ + accountId: id, + instanceId: memberOf, + accepted: created, + created, + }); + } + return { account, auth: { headers: { authorization: `Bearer ${token}` } } }; +} + +/** + * Opens a second workspace, a local instance apart from the writer's. + * @returns Its instance ID. + */ +async function seedWorkspace(db: Database): Promise { + const id = uuidV7(); + await db + .insert(schema.localInstances) + .values({ id, slug: "workspace-b", expires }); + await db + .insert(schema.instances) + .values({ id, localId: id, created, host: "workspace-b.drfed.org" }); + return id; } /** @@ -923,12 +956,16 @@ async function receive( return { resourceId: resource.id, revisionId: revision.id }; } -/** Links a revision to an inbound delivery to the local instance. */ -async function receipt(db: Database, revision: Uuid): Promise { +/** Links a revision to an inbound delivery to a local instance. */ +async function receipt( + db: Database, + revision: Uuid, + instanceId: Uuid = localInstanceId, +): Promise { const deliveryId = uuidV7(); await db.insert(schema.activityDeliveries).values({ id: deliveryId, - instanceId: localInstanceId, + instanceId, direction: "inbound", status: "received", verificationResult: "verified", @@ -943,15 +980,17 @@ async function receipt(db: Database, revision: Uuid): Promise { /** * Saves a local activity that embeds a document as its `object`, with the - * embedding recorded when a source is given. - * @returns The activity's resource ID and its revision ID. + * embedding recorded when a source is given. It records the source + * directly, without the check a local write makes, as if the writer could + * read the source when saving and may not any more. + * @returns The activity's resource ID, IRI, and revision ID. */ async function embed( db: Database, type: string, object: JsonObject, source?: { revisionId: Uuid; relation: "snapshot" | "derived" }, -): Promise<{ resourceId: Uuid; revisionId: Uuid }> { +): Promise<{ resourceId: Uuid; iri: string; revisionId: Uuid }> { const resource = await ensureResource(db, `${ACTOR_IRI}/${uuidV7()}`); const revision = await appendResourceRevision(db, { resourceId: resource.id, @@ -978,84 +1017,209 @@ async function embed( ], }), }); - return { resourceId: resource.id, revisionId: revision.id }; + return { + resourceId: resource.id, + iri: resource.iri, + revisionId: revision.id, + }; } const withoutContext = ({ "@context": _, ...rest }: JsonObject): JsonObject => rest; -describe("Access to revisions by their embeddings", () => { - it("opens a document embedding a private received revision only to its readers", async () => { +/** + * Replaces an IRI in a response, to compare two responses about resources + * that differ only in their IRIs. + * @returns The response with the IRI replaced. + */ +const withoutIri = (value: unknown, iri: string): unknown => + JSON.parse(JSON.stringify(value).replaceAll(iri, "")); + +describe("Access to revisions across workspaces", () => { + // Workspace A is the writer's local instance; only workspace B received a + // private Note from elsewhere. + const privateNote = async (db: Database) => { + const workspaceB = await seedWorkspace(db); + const iri = `https://remote.example/notes/${uuidV7()}`; + const received = await receive( + db, + iri, + [`${CAROL}/followers`], + "only workspace B received this", + ); + await receipt(db, received.revisionId, workspaceB); + const stored = await head(db, received.resourceId); + return { + workspaceB, + ...received, + embedded: withoutContext(stored.document as JsonObject), + }; + }; + + it("hides a revision only B received from A, but no local document embedding it", async () => { await withWriter(async ({ harness, auth, query }) => { const { db } = harness; - const iri = `https://remote.example/notes/${uuidV7()}`; - const followers = "https://remote.example/users/carol/followers"; - const received = await receive(db, iri, [followers], "secret"); - await receipt(db, received.revisionId); - const stored = await loadCurrentResourceRevision(db, received.resourceId); - const announce = await embed( - db, - "Announce", - withoutContext(stored!.document as JsonObject), - { revisionId: received.revisionId, relation: "snapshot" }, - ); - // An intermediate local revision carries the requirement on. - const announced = await loadCurrentResourceRevision( - db, - announce.resourceId, - ); - const undo = await embed( - db, - "Undo", - withoutContext(announced!.document as JsonObject), - { revisionId: announce.revisionId, relation: "snapshot" }, - ); - const read = `query($announce: ID!, $announceRevision: ID!, $undo: ID!, $undoRevision: ID!) { - announcement: node(id: $announce) { ... on Resource { - currentRevision { id } revisions { edges { node { id } } } + const note = await privateNote(db); + const memberB = await seedViewer(db, { memberOf: note.workspaceB }); + const outsider = await seedViewer(db); + const admin = await seedViewer(db, { admin: true }); + const sourced = await embed(db, "Like", note.embedded, { + revisionId: note.revisionId, + relation: "snapshot", + }); + const pasted = await embed(db, "Like", note.embedded); + const read = `query($note: ID!, $revision: ID!, $sourced: ID!, $pasted: ID!) { + note: node(id: $note) { ... on Resource { + currentRevision { id } + revision(sequence: 1) { id } + revisions { edges { node { id } } pageInfo { hasNextPage } } } } - announceRevision: node(id: $announceRevision) { ... on ResourceRevision { id } } - undoing: node(id: $undo) { ... on Resource { currentRevision { id } } } - undoRevisions: nodes(ids: [$undoRevision]) { id } - }`; + revision: node(id: $revision) { ... on ResourceRevision { sequence } } + revisions: nodes(ids: [$revision]) { id } + sourced: node(id: $sourced) { ...embedding } + pasted: node(id: $pasted) { ...embedding } + } + fragment embedding on Resource { currentRevision { + document + root { relations(property: object) { node { + document + source { relation status revision { id } } + } } } + } }`; + const own = revisionId(note.revisionId); const variables = { - announce: globalId("Resource", announce.resourceId), - announceRevision: revisionId(announce.revisionId), - undo: globalId("Resource", undo.resourceId), - undoRevision: revisionId(undo.revisionId), + note: globalId("Resource", note.resourceId), + revision: own, + sourced: globalId("Resource", sourced.resourceId), + pasted: globalId("Resource", pasted.resourceId), }; - const open = { + const copy = async (resourceId: Uuid, source: unknown) => ({ + currentRevision: { + document: (await head(db, resourceId)).document, + root: { + relations: [{ node: { document: note.embedded, source } }], + }, + }, + }); + const closed = { data: { - announcement: { - currentRevision: { id: variables.announceRevision }, - revisions: { - edges: [{ node: { id: variables.announceRevision } }], - }, + note: { + currentRevision: null, + revision: null, + revisions: { edges: [], pageInfo: { hasNextPage: false } }, }, - announceRevision: { id: variables.announceRevision }, - undoing: { currentRevision: { id: variables.undoRevision } }, - undoRevisions: [{ id: variables.undoRevision }], + revision: null, + revisions: [null], + sourced: await copy(sourced.resourceId, null), + pasted: await copy(pasted.resourceId, null), }, }; - const closed = { + const open = { data: { - announcement: { currentRevision: null, revisions: { edges: [] } }, - announceRevision: null, - undoing: { currentRevision: null }, - undoRevisions: [null], + note: { + currentRevision: { id: own }, + revision: { id: own }, + revisions: { + edges: [{ node: { id: own } }], + pageInfo: { hasNextPage: false }, + }, + }, + revision: { sequence: 1 }, + revisions: [{ id: own }], + sourced: await copy(sourced.resourceId, { + relation: "snapshot", + status: "current", + revision: { id: own }, + }), + pasted: await copy(pasted.resourceId, null), }, }; - const outsider = await seedViewer(db, false); - const admin = await seedViewer(db, true); - for (const init of [undefined, outsider]) { + // Neither a member of A, nor of no workspace, nor anyone anonymous may + // read the revision, even by its ID alone; the local documents that + // embed it stay whole, and the one that recorded it as its source + // reads as the pasted one, but for its IRI. + for (const init of [undefined, auth, outsider.auth]) { const response = await harness.post({ query: read, variables }, init); - assert.deepEqual(await response.json(), closed); + const text = await response.text(); + assert.ok(!text.includes(own)); + const body = JSON.parse(text); + assert.deepEqual(body, closed); + assert.deepEqual( + withoutIri(body.data.sourced, sourced.iri), + withoutIri(body.data.pasted, pasted.iri), + ); } - for (const init of [auth, admin]) { + for (const init of [memberB.auth, admin.auth]) { assert.deepEqual(await query(read, variables, init), open); } }); }); +}); + +describe("Access to revisions by their own evidence", () => { + it("opens no earlier private revision by a later public one, nor tells of it by paging", async () => { + await withWriter(async ({ harness, query }) => { + const { db } = harness; + const workspaceB = await seedWorkspace(db); + const memberB = await seedViewer(db, { memberOf: workspaceB }); + const iri = `https://remote.example/notes/${uuidV7()}`; + await receive(db, iri, [PUBLIC_IRI], "public at first"); + const hidden = await receive(db, iri, [CAROL], "private"); + await receipt(db, hidden.revisionId, workspaceB); + await receive(db, iri, [PUBLIC_IRI], "public again"); + const read = `query($id: ID!, $first: Int, $after: String) { + node(id: $id) { ... on Resource { + currentRevision { sequence } + revision(sequence: 2) { sequence } + revisions(first: $first, after: $after) { + edges { cursor node { sequence } } + pageInfo { hasNextPage } + } + } } + }`; + const id = globalId("Resource", hidden.resourceId); + const page = async ( + init: RequestInit | undefined, + first: number, + after?: string, + ) => { + const body = await query(read, { id, first, after }, init); + assert.equal(body.errors, undefined); + assert.ok(body.data != null); + const { currentRevision, revision, revisions } = body.data.node; + return { + currentRevision, + revision, + sequences: revisions.edges.map( + ({ node }: { node: { sequence: number } }) => node.sequence, + ), + cursor: revisions.edges.at(-1)?.cursor as string | undefined, + hasNextPage: revisions.pageInfo.hasNextPage, + }; + }; + const both = await page(undefined, 2); + assert.deepEqual( + { ...both, cursor: undefined }, + { + currentRevision: { sequence: 3 }, + revision: null, + sequences: [3, 1], + cursor: undefined, + hasNextPage: false, + }, + ); + // Pages of one revision skip the private one as if it did not exist. + const first = await page(undefined, 1); + assert.deepEqual([first.sequences, first.hasNextPage], [[3], true]); + const second = await page(undefined, 1, first.cursor); + assert.deepEqual([second.sequences, second.hasNextPage], [[1], false]); + const forB = await page(memberB.auth, 2); + assert.deepEqual( + [forB.revision, forB.sequences, forB.hasNextPage], + [{ sequence: 2 }, [3, 2], true], + ); + }); + }); it("keeps an earlier public revision readable after a private one", async () => { await withWriter(async ({ harness, query }) => { @@ -1119,8 +1283,8 @@ describe("Access to revisions by their embeddings", () => { like: sourceOf(null), }, }); - const admin = await seedViewer(db, true); - const body = await query(read, variables, admin); + const admin = await seedViewer(db, { admin: true }); + const body = await query(read, variables, admin.auth); assert.equal(body.data?.node.revisions.edges.length, 2); assert.deepEqual(body.data?.like, sourceOf("superseded")); }); diff --git a/packages/graphql/src/revision.ts b/packages/graphql/src/revision.ts index 66573b25..50a87ba0 100644 --- a/packages/graphql/src/revision.ts +++ b/packages/graphql/src/revision.ts @@ -185,10 +185,14 @@ const DocumentSourceStatus = builder.enumType("DocumentSourceStatus", { }, }); -/** An embedding of a revision, with the source it names. */ +type SourceStatus = "current" | "superseded" | "deleted"; + +/** A recorded embedding whose source revision the viewer may read. */ interface Source { readonly relation: RevisionEmbedding["relation"]; readonly revision: ResourceRevisionRow; + /** Null when the viewer may not read the resource's current revision. */ + readonly status: SourceStatus | null; } const DocumentSource = builder.objectRef("DocumentSource"); @@ -237,36 +241,111 @@ function registeredResource( // The revision each interpreted node belongs to. const nodeRevisions = new WeakMap(); -const embeddingLookups = new WeakMap< +const sourceLookups = new WeakMap< UserContext, - Map>> + Map>> >(); /** - * Loads the recorded embeddings of a revision by their paths, once per + * Tells where a source revision stands against its resource's current + * revision. An `unavailable` current revision, a legacy typed row without a + * retained document, is a later revision like any other. + * @param revision The source revision. + * @param current The current revision of its resource, when the viewer may + * read it. + * @returns The status, or null without a readable current revision. + */ +const statusOf = ( + revision: ResourceRevisionRow, + current: Pick | undefined, +): SourceStatus | null => + current == null + ? null + : current.id === revision.id + ? "current" + : current.kind === "whiteout" + ? "deleted" + : "superseded"; + +/** + * Loads the recorded sources of a revision's embedded documents that the + * viewer may read, with where each stands, in two queries per revision + * whatever the number of documents it embeds. Lookups are shared within a * request. - * @returns The embeddings, keyed by the JSON of their paths. + * @returns The sources, keyed by the JSON of the embedded documents' paths. */ -function embeddingsOf( +function sourcesOf( ctx: UserContext, revisionId: Uuid, -): Promise> { - let lookups = embeddingLookups.get(ctx); +): Promise> { + let lookups = sourceLookups.get(ctx); if (lookups == null) { lookups = new Map(); - embeddingLookups.set(ctx, lookups); + sourceLookups.set(ctx, lookups); } let lookup = lookups.get(revisionId); if (lookup == null) { - lookup = (async () => - new Map( - ( - await ctx.db - .select() - .from(schema.revisionEmbeddings) - .where(eq(schema.revisionEmbeddings.revisionId, revisionId)) - ).map((row) => [JSON.stringify(row.path), row]), - ))(); + lookup = (async () => { + const embeddings = await ctx.db + .select({ + path: schema.revisionEmbeddings.path, + relation: schema.revisionEmbeddings.relation, + revision: schema.resourceRevisions, + }) + .from(schema.revisionEmbeddings) + .innerJoin( + schema.resourceRevisions, + eq( + schema.resourceRevisions.id, + schema.revisionEmbeddings.sourceRevisionId, + ), + ) + .where( + and( + eq(schema.revisionEmbeddings.revisionId, revisionId), + readableRevision(ctx, schema.resourceRevisions.id), + ), + ); + const resourceIds = [ + ...new Set(embeddings.map(({ revision }) => revision.resourceId)), + ]; + const heads = + resourceIds.length === 0 + ? [] + : await ctx.db + .select({ + resourceId: schema.resourceHeads.resourceId, + id: schema.resourceRevisions.id, + kind: schema.resourceRevisions.kind, + }) + .from(schema.resourceHeads) + .innerJoin( + schema.resourceRevisions, + eq( + schema.resourceRevisions.id, + schema.resourceHeads.revisionId, + ), + ) + .where( + and( + inArray(schema.resourceHeads.resourceId, resourceIds), + readableRevision(ctx, schema.resourceRevisions.id), + ), + ); + const current = new Map( + heads.map((head) => [head.resourceId, head] as const), + ); + return new Map( + embeddings.map(({ path, relation, revision }) => [ + JSON.stringify(path), + { + relation, + revision, + status: statusOf(revision, current.get(revision.resourceId)), + }, + ]), + ); + })(); lookups.set(revisionId, lookup); } return lookup; @@ -274,9 +353,11 @@ function embeddingsOf( /** * Finds the recorded source of an embedded document, when the viewer may - * read the source revision. + * read the source revision. Whatever it finds, the document itself reads + * as the revision embedding it does. * @returns The source, or null for the root, for a document whose source is - * unknown, and for a source the viewer may not read. + * unknown, and for a source the viewer may not read, which are not + * told apart. */ async function sourceOf( ctx: UserContext, @@ -284,50 +365,9 @@ async function sourceOf( ): Promise { const revisionId = nodeRevisions.get(node); if (revisionId == null || node.path.length === 0) return null; - const embedding = (await embeddingsOf(ctx, revisionId)).get( - JSON.stringify(node.path), + return ( + (await sourcesOf(ctx, revisionId)).get(JSON.stringify(node.path)) ?? null ); - if (embedding == null) return null; - const revision = await ctx.db.query.resourceRevisions.findFirst({ - where: { - id: embedding.sourceRevisionId, - RAW: (table) => readableRevision(ctx, table.id), - }, - }); - return revision == null ? null : { relation: embedding.relation, revision }; -} - -/** - * Tells where a source revision stands against its resource's current - * revision. An `unavailable` current revision, a legacy typed row without a - * retained document, is a later revision like any other. - * @returns The status, or null when the viewer may not read the current - * revision. - */ -async function statusOf( - ctx: UserContext, - revision: ResourceRevisionRow, -): Promise<"current" | "superseded" | "deleted" | null> { - const [current] = await ctx.db - .select({ - id: schema.resourceRevisions.id, - kind: schema.resourceRevisions.kind, - }) - .from(schema.resourceHeads) - .innerJoin( - schema.resourceRevisions, - eq(schema.resourceRevisions.id, schema.resourceHeads.revisionId), - ) - .where( - and( - eq(schema.resourceHeads.resourceId, revision.resourceId), - readableRevision(ctx, schema.resourceRevisions.id), - ), - ) - .limit(1); - if (current == null) return null; - if (current.id === revision.id) return "current"; - return current.kind === "whiteout" ? "deleted" : "superseded"; } const occurrenceFields = { @@ -487,7 +527,9 @@ DocumentNode.implement({ "the document embedding it was saved. Null for the root, for an " + "embedded document whose source is unknown, such as one saved " + "before sources were recorded or pasted without one, and when the " + - "viewer may not read the source revision.", + "viewer may not read the source revision, which are not told " + + "apart. It hides nothing else: the document reads as the revision " + + "embedding it does, whatever its source.", resolve: (node, _, ctx) => sourceOf(ctx, node), }), }), @@ -495,8 +537,8 @@ DocumentNode.implement({ DocumentSource.implement({ description: - "The revision an embedded document came from. The viewer may read it, " + - "since a revision is readable only to those who may read its sources.", + "The revision an embedded document came from, which the viewer may " + + "read.", fields: (t) => ({ relation: t.expose("relation", { type: DocumentSourceRelation }), revision: t.field({ @@ -511,7 +553,7 @@ DocumentSource.implement({ "Whether the source revision is still current, or a later revision " + "or a deletion followed it; null when the viewer may not read the " + "resource's current revision.", - resolve: (source, _, ctx) => statusOf(ctx, source.revision), + resolve: (source) => source.status, }), }), }); @@ -562,9 +604,8 @@ const ResourceRevisionRef = builder.drizzleNode("resourceRevisions", { "to the public by anyone; one a receipt links to a delivery to a local " + "instance the viewer is a member of by its members; and the current " + "revision of a resource with a legacy typed row as `Activity` and " + - "`Object` tell. A revision whose embedded documents came from other " + - "revisions is readable only by those who may read every one of them, " + - "and theirs in turn. Administrators read every revision. A later " + + "`Object` tell. Where its embedded documents came from never hides " + + "it. Administrators read every revision. A later " + "restriction or deletion of the resource hides no earlier revision. A " + "revision the viewer may not read is left out as if it did not exist.", // A node lookup checks the revision by its own ID. @@ -666,6 +707,26 @@ builder.drizzleObjectField("resources", "currentRevision", (t) => }), ); +builder.drizzleObjectField("resources", "revision", (t) => + t.field({ + type: ResourceRevisionRef, + nullable: true, + args: { sequence: t.arg.int({ required: true }) }, + description: + "The revision with the given sequence; null when there is none, or " + + "when the viewer may not read it, which are not told apart.", + select: { columns: { id: true } }, + resolve: async (resource, { sequence }, ctx) => + (await ctx.db.query.resourceRevisions.findFirst({ + where: { + resourceId: resource.id, + sequence, + RAW: (table) => readableRevision(ctx, table.id), + }, + })) ?? null, + }), +); + builder.drizzleObjectField("resources", "revisions", (t) => t.relatedConnection( "revisions", From 076382046871d3d4dbd99c556f47ff0f66bef12c Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Sun, 15 Nov 2026 20:58:43 +0900 Subject: [PATCH 05/10] Check declared sources and never guess them A local write may now declare as the source of an embedded document only a revision its member may read. previewLocalWrite() and commitLocalWrite() take an unreadableRevisions option that tells which declared revisions the member may not read; the preview checks them, and the commit checks them again, since access may change in between. A request that declares sources without the option is invalid. @drfed/federation cannot depend on @drfed/graphql, so the caller passes the check, such as unreadableRevisions() of the new @drfed/graphql/readable subpath. Every failure of a declared revision, whether it does not exist, is no snapshot, belongs to another resource, or may not be read, is the same new source_unavailable error with the declared paths as diagnostics, so that a refusal tells nothing of revisions the member may not read. Pasting the same contents without a source is still accepted. The source of an undeclared embedded document is no longer guessed from the current snapshot of the resource under its id, which recorded sources the member was never checked against. Sources now come only from resources saved in the same write and from declared revisions. When a document keeps a revision saved in the same write, it also takes the sources recorded for that revision, so that an Update records those of the version it carries. The seed cases that relied on the guess declare their sources. https://github.com/fedify-dev/drfed/issues/154 https://github.com/fedify-dev/drfed/issues/154#issuecomment-6850587268 AI assistance: the maintainer asked Claude Code to complete the GraphQL chapters of the issue's plan, following the review comment above, which asks to check received material where it is imported. Claude Code designed the injected check and the uniform error, removed the guessed sources, and wrote the inheritance, the tests, the seed changes, and the documentation and changelog. The maintainer reviewed the result against the comment point by point. The build, checks, and test suite were run with PGlite; the PostgreSQL variants were skipped. Assisted-by: Claude Code:claude-opus-5-5 --- CHANGES.md | 6 +- CONTRIBUTING.md | 4 +- changes.d/javascript/embedded-sources.md | 6 +- docs/internals/local-writes.md | 58 +++-- docs/internals/resource-revisions.md | 8 +- packages/federation/README.md | 7 +- .../src/local-write-embedding.test.ts | 212 +++++++++++++++--- packages/federation/src/local-write.ts | 1 + .../federation/src/local-write/embedding.ts | 186 +++++++-------- .../federation/src/local-write/operation.ts | 63 +++++- packages/federation/src/local-write/types.ts | 31 ++- packages/graphql/README.md | 6 + packages/graphql/package.json | 5 + packages/graphql/src/revision.test.ts | 189 +++++++++++++++- packages/models/src/document.ts | 1 + scripts/seed-revisions/cases-access.mts | 7 + scripts/seed-revisions/cases-sources.mts | 36 ++- scripts/seed-revisions/writer.mts | 16 +- 18 files changed, 655 insertions(+), 187 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0eab9c67..22b9f588 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -149,7 +149,11 @@ To be released. revision's contents or was derived from it. `commitLocalWrite()` in `@drfed/federation/local-write` records them for every document it saves, and `create` and `edit` requests accept `sources` to declare the revision - an embedded document was loaded from. [[#154]] + an embedded document was loaded from. Declaring sources requires the + `unreadableRevisions` option of `previewLocalWrite()` and + `commitLocalWrite()`, such as `unreadableRevisions()` of the new + `@drfed/graphql/readable`; a source that is missing or that the member + may not read fails alike with `source_unavailable`. [[#154]] [#151]: https://github.com/fedify-dev/drfed/issues/151 [#152]: https://github.com/fedify-dev/drfed/issues/152 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 27c8939f..69fb5783 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -719,7 +719,9 @@ The GraphQL types for resource revisions live in *src/revision.ts*. Each revision is read by evidence of its own, through `readableRevision()` in *src/readable.ts*, never by the current state of its resource nor by where its embedded documents came from; only `DocumentNode.source` checks a source -revision. Filter revisions by it before paging. +revision. Filter revisions by it before paging, and use +`unreadableRevisions()` wherever another layer, such as a local write's +`sources`, must apply the same rule. CLI and server changes diff --git a/changes.d/javascript/embedded-sources.md b/changes.d/javascript/embedded-sources.md index b2f64944..8bf22567 100644 --- a/changes.d/javascript/embedded-sources.md +++ b/changes.d/javascript/embedded-sources.md @@ -8,4 +8,8 @@ links: revision's contents or was derived from it. `commitLocalWrite()` in `@drfed/federation/local-write` records them for every document it saves, and `create` and `edit` requests accept `sources` to declare the revision - an embedded document was loaded from. [[#154]] + an embedded document was loaded from. Declaring sources requires the + `unreadableRevisions` option of `previewLocalWrite()` and + `commitLocalWrite()`, such as `unreadableRevisions()` of the new + `@drfed/graphql/readable`; a source that is missing or that the member + may not read fails alike with `source_unavailable`. [[#154]] diff --git a/docs/internals/local-writes.md b/docs/internals/local-writes.md index cd9db414..ecba5eed 100644 --- a/docs/internals/local-writes.md +++ b/docs/internals/local-writes.md @@ -82,16 +82,17 @@ after the first write throw out of the transaction; nothing partial is left. A replayed token finds its resources already saved (`resource_conflict`) or the object already changed (`revision_conflict`). -| Error | Meaning | -| ----------------------- | -------------------------------------------------------------------------------------------- | -| `invalid_request` | Malformed request or resource descriptors, or a missing token or reservation. | -| `invalid_document` | Validator, authority or server-owned-field diagnostics at submitted paths. | -| `actor_not_found` | The actor is missing, deleted, not local, on an expired instance, or not the member's. | -| `invalid_instance_host` | The stored instance host cannot be parsed by this server. | -| `stale_preview` | The token is invalid, expired, or for another account or request. | -| `revision_conflict` | The object's current revision is not the expected one. | -| `resource_conflict` | The resources were already saved, or an IRI is another kind of resource. | -| `unsupported_edit` | The object is deleted, not the actor's, changes type, or cannot be kept in step (see below). | +| Error | Meaning | +| ----------------------- | --------------------------------------------------------------------------------------------- | +| `invalid_request` | Malformed request or resource descriptors, or a missing token or reservation. | +| `invalid_document` | Validator, authority or server-owned-field diagnostics at submitted paths. | +| `actor_not_found` | The actor is missing, deleted, not local, on an expired instance, or not the member's. | +| `invalid_instance_host` | The stored instance host cannot be parsed by this server. | +| `stale_preview` | The token is invalid, expired, or for another account or request. | +| `revision_conflict` | The object's current revision is not the expected one. | +| `resource_conflict` | The resources were already saved, or an IRI is another kind of resource. | +| `unsupported_edit` | The object is deleted, not the actor's, changes type, or cannot be kept in step (see below). | +| `source_unavailable` | A declared source is missing, not a snapshot of its document, or one the member may not read. | Identity and documents @@ -153,7 +154,10 @@ describe. `Link` values and anonymous documents get no source. The source is found in this order: 1. A resource saved earlier in the same write, such as a nested new resource - kept embedded or the version an edit's `Update` embeds. + kept embedded or the version an edit's `Update` embeds. When the + embedded document keeps that resource's new revision, the documents it + embeds take the sources recorded for that revision at their own paths, + so an `Update` records the sources of the version it carries. 2. A source the request declares for the embedded document's submitted path: @@ -170,12 +174,34 @@ found in this order: An editor declares the revision it loaded a document from, so that a changed copy keeps its source. Both `create` and `edit` accept `sources`, and the preview token binds them. Each path must name an embedded document - with an `id` that is not a new resource of the write, and its revision - must be a snapshot of the resource registered under that `id`; otherwise - the write is refused. + with an `id` that is not a new resource of the write; otherwise the + request is `invalid_request`. Its revision must be a snapshot of the + resource registered under that `id` that the member may read; otherwise + the write fails with `source_unavailable`, with a diagnostic at the + declared path. A missing revision and one the member may not read fail + alike, so the error tells nothing of revisions the member may not read. + + The local write operations do not decide who may read a revision. The + caller passes `unreadableRevisions(ids)` in the options of both + `previewLocalWrite()` and `commitLocalWrite()`, which check the declared + revisions again, since the member's access may change after the + preview. GraphQL's rule is `unreadableRevisions(viewer, ids)` in + `@drfed/graphql/readable`: -3. The current revision of the resource registered under the `id`, only - when the embedded document keeps its contents unchanged. + ~~~~ ts + const access = { + unreadableRevisions: (ids: readonly Uuid[]) => + unreadableRevisions({ db, account }, ids), + }; + await previewLocalWrite(env, principal, request, access); + ~~~~ + + A request that declares sources without the check is `invalid_request`. + +Any other embedded document has an unknown source, even when it equals a +stored revision of the resource under its `id`: the server never guesses a +source from an IRI. A pasted document and a loaded one declared as its +source therefore differ only in `DocumentNode.source`. An embedded document is a `snapshot` of its source when its effective context equals the source document's and its JSON, apart from the `@context` key, diff --git a/docs/internals/resource-revisions.md b/docs/internals/resource-revisions.md index ec58a073..1a759eb1 100644 --- a/docs/internals/resource-revisions.md +++ b/docs/internals/resource-revisions.md @@ -302,8 +302,12 @@ anyone, as every local revision is, whether it records that `Note`'s revision as its source or was pasted without one: recording a source never makes a document harder to read. Only following the source checks the source revision, as `DocumentNode.source` does below. Received content stays -protected where it is read: the received revision itself is readable only by -the evidence above. +protected where it is read or imported: the received revision itself is +readable only by the evidence above, and a local write may declare as a +source only a revision its member may read, as +[local writes](local-writes.md#embedded-document-sources) describe. +`unreadableRevisions(viewer, ids)` in `@drfed/graphql/readable` applies the +same rule to a set of revisions for that check. Deletion hides no revision by itself: deleting a resource appends a whiteout, and its earlier revisions, like those of a resource whose author is deleted, diff --git a/packages/federation/README.md b/packages/federation/README.md index e0d66b4e..56bfaee3 100644 --- a/packages/federation/README.md +++ b/packages/federation/README.md @@ -65,8 +65,11 @@ alone, an activity referring to existing resources, or an activity with new nested resources, atomically, and actual edits or deletions of a current object with a generated `Update` or `Delete`. A preview shows every value the server adds and returns a token; the commit saves exactly those values after -checking permission again. Saving never delivers anything. See the -[local write internals] for the contract. +checking permission again. Saving never delivers anything. A request may +declare the revisions its embedded documents came from in `sources`; the +caller then passes `unreadableRevisions()`, such as the one of +`@drfed/graphql/readable`, so that only revisions the member may read are +accepted. See the [local write internals] for the contract. [local write internals]: https://drfed.org/internals/local-writes diff --git a/packages/federation/src/local-write-embedding.test.ts b/packages/federation/src/local-write-embedding.test.ts index d329cb7c..cdd62617 100644 --- a/packages/federation/src/local-write-embedding.test.ts +++ b/packages/federation/src/local-write-embedding.test.ts @@ -26,6 +26,7 @@ import { type JsonObject, type LocalWriteEnvironment, type LocalWriteRequest, + type PreviewOptions, commitLocalWrite, previewLocalWrite, } from "@drfed/federation/local-write"; @@ -109,10 +110,25 @@ const activity = ( const reserve: NonNullable = () => Promise.resolve(); +/** Lets the principal read every revision. */ +const READ_ALL: PreviewOptions = { + unreadableRevisions: () => Promise.resolve(new Set()), +}; + +/** + * Lets the principal read every revision but the given ones. + * @returns The options that check declared sources so. + */ +const readAllBut = (...hidden: Uuid[]): PreviewOptions => ({ + unreadableRevisions: (ids) => + Promise.resolve(new Set(ids.filter((id) => hidden.includes(id)))), +}); + async function write(env: LocalWriteEnvironment, request: LocalWriteRequest) { - const preview = await previewLocalWrite(env, PRINCIPAL, request); + const preview = await previewLocalWrite(env, PRINCIPAL, request, READ_ALL); assert.ok(preview.ok, JSON.stringify(!preview.ok && preview.error)); const outcome = await commitLocalWrite(env, PRINCIPAL, request, { + ...READ_ALL, previewToken: preview.preview.token, ...(request.operation === "create" && request.publish !== true ? {} @@ -263,7 +279,7 @@ describe("embedded document sources", () => { }); }); - it("records declared sources of an edited version, not of its Update", async () => { + it("records declared sources of an edited version, and in its Update", async () => { await withFederation(async (harness) => { await seedMember(harness.db); const env = await environment(harness); @@ -292,8 +308,14 @@ describe("embedded document sources", () => { relation: "snapshot", }, ]); - // The past version the Update carries has no current match. + // The Update keeps the version, so it records the version's sources + // at its own paths. assert.deepEqual(await embeddings(harness.db, update.revisionId), [ + { + path: ["object", "location"], + sourceRevisionId: first.id, + relation: "snapshot", + }, { path: ["object"], sourceRevisionId: version.revisionId, @@ -334,26 +356,69 @@ describe("embedded document sources", () => { }); }); - it("matches an undeclared document only to the current snapshot it keeps", async () => { + it("records the sources of nested documents at every depth", async () => { await withFederation(async (harness) => { await seedMember(harness.db); const env = await environment(harness); - const { first, current } = await savedNote(env, harness.db); - for (const [object, expected] of [ - [ - withoutContext(current.document), - [ + const { first } = await savedNote(env, harness.db); + const [note, root] = ( + await write( + env, + create( { - path: ["object"], - sourceRevisionId: current.id, - relation: "snapshot", + "@context": AS, + type: "Create", + to: [PUBLIC_IRI], + object: { + type: "Note", + content: "

Nested

", + to: [PUBLIC_IRI], + location: withoutContext(first.document), + }, }, - ], - ], - // The past version and a changed copy have no known source. - [withoutContext(first.document), []], - [{ ...withoutContext(current.document), content: "

X

" }, []], - ] as const) { + [ + { path: [], kind: "activity" }, + { path: ["object"], kind: "object", representation: "embedded" }, + ], + [{ path: ["object", "location"], revisionId: first.id }], + ), + ) + ).resources; + assert.ok(note != null && root != null); + assert.deepEqual(await embeddings(harness.db, note.revisionId), [ + { + path: ["location"], + sourceRevisionId: first.id, + relation: "snapshot", + }, + ]); + assert.deepEqual(await embeddings(harness.db, root.revisionId), [ + { + path: ["object", "location"], + sourceRevisionId: first.id, + relation: "snapshot", + }, + { + path: ["object"], + sourceRevisionId: note.revisionId, + relation: "snapshot", + }, + ]); + }); + }); + + it("never guesses the source of an undeclared document", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first, current } = await savedNote(env, harness.db); + // Not even a copy of the current snapshot, which a pasted document + // may equal by chance. + for (const object of [ + withoutContext(current.document), + withoutContext(first.document), + { ...withoutContext(current.document), content: "

X

" }, + ]) { const [like] = ( await write( env, @@ -366,10 +431,7 @@ describe("embedded document sources", () => { ) ).resources; assert.ok(like != null); - assert.deepEqual( - await embeddings(harness.db, like.revisionId), - expected, - ); + assert.deepEqual(await embeddings(harness.db, like.revisionId), []); } }); }); @@ -439,16 +501,6 @@ describe("embedded document sources", () => { { path: ["object"], revisionId: first.id }, ]), ], - [ - "another resource's revision", - activity(like, [{ path: ["object"], revisionId: otherHead.id }]), - ], - [ - "missing revision", - activity(like, [ - { path: ["object"], revisionId: MISSING_REVISION_ID }, - ]), - ], [ "no id", activity( @@ -495,10 +547,101 @@ describe("embedded document sources", () => { ], ]; for (const [label, request] of cases) { - const preview = await previewLocalWrite(env, PRINCIPAL, request); + const preview = await previewLocalWrite( + env, + PRINCIPAL, + request, + READ_ALL, + ); assert.ok(!preview.ok, label); assert.equal(preview.error.type, "invalid_request", label); } + // Declaring sources needs a check of what the principal may read. + const declared = activity(like, [ + { path: ["object"], revisionId: first.id }, + ]); + const unchecked = await previewLocalWrite(env, PRINCIPAL, declared); + assert.ok(!unchecked.ok); + assert.equal(unchecked.error.type, "invalid_request"); + }); + }); + + it("refuses unavailable sources alike, whatever makes them so", async () => { + await withFederation(async (harness) => { + await seedMember(harness.db); + const env = await environment(harness); + const { first } = await savedNote(env, harness.db); + const [other] = (await write(env, create(NOTE))).resources; + assert.ok(other != null); + const otherHead = await head(harness.db, other.id); + await write(env, { + operation: "delete", + actorId: localActorId, + objectId: other.id, + expectedRevisionId: otherHead.id, + }); + const whiteout = await loadCurrentResourceRevision(harness.db, other.id); + assert.ok(whiteout?.kind === "whiteout"); + const like = (revisionId: Uuid) => + activity( + { + "@context": AS, + type: "Like", + object: withoutContext(first.document), + to: [PUBLIC_IRI], + }, + [{ path: ["object"], revisionId }], + ); + const cases: [string, Uuid, PreviewOptions][] = [ + ["missing", MISSING_REVISION_ID, READ_ALL], + ["unreadable", first.id, readAllBut(first.id)], + ["another resource's", otherHead.id, READ_ALL], + ["a whiteout", whiteout.id, READ_ALL], + ]; + const errors = []; + for (const [label, revisionId, options] of cases) { + const preview = await previewLocalWrite( + env, + PRINCIPAL, + like(revisionId), + options, + ); + assert.ok(!preview.ok, label); + errors.push(preview.error); + } + // Nothing tells a revision the principal may not read from one that + // does not exist. + for (const error of errors) { + assert.deepEqual(error, { + type: "source_unavailable", + message: errors[0]!.message, + diagnostics: [ + { + reason: "source_unavailable", + category: "authority", + severity: "error", + path: ["object"], + message: errors[0]!.diagnostics[0]!.message, + }, + ], + }); + } + // The commit checks again, since access may change after the preview. + const preview = await previewLocalWrite( + env, + PRINCIPAL, + like(first.id), + READ_ALL, + ); + assert.ok(preview.ok); + const before = await harness.db.$count(schema.resourceRevisions); + const outcome = await commitLocalWrite(env, PRINCIPAL, like(first.id), { + ...readAllBut(first.id), + previewToken: preview.preview.token, + }); + assert.ok(!outcome.ok); + assert.deepEqual(outcome.error, errors[0]); + assert.equal(await harness.db.$count(schema.resourceRevisions), before); }); }); @@ -517,6 +660,7 @@ describe("embedded document sources", () => { env, PRINCIPAL, activity(like, [{ path: ["object"], revisionId: first.id }]), + READ_ALL, ); assert.ok(preview.ok); for (const sources of [ @@ -527,7 +671,7 @@ describe("embedded document sources", () => { env, PRINCIPAL, activity(like, sources), - { previewToken: preview.preview.token }, + { ...READ_ALL, previewToken: preview.preview.token }, ); assert.ok(!outcome.ok); assert.equal(outcome.error.type, "stale_preview"); diff --git a/packages/federation/src/local-write.ts b/packages/federation/src/local-write.ts index ea8b23c6..6e56898c 100644 --- a/packages/federation/src/local-write.ts +++ b/packages/federation/src/local-write.ts @@ -50,6 +50,7 @@ export type { LocalWriteResult, NewResource, PreparedResource, + PreviewOptions, PreviewOutcome, SavedResource, WritePrincipal, diff --git a/packages/federation/src/local-write/embedding.ts b/packages/federation/src/local-write/embedding.ts index ebfe90e0..6dd81358 100644 --- a/packages/federation/src/local-write/embedding.ts +++ b/packages/federation/src/local-write/embedding.ts @@ -15,10 +15,11 @@ // along with this program. If not, see . import { type Database, type Transaction, schema } from "@drfed/models"; -import type { - DocumentNode, - FieldPath, - JsonValue, +import { + DIAGNOSTIC_REASONS, + type DocumentNode, + type FieldPath, + type JsonValue, } from "@drfed/models/document"; import type { RevisionEmbeddingInput } from "@drfed/models/resource-revision"; import type { Uuid } from "@drfed/models/uuid"; @@ -52,16 +53,26 @@ export interface SourceSnapshot { readonly document: JsonValue; } +/** A snapshot this write saved, with the sources recorded for it. */ +export interface SavedSnapshot extends SourceSnapshot { + readonly embeddings: readonly RevisionEmbeddingInput[]; +} + /** * Loads the revisions that requests name as sources, with the IRIs of their * resources. - * @returns The revisions by their lowercase IDs; unknown IDs are absent. + * @param hidden The lowercase IDs of revisions the principal may not read, + * which are left out as if they did not exist. + * @returns The revisions by their lowercase IDs; unknown and hidden IDs are + * absent. */ export async function loadSourceRevisions( db: Database | Transaction, ids: readonly Uuid[], + hidden: ReadonlySet = new Set(), ): Promise> { - if (ids.length === 0) return new Map(); + const shown = ids.filter((id) => !hidden.has(id.toLowerCase())); + if (shown.length === 0) return new Map(); const rows = await db .select({ id: schema.resourceRevisions.id, @@ -73,7 +84,7 @@ export async function loadSourceRevisions( schema.resources, eq(schema.resources.id, schema.resourceRevisions.resourceId), ) - .where(inArray(schema.resourceRevisions.id, [...new Set(ids)])); + .where(inArray(schema.resourceRevisions.id, [...new Set(shown)])); return new Map( rows.map(({ id, kind, iri }) => [id.toLowerCase(), { iri, kind }]), ); @@ -83,11 +94,15 @@ export async function loadSourceRevisions( * Checks the sources a request declares against the submitted document: * each names, once, an embedded document that is not a `Link`, is not a new * resource of the write, and has an `id`, and a stored snapshot of the - * resource registered under that `id`. + * resource registered under that `id` that the principal may read. Every + * failure of the named revision, whether it does not exist, is no snapshot, + * belongs to another resource, or may not be read, is one and the same + * `source_unavailable`, so that it tells nothing of revisions the principal + * may not read. * @param sources The declared sources. * @param nodes The documents the submitted document describes. * @param newPaths The keys of the paths of the write's new resources. - * @param revisions Looks up the declared revisions. + * @param revisions Looks up the declared revisions the principal may read. * @returns Why a declaration is invalid, or null. */ export async function checkSources( @@ -102,7 +117,7 @@ export async function checkSources( const invalid = (message: string) => writeError("invalid_request", message); const byPath = new Map(nodes.map((node) => [pathKey(node.path), node])); const seen = new Set(); - const named: { key: string; iri: string; revisionId: Uuid }[] = []; + const named: { path: FieldPath; iri: string; revisionId: Uuid }[] = []; for (const { path, revisionId } of sources) { const key = pathKey(path); if (seen.has(key)) return invalid(`The source of ${key} is listed twice.`); @@ -116,16 +131,26 @@ export async function checkSources( } const iri = node.identifiers.find(({ property }) => property === "id")?.iri; if (iri == null) return invalid(`${key} has no id to name its source.`); - named.push({ key, iri, revisionId }); + named.push({ path, iri, revisionId }); } const found = await revisions(named.map(({ revisionId }) => revisionId)); - for (const { key, iri, revisionId } of named) { + const unavailable = named.filter(({ iri, revisionId }) => { const revision = found.get(revisionId.toLowerCase()); - if (revision?.kind !== "snapshot" || revision.iri !== iri) { - return invalid(`The source of ${key} is not a saved version of ${iri}.`); - } - } - return null; + return revision?.kind !== "snapshot" || revision.iri !== iri; + }); + return unavailable.length === 0 + ? null + : writeError( + "source_unavailable", + "A declared source is not a saved version of its document that " + + "can be read.", + unavailable.map(({ path }) => ({ + reason: "source_unavailable", + ...DIAGNOSTIC_REASONS.source_unavailable, + path, + message: "The source is not a saved version that can be read.", + })), + ); } /** @@ -197,51 +222,6 @@ export function embeddingRelation( : "derived"; } -/** - * Reads the current snapshots of the resources registered under IRIs. - * @returns The snapshots by IRI; resources whose current revision is not a - * snapshot, and unregistered IRIs, are absent. - */ -async function currentSnapshots( - tx: Transaction, - iris: readonly string[], -): Promise> { - if (iris.length === 0) return new Map(); - const rows = await tx - .select({ - iri: schema.resources.iri, - revisionId: schema.resourceRevisions.id, - document: schema.resourceRevisions.document, - }) - .from(schema.resources) - .innerJoin( - schema.resourceHeads, - eq(schema.resourceHeads.resourceId, schema.resources.id), - ) - .innerJoin( - schema.resourceRevisions, - and( - eq( - schema.resourceRevisions.resourceId, - schema.resourceHeads.resourceId, - ), - eq(schema.resourceRevisions.id, schema.resourceHeads.revisionId), - ), - ) - .where( - and( - inArray(schema.resources.iri, [...new Set(iris)]), - eq(schema.resourceRevisions.kind, "snapshot"), - ), - ); - return new Map( - rows.map(({ iri, revisionId, document }) => [ - iri, - { revisionId, document: document as JsonValue }, - ]), - ); -} - async function storedSnapshots( tx: Transaction, ids: readonly Uuid[], @@ -274,16 +254,18 @@ async function storedSnapshots( * depth. Each takes its source from, in order: * * 1. the revision this write saved for its IRI, as a new nested resource - * or an edited object; + * or an edited object; when the document keeps that revision, the + * documents it embeds take the sources recorded for that revision too, + * so that an `Update` records those of the version it carries; * 2. the revision the request declares for its submitted path, for a - * document the request submitted rather than one the server generated; - * 3. the current snapshot of the resource registered under its IRI, only - * when the embedded document keeps it. + * document the request submitted rather than one the server generated. * - * Any other has an unknown source and no row. + * Any other has an unknown source and no row, even when it equals a stored + * revision of the resource under its IRI: a source is never guessed. * @param tx The write's transaction. * @param resource The prepared resource about to be saved. - * @param declared Declared source revisions by the keys of submitted paths. + * @param declared Declared source revisions by the keys of submitted paths, + * already checked to be readable snapshots. * @param saved The snapshots this write has saved so far, by IRI. * @returns The embeddings to save with the resource's revision. */ @@ -291,7 +273,7 @@ export async function findEmbeddings( tx: Transaction, resource: PreparedResource, declared: ReadonlyMap, - saved: ReadonlyMap, + saved: ReadonlyMap, ): Promise { const nodes = interpretDocument(resource.document) ?? []; const nodePaths = new Set(nodes.map(({ path }) => pathKey(path))); @@ -303,49 +285,47 @@ export async function findEmbeddings( node.iri !== resource.iri, ); const declaredFor = (node: InterpretedNode): Uuid | undefined => - resource.generated + resource.generated || saved.has(node.iri ?? "") ? undefined : declared.get(pathKey([...resource.path, ...node.path])); - const [declaredSnapshots, currentByIri] = await Promise.all([ - storedSnapshots( - tx, - embedded.flatMap((node) => { - const id = saved.has(node.iri) ? undefined : declaredFor(node); - return id == null ? [] : [id]; - }), - ), - currentSnapshots( - tx, - embedded - .filter((node) => !saved.has(node.iri) && declaredFor(node) == null) - .map(({ iri }) => iri), - ), - ]); - const relation = (node: InterpretedNode, source: SourceSnapshot) => - embeddingRelation( + const declaredSnapshots = await storedSnapshots( + tx, + embedded.flatMap((node) => { + const id = declaredFor(node); + return id == null ? [] : [id]; + }), + ); + const direct = embedded.flatMap((node): RevisionEmbeddingInput[] => { + const declaredId = declaredFor(node); + const source = + saved.get(node.iri) ?? + (declaredId == null + ? undefined + : declaredSnapshots.get(declaredId.toLowerCase())); + if (source == null) return []; + const relation = embeddingRelation( resource.document, nodePaths, node.path, node.value, source.document, ); - return embedded.flatMap((node): RevisionEmbeddingInput[] => { - const own = saved.get(node.iri); - const declaredId = own == null ? declaredFor(node) : undefined; - const source = - own ?? - (declaredId == null - ? currentByIri.get(node.iri) - : declaredSnapshots.get(declaredId.toLowerCase())); - if (source == null) return []; - const found = relation(node, source); - // An undeclared document matched by IRI alone has a source only when - // it keeps the current snapshot. - if (own == null && declaredId == null && found !== "snapshot") return []; - return [ - { path: node.path, sourceRevisionId: source.revisionId, relation: found }, - ]; + return [{ path: node.path, sourceRevisionId: source.revisionId, relation }]; }); + const recorded = new Set(direct.map(({ path }) => pathKey(path))); + const inherited = direct.flatMap(({ path, sourceRevisionId, relation }) => + relation === "snapshot" + ? [...saved.values()] + .filter(({ revisionId }) => revisionId === sourceRevisionId) + .flatMap(({ embeddings }) => embeddings) + .map((embedding) => ({ + ...embedding, + path: [...path, ...embedding.path], + })) + .filter((embedding) => !recorded.has(pathKey(embedding.path))) + : [], + ); + return [...direct, ...inherited]; } /** diff --git a/packages/federation/src/local-write/operation.ts b/packages/federation/src/local-write/operation.ts index e193fc0a..61f90123 100644 --- a/packages/federation/src/local-write/operation.ts +++ b/packages/federation/src/local-write/operation.ts @@ -46,7 +46,7 @@ import { registeredIris, } from "./actor.ts"; import { - type SourceSnapshot, + type SavedSnapshot, declaredSources, findEmbeddings, loadSourceRevisions, @@ -84,6 +84,7 @@ import { type LocalWriteRequest, LocalWriteRollback, type PreparedResource, + type PreviewOptions, type PreviewOutcome, type SavedResource, type WritePrincipal, @@ -94,14 +95,40 @@ import { function lookups( db: Database | Transaction, actor: WritingActor, + hidden: ReadonlySet, ): IdentityLookups { return { localActors: (iris) => localActorIris(db, actor.instanceId, iris), registered: (iris) => registeredIris(db, iris), - revisions: (ids) => loadSourceRevisions(db, ids), + revisions: (ids) => loadSourceRevisions(db, ids, hidden), }; } +/** + * Asks which of the revisions a request declares as sources the principal + * may not read. It runs before the commit's transaction, since the check + * may read the database apart from it. + * @returns Their lowercase IDs, or why sources cannot be declared. + */ +async function hiddenSources( + request: LocalWriteRequest, + options: PreviewOptions | undefined, +): Promise | LocalWriteError> { + const ids = + request.operation === "delete" + ? [] + : (request.sources ?? []).map(({ revisionId }) => revisionId); + if (ids.length === 0) return new Set(); + if (typeof options?.unreadableRevisions !== "function") { + return writeError( + "invalid_request", + "Declaring sources requires a check of which revisions can be read.", + ); + } + const hidden = await options.unreadableRevisions(ids); + return new Set([...hidden].map((id) => id.toLowerCase())); +} + function checkRequest(request: LocalWriteRequest): LocalWriteError | null { if (request === null || typeof request !== "object") { return writeError("invalid_request", "Expected a write request."); @@ -149,6 +176,7 @@ async function prepare( actor: WritingActor, request: LocalWriteRequest, allocation: Allocation, + hidden: ReadonlySet, ): Promise { if (request.operation === "create") { return await prepareCreate( @@ -157,7 +185,7 @@ async function prepare( actor, request, allocation, - lookups(db, actor), + lookups(db, actor, hidden), ); } const target = await loadTarget( @@ -176,7 +204,7 @@ async function prepare( target, request, allocation, - lookups(db, actor), + lookups(db, actor, hidden), ) : await prepareDelete(env.federation, actor, target, allocation, () => currentAddressing(db, target.id), @@ -201,9 +229,12 @@ export async function previewLocalWrite( env: LocalWriteEnvironment, principal: WritePrincipal, request: LocalWriteRequest, + options?: PreviewOptions, ): Promise { const requestError = checkRequest(request); if (requestError != null) return { ok: false, error: requestError }; + const hidden = await hiddenSources(request, options); + if (isLocalWriteError(hidden)) return { ok: false, error: hidden }; const actor = await findWritingActor( env.db, env.rootOrigin, @@ -213,7 +244,14 @@ export async function previewLocalWrite( ); if (isLocalWriteError(actor)) return { ok: false, error: actor }; const allocation = allocateFor(request); - const prepared = await prepare(env, env.db, actor, request, allocation); + const prepared = await prepare( + env, + env.db, + actor, + request, + allocation, + hidden, + ); if (isLocalWriteError(prepared)) return { ok: false, error: prepared }; const token = await issueToken( env.previewKey, @@ -367,6 +405,8 @@ export async function commitLocalWrite( ), }; } + const hidden = await hiddenSources(request, options); + if (isLocalWriteError(hidden)) return { ok: false, error: hidden }; try { const result = await env.db.transaction(async (tx) => { const fail = (error: LocalWriteError): never => { @@ -382,7 +422,14 @@ export async function commitLocalWrite( if (isLocalWriteError(actor)) fail(actor); const writer = actor as WritingActor; if (outboxed) await lockActorCollection(tx, writer.id, "outbox"); - const prepared = await prepare(env, tx, writer, request, allocation); + const prepared = await prepare( + env, + tx, + writer, + request, + allocation, + hidden, + ); if (isLocalWriteError(prepared)) fail(prepared); const { resources, target, typed } = prepared as PreparedOperation; const created = resources.filter( @@ -432,7 +479,7 @@ export async function commitLocalWrite( ); // Children are saved before what embeds them, and an edited object // before its Update, so each finds the revisions it embeds here. - const snapshots = new Map(); + const snapshots = new Map(); for (const resource of resources) { const embeddings = await findEmbeddings( tx, @@ -452,6 +499,7 @@ export async function commitLocalWrite( snapshots.set(resource.iri, { revisionId, document: resource.document, + embeddings, }); continue; } @@ -471,6 +519,7 @@ export async function commitLocalWrite( snapshots.set(resource.iri, { revisionId: revision.id, document: resource.document, + embeddings, }); } if (outboxed) { diff --git a/packages/federation/src/local-write/types.ts b/packages/federation/src/local-write/types.ts index 7da7bdd9..ef3e7805 100644 --- a/packages/federation/src/local-write/types.ts +++ b/packages/federation/src/local-write/types.ts @@ -63,9 +63,10 @@ export interface NewResource { /** * The stored revision an embedded document of a request was derived from, - * such as a loaded `Note` changed for an experiment. A revision's readers - * may read where each document it embeds came from; the server decides - * whether the document still keeps that revision or was derived from it. + * such as a loaded `Note` changed for an experiment. The principal must be + * able to read it, as {@link PreviewOptions.unreadableRevisions} tells; the + * server decides whether the document still keeps that revision or was + * derived from it. */ export interface EmbeddedSource { /** @@ -128,13 +129,17 @@ export type LocalWriteErrorType = | "stale_preview" | "revision_conflict" | "resource_conflict" - | "unsupported_edit"; + | "unsupported_edit" + | "source_unavailable"; export interface LocalWriteError { readonly type: LocalWriteErrorType; /** For people; use `type` and `diagnostics` for decisions. */ readonly message: string; - /** Document findings at submitted paths, for `invalid_document`. */ + /** + * Document findings at submitted paths, for `invalid_document`, and the + * paths of declared sources, for `source_unavailable`. + */ readonly diagnostics: readonly Diagnostic[]; } @@ -190,7 +195,21 @@ export type CommitOutcome = | { readonly ok: true; readonly result: LocalWriteResult } | { readonly ok: false; readonly error: LocalWriteError }; -export interface CommitOptions { +export interface PreviewOptions { + /** + * Finds the revisions among IDs that the principal may not read. Each + * revision a request declares in `sources` must be one the principal may + * read; the preview checks it, and the commit checks it again, since the + * principal's access may change in between. One the principal may not + * read fails as one that does not exist does, with `source_unavailable`. + * Required to declare sources. + */ + readonly unreadableRevisions?: ( + ids: readonly Uuid[], + ) => Promise>; +} + +export interface CommitOptions extends PreviewOptions { /** The token of the approved preview. */ readonly previewToken: string; /** diff --git a/packages/graphql/README.md b/packages/graphql/README.md index a47f1c81..671ead6e 100644 --- a/packages/graphql/README.md +++ b/packages/graphql/README.md @@ -111,6 +111,12 @@ superseded, or deleted; it is null when the viewer may not read the source revision, and nothing else of the document changes. See [resource revision internals]. +`unreadableRevisions(viewer, ids)` in `@drfed/graphql/readable` tells which +revisions a viewer may not read by the same rule. Pass it to +`previewLocalWrite()` and `commitLocalWrite()` of +`@drfed/federation/local-write`, which check that a writer declares as +sources only revisions they may read. + [resource revision internals]: https://drfed.org/internals/resource-revisions#graphql-reads diff --git a/packages/graphql/package.json b/packages/graphql/package.json index 339af365..5671008e 100644 --- a/packages/graphql/package.json +++ b/packages/graphql/package.json @@ -74,6 +74,10 @@ "types": "./dist/object.d.mts", "default": "./dist/object.mjs" }, + "./readable": { + "types": "./dist/readable.d.mts", + "default": "./dist/readable.mjs" + }, "./activity-delivery": { "types": "./dist/activity-delivery/entry.d.mts", "default": "./dist/activity-delivery/entry.mjs" @@ -93,6 +97,7 @@ "src/instance.ts", "src/schema.ts", "src/object.ts", + "src/readable.ts", "src/activity-delivery/entry.ts" ], "dts": { diff --git a/packages/graphql/src/revision.test.ts b/packages/graphql/src/revision.test.ts index 832f96df..7d6a56b4 100644 --- a/packages/graphql/src/revision.test.ts +++ b/packages/graphql/src/revision.test.ts @@ -21,12 +21,16 @@ import { describe, it } from "node:test"; import { type CreateRequest, + type EmbeddedSource, type JsonObject, type LocalWriteEnvironment, type LocalWriteRequest, + type PreviewOptions, + type SavedResource, commitLocalWrite, previewLocalWrite, } from "@drfed/federation/local-write"; +import { unreadableRevisions } from "@drfed/graphql/readable"; import { type Database, schema } from "@drfed/models"; import { PUBLIC_IRI, ensureResource } from "@drfed/models/resource"; import { @@ -60,6 +64,7 @@ const ACTOR_IRI = `https://test-instance.drfed.org/users/${localActorId}`; const FEATURED_IRI = `${ACTOR_IRI}/featured`; const BLIND = "https://remote.example/users/blind"; const PRINCIPAL = { accountId: accountId as Uuid }; +const ACTIVITY: CreateRequest["resources"] = [{ path: [], kind: "activity" }]; const CAROL = "https://remote.example/users/carol"; const revisionId = (id: string): string => @@ -67,14 +72,21 @@ const revisionId = (id: string): string => interface Writer { readonly harness: TestHarness; + readonly env: LocalWriteEnvironment; + /** The account of the local instance's member, who writes. */ + readonly account: Account; readonly auth: RequestInit; - /** Saves new resources and returns their IDs and IRIs, root last. */ + /** + * Saves new resources and returns their IDs and IRIs, root last. Declared + * sources are checked against what the writer may read. + */ save( document: JsonObject, resources?: CreateRequest["resources"], + sources?: readonly EmbeddedSource[], ): Promise<{ id: Uuid; iri: string }[]>; /** Commits an edit or deletion. */ - change(request: LocalWriteRequest): Promise; + change(request: LocalWriteRequest): Promise; /** Sends a query, anonymously unless `init` authenticates it. */ query( query: string, @@ -83,6 +95,15 @@ interface Writer { ): Promise<{ data?: Record; errors?: unknown[] }>; } +/** + * Checks declared sources as the GraphQL layer reads revisions for an + * account. + * @returns The options that pass the check to a local write. + */ +const readerOf = (db: Database, account: Account): PreviewOptions => ({ + unreadableRevisions: (ids) => unreadableRevisions({ db, account }, ids), +}); + async function withWriter( // oxlint-disable-next-line promise/prefer-await-to-callbacks callback: (writer: Writer) => Promise, @@ -90,6 +111,10 @@ async function withWriter( await withTestHarness(async (harness) => { const auth = await seedAuthenticatedLocalInstance(harness.db); await seedLocalActor(harness.db); + const account = await harness.db.query.accounts.findFirst({ + where: { id: accountId }, + }); + assert.ok(account != null); const env: LocalWriteEnvironment = { db: harness.db, federation: harness.federation, @@ -100,10 +125,12 @@ async function withWriter( ["sign", "verify"], ), }; + const access = readerOf(harness.db, account); const commit = async (request: LocalWriteRequest) => { - const preview = await previewLocalWrite(env, PRINCIPAL, request); + const preview = await previewLocalWrite(env, PRINCIPAL, request, access); assert.ok(preview.ok, JSON.stringify(!preview.ok && preview.error)); const outcome = await commitLocalWrite(env, PRINCIPAL, request, { + ...access, previewToken: preview.preview.token, // Edits and deletions require a reservation; nothing is sent here. ...(request.operation === "create" @@ -116,18 +143,21 @@ async function withWriter( // oxlint-disable-next-line promise/prefer-await-to-callbacks, node/callback-return await callback({ harness, + env, + account, auth, - async save(document, resources = [{ path: [], kind: "object" }]) { + async save(document, resources, sources) { const result = await commit({ operation: "create", actorId: localActorId, document: { "@context": AS, ...document }, - resources, + resources: resources ?? [{ path: [], kind: "object" }], + ...(sources == null ? {} : { sources }), }); return result.resources.map(({ id, iri }) => ({ id, iri })); }, async change(request) { - await commit(request); + return (await commit(request)).resources; }, async query(query, variables, init) { const response = await harness.post( @@ -1154,6 +1184,63 @@ describe("Access to revisions across workspaces", () => { } }); }); + + it("refuses a member of A to embed a revision only B received as a source", async () => { + await withWriter(async ({ harness, env, account, save }) => { + const { db } = harness; + const note = await privateNote(db); + const memberB = await seedViewer(db, { memberOf: note.workspaceB }); + const admin = await seedViewer(db, { admin: true }); + const like = (revision: Uuid): LocalWriteRequest => ({ + operation: "create", + actorId: localActorId, + document: { + "@context": AS, + type: "Like", + object: note.embedded, + to: [PUBLIC_IRI], + }, + resources: ACTIVITY, + sources: [{ path: ["object"], revisionId: revision }], + }); + const access = readerOf(db, account); + const refused = await previewLocalWrite( + env, + PRINCIPAL, + like(note.revisionId), + access, + ); + assert.ok(!refused.ok); + assert.equal(refused.error.type, "source_unavailable"); + assert.deepEqual( + refused.error.diagnostics.map(({ path }) => path), + [["object"]], + ); + // It fails as a revision that does not exist does. + assert.deepEqual( + await previewLocalWrite(env, PRINCIPAL, like(uuidV7()), access), + refused, + ); + // Pasting it without a source is not refused. + await save( + { type: "Like", object: note.embedded, to: [PUBLIC_IRI] }, + ACTIVITY, + ); + // Members of B and administrators may read it, so may declare it. + assert.deepEqual( + await unreadableRevisions({ db, account }, [note.revisionId]), + new Set([note.revisionId]), + ); + for (const viewer of [memberB, admin]) { + assert.deepEqual( + await unreadableRevisions({ db, account: viewer.account }, [ + note.revisionId, + ]), + new Set(), + ); + } + }); + }); }); describe("Access to revisions by their own evidence", () => { @@ -1310,6 +1397,96 @@ describe("DocumentNode.source", () => { return root.relations[0].node.source; }; + it("follows a saved Create and the Update of its edited Note to the deletion", async () => { + await withWriter(async ({ harness, save, change, query }) => { + const [note, create] = await save( + { + type: "Create", + to: [PUBLIC_IRI], + object: { type: "Note", content: "A", to: [PUBLIC_IRI] }, + }, + [ + { path: [], kind: "activity" }, + { path: ["object"], kind: "object", representation: "embedded" }, + ], + ); + assert.ok(note != null && create != null); + const first = await head(harness.db, note.id); + const [, update] = await change( + edit(note.id, first.id, { + ...(first.document as JsonObject), + content: "B", + }), + ); + assert.ok(update != null); + const second = await head(harness.db, note.id); + const of = (revision: Uuid, sequence: number, status: string) => ({ + relation: "snapshot", + status, + revision: { id: revisionId(revision), sequence }, + }); + assert.deepEqual( + await read(query, create.id), + of(first.id, 1, "superseded"), + ); + assert.deepEqual( + await read(query, update.id), + of(second.id, 2, "current"), + ); + await change({ + operation: "delete", + actorId: localActorId, + objectId: note.id, + expectedRevisionId: second.id, + }); + assert.deepEqual( + await read(query, create.id), + of(first.id, 1, "deleted"), + ); + assert.deepEqual( + await read(query, update.id), + of(second.id, 2, "deleted"), + ); + }); + }); + + it("knows the source of a loaded document only when it is declared", async () => { + await withWriter(async ({ harness, save, query }) => { + const [note] = await save({ + type: "Note", + content: "A", + to: [PUBLIC_IRI], + }); + assert.ok(note != null); + const loaded = await head(harness.db, note.id); + const object = withoutContext(loaded.document as JsonObject); + const sources = [{ path: ["object"], revisionId: loaded.id }]; + const like = (embedded: JsonObject) => ({ + type: "Like", + object: embedded, + to: [PUBLIC_IRI], + }); + const [kept] = await save(like(object), ACTIVITY, sources); + const [derived] = await save( + like({ ...object, content: "changed" }), + ACTIVITY, + sources, + ); + // A pasted copy has an unknown source, even when it keeps the + // current revision. + const [pasted] = await save(like(object), ACTIVITY); + assert.ok(kept != null && derived != null && pasted != null); + const of = (relation: string) => ({ + relation, + status: "current", + revision: { id: revisionId(loaded.id), sequence: 1 }, + }); + assert.deepEqual(await read(query, kept.id), of("snapshot")); + assert.deepEqual(await read(query, derived.id), of("derived")); + assert.equal(await read(query, pasted.id), null); + }); + }); + it("tells snapshots and derived documents and where their sources stand", async () => { await withWriter(async ({ harness, query }) => { const { db } = harness; diff --git a/packages/models/src/document.ts b/packages/models/src/document.ts index 33712b63..6d7ddcd1 100644 --- a/packages/models/src/document.ts +++ b/packages/models/src/document.ts @@ -89,6 +89,7 @@ export const DIAGNOSTIC_REASONS = { invalid_context: { category: "vocabulary", severity: "error" }, unauthorized_local_identity: { category: "authority", severity: "error" }, server_owned_field_conflict: { category: "authority", severity: "error" }, + source_unavailable: { category: "authority", severity: "error" }, context_unavailable_offline: { category: "support", severity: "error" }, unsupported_context_form: { category: "support", severity: "error" }, unsupported_type: { category: "support", severity: "error" }, diff --git a/scripts/seed-revisions/cases-access.mts b/scripts/seed-revisions/cases-access.mts index ef370afd..38922a42 100644 --- a/scripts/seed-revisions/cases-access.mts +++ b/scripts/seed-revisions/cases-access.mts @@ -35,14 +35,20 @@ const privateEmbedding: SeedCase = async ({ db, alice, writer }) => { to: [CAROL_FOLLOWERS_IRI], deliveredTo: [alice], }); + // A member of A may read the Note, so may declare it as the source. const announce = await writer.save( { type: "Announce", object: withoutContext(note.document) }, ACTIVITY, + [{ path: ["object"], revisionId: note.revisionId }], ); const head = await loadHead(db, announce.id); const undo = await writer.save( { type: "Undo", object: withoutContext(head.document) }, ACTIVITY, + [ + { path: ["object"], revisionId: head.revisionId }, + { path: ["object", "object"], revisionId: note.revisionId }, + ], ); return { number: 16, @@ -69,6 +75,7 @@ const laterRestricted: SeedCase = async ({ db, alice, bob, writer }) => { const liked = await writer.save( { type: "Like", object: withoutContext(first.document) }, ACTIVITY, + [{ path: ["object"], revisionId: first.revisionId }], ); await receiveNote(db, { iri, diff --git a/scripts/seed-revisions/cases-sources.mts b/scripts/seed-revisions/cases-sources.mts index ada7b0b1..4b25509e 100644 --- a/scripts/seed-revisions/cases-sources.mts +++ b/scripts/seed-revisions/cases-sources.mts @@ -56,7 +56,11 @@ const declared = (note: SavedNote) => [ const snapshotCurrent: SeedCase = async (context) => { const note = await saveNote(context, "Embedded as it is"); - const saved = await context.writer.save(like(note.embedded), ACTIVITY); + const saved = await context.writer.save( + like(note.embedded), + ACTIVITY, + declared(note), + ); return { number: 8, title: "Snapshot of a source that is still current", @@ -66,7 +70,11 @@ const snapshotCurrent: SeedCase = async (context) => { const snapshotSuperseded: SeedCase = async (context) => { const note = await saveNote(context, "Embedded, then edited"); - const saved = await context.writer.save(like(note.embedded), ACTIVITY); + const saved = await context.writer.save( + like(note.embedded), + ACTIVITY, + declared(note), + ); await context.writer.edit(note.id, { content: "Edited after the Like" }); return { number: 9, @@ -77,7 +85,11 @@ const snapshotSuperseded: SeedCase = async (context) => { const snapshotDeleted: SeedCase = async (context) => { const note = await saveNote(context, "Embedded, then deleted"); - const saved = await context.writer.save(like(note.embedded), ACTIVITY); + const saved = await context.writer.save( + like(note.embedded), + ACTIVITY, + declared(note), + ); await context.writer.remove(note.id); return { number: 10, @@ -119,7 +131,7 @@ const unknownSource: SeedCase = async (context) => { const { env, alice, writer } = context; const note = await saveNote(context, "Read by a script"); await writer.edit(note.id, { content: "Edited before the script saved" }); - // The stale version matches no current revision, and nothing is declared. + // Nothing is declared, so the stale copy has no known source. const stale = await writer.save(like(note.embedded), ACTIVITY); const legacy = await createLegacyObject( env, @@ -154,7 +166,11 @@ const reserialized: SeedCase = async (context) => { const reordered = Object.fromEntries( Object.entries(note.embedded).toReversed(), ); - const kept = await context.writer.save(like(reordered), ACTIVITY); + const kept = await context.writer.save( + like(reordered), + ACTIVITY, + declared(note), + ); const recontextualized = await context.writer.save( like({ "@context": [AS, { ex: "https://ext.example/ns#" }], @@ -177,11 +193,19 @@ const reserialized: SeedCase = async (context) => { const deepSources: SeedCase = async (context) => { const { db, writer } = context; const note = await saveNote(context, "Embedded two levels deep"); - const liked = await writer.save(like(note.embedded), ACTIVITY); + const liked = await writer.save( + like(note.embedded), + ACTIVITY, + declared(note), + ); const head = await loadHead(db, liked.id); const undo = await writer.save( { type: "Undo", object: withoutContext(head.document) }, ACTIVITY, + [ + { path: ["object"], revisionId: head.revisionId }, + { path: ["object", "object"], revisionId: note.revisionId }, + ], ); return { number: 15, diff --git a/scripts/seed-revisions/writer.mts b/scripts/seed-revisions/writer.mts index 7cc9ff26..2fcea71b 100644 --- a/scripts/seed-revisions/writer.mts +++ b/scripts/seed-revisions/writer.mts @@ -25,6 +25,7 @@ import { commitLocalWrite, previewLocalWrite, } from "@drfed/federation/local-write"; +import { unreadableRevisions } from "@drfed/graphql/readable"; import type { Database } from "@drfed/models"; import { loadCurrentResourceRevision } from "@drfed/models/resource-revision"; import type { Uuid } from "@drfed/models/uuid"; @@ -89,7 +90,8 @@ export async function loadHead(db: Database, resourceId: Uuid): Promise { /** * Makes the writer of a workspace's actor. Nothing it saves is delivered: - * edits and deletions get a reservation that does nothing. + * edits and deletions get a reservation that does nothing. Declared sources + * must be revisions the member may read, as GraphQL reads them. * @returns The writer. */ export function createWriter( @@ -97,12 +99,22 @@ export function createWriter( { actorId, member }: Workspace, ): Writer { const principal = { accountId: member.accountId }; + const access = { + unreadableRevisions: async (ids: readonly Uuid[]) => { + const account = await env.db.query.accounts.findFirst({ + where: { id: member.accountId }, + }); + if (account == null) throw new Error("The member has no account."); + return await unreadableRevisions({ db: env.db, account }, ids); + }, + }; const commit = async ( request: LocalWriteRequest, ): Promise => { - const preview = await previewLocalWrite(env, principal, request); + const preview = await previewLocalWrite(env, principal, request, access); if (!preview.ok) throw new Error(JSON.stringify(preview.error)); const outcome = await commitLocalWrite(env, principal, request, { + ...access, previewToken: preview.preview.token, ...(request.operation === "create" ? {} From 1f5bef2b5cb1786de19240cb403134224767814b Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Mon, 16 Nov 2026 17:36:52 +0900 Subject: [PATCH 06/10] Add a space to split the login link and the last \n --- packages/graphql/src/auth/mail.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/graphql/src/auth/mail.ts b/packages/graphql/src/auth/mail.ts index 7813a932..e9509365 100644 --- a/packages/graphql/src/auth/mail.ts +++ b/packages/graphql/src/auth/mail.ts @@ -54,12 +54,14 @@ export async function sendMail( const renderLoginEmail = (loginUrl: string): MessageContent => ({ // FIXME: https://github.com/fedify-dev/drfed/issues/35 + // oxlint-disable no-inline-comments text: `Hello, Welcome to DrFed! If you request to login to DrFed, please visit: -open ${loginUrl} +open ${loginUrl}${/* Split between the link and the last `\n` */ " "} Otherwise, please just ignore this mail.`, }); +// oxlint-enable no-inline-comments export function logReceipt(receipt: Receipt): void { if (receipt.successful) { From 82e53339abb172847e77935df1d8e525601e8b46 Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Tue, 17 Nov 2026 14:57:19 +0900 Subject: [PATCH 07/10] Show resource revisions on a resource page The web app now has a page for a resource at /resource/{id}, which shows its history beside one revision. The revision parameter names the sequence to show; without it, the latest revision the viewer may read is shown, and a sequence the viewer may not read is reported with a link back to the latest. The history is a timeline, newest first, that marks the current revision and counts the revisions the viewer may not read between the loaded ones. Older revisions are loaded with a button. A revision is shown with its metadata as a field list, times as stored, and its validation findings. An interpreted root is drawn as a tree whose embedded documents can be collapsed, down to three levels, with their source paths written as JSON Pointers and the source revisions they came from. The saved JSON is shown below, expanded when the revision was not interpreted. https://github.com/fedify-dev/drfed/issues/154 AI assistance: the maintainers chose the layout, wording, and display rules from mockups in the design branch, and asked Claude Code to apply them to the real page following the decisions of the issue thread. Claude Code wrote the route, the components, the timeline calculations, and the styles. The type check, lint, formatter, license check, and web build were run without the mockup files, and the page was checked against the seeded revisions on the development server. Assisted-by: Claude Code:claude-opus-5-5 --- .../web/src/components/ResourceDocument.tsx | 702 ++++++++++++++++++ .../web/src/components/ResourceRevision.tsx | 239 ++++++ .../web/src/components/ResourceTimeline.tsx | 173 +++++ packages/web/src/resource.ts | 141 ++++ packages/web/src/routes/resource/[id].tsx | 254 +++++++ packages/web/src/styles/resource.module.css | 405 ++++++++++ 6 files changed, 1914 insertions(+) create mode 100644 packages/web/src/components/ResourceDocument.tsx create mode 100644 packages/web/src/components/ResourceRevision.tsx create mode 100644 packages/web/src/components/ResourceTimeline.tsx create mode 100644 packages/web/src/resource.ts create mode 100644 packages/web/src/routes/resource/[id].tsx create mode 100644 packages/web/src/styles/resource.module.css diff --git a/packages/web/src/components/ResourceDocument.tsx b/packages/web/src/components/ResourceDocument.tsx new file mode 100644 index 00000000..a4a379d0 --- /dev/null +++ b/packages/web/src/components/ResourceDocument.tsx @@ -0,0 +1,702 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// The document tree of a revision: the root and the documents embedded in it, +// three levels deep. Relay fragments cannot recurse, so each level has its +// own fragment that spreads the next one. + +import { A } from "@solidjs/router"; +import { graphql } from "relay-runtime"; +import { + For, + type JSX, + Match, + Show, + Switch, + createMemo, + createSignal, +} from "solid-js"; +import { createFragment } from "solid-relay"; + +import { + type Path, + WORDING, + formatPointer, + pathKey, + resourceHref, + toPath, + typeLabel, +} from "~/resource.ts"; + +import type { ResourceDocumentLevel0_node$key } from "./__generated__/ResourceDocumentLevel0_node.graphql.ts"; +import type { ResourceDocumentLevel1_node$key } from "./__generated__/ResourceDocumentLevel1_node.graphql.ts"; +import type { ResourceDocumentLevel2_node$key } from "./__generated__/ResourceDocumentLevel2_node.graphql.ts"; +import type { ResourceDocumentLevel3_node$key } from "./__generated__/ResourceDocumentLevel3_node.graphql.ts"; +import type { ResourceDocumentParts_node$key } from "./__generated__/ResourceDocumentParts_node.graphql.ts"; +import type { ResourceDocumentRelation_relation$key } from "./__generated__/ResourceDocumentRelation_relation.graphql.ts"; +import { ActivityLogSource } from "./ActivityLogSource.tsx"; +import { CopyButton } from "./CopyButton.tsx"; + +import styles from "~/styles/resource.module.css"; + +const STATUS_LABELS: ReadonlyMap = new Map([ + ["current", "Current"], + ["superseded", "Newer revisions exist"], + ["deleted", "Deleted"], +]); + +/** A validator finding, with its path narrowed. */ +export interface Diagnostic { + readonly severity: string; + readonly category: string; + readonly reason: string; + readonly path: Path; + readonly message: string; +} + +/** A relation value as a level fragment selects it. */ +interface LevelRelation { + readonly property: string; + readonly representation: string; + readonly node: unknown; + readonly " $fragmentSpreads": ResourceDocumentRelation_relation$key[" $fragmentSpreads"]; +} + +const formatJson = (value: unknown) => JSON.stringify(value, undefined, 2); + +const statusLabel = (status: string | null | undefined): string | undefined => + status == undefined ? undefined : STATUS_LABELS.get(status); + +/** + * Shows saved JSON in a disclosure, highlighted once opened. + * @returns The disclosure. + */ +export function JsonDisclosure(props: { + value: unknown; + label: string; + open: boolean; +}) { + // oxlint-disable-next-line solid/reactivity -- Only the initial state. + const [open, setOpen] = createSignal(props.open); + return ( +
setOpen(event.currentTarget.open)} + > + {props.label} + + + + +
+ ); +} + +/** + * A source path as a JSON Pointer. + * @returns The pointer, or nothing for the root. + */ +function PathText(props: { path: Path }) { + return ( + + {(text) => {text()}} + + ); +} + +/** + * Validator findings, with their paths as JSON Pointers. + * @returns The list, or nothing when there are none. + */ +export function DiagnosticList(props: { diagnostics: readonly Diagnostic[] }) { + return ( + 0}> +
    + + {(diagnostic) => ( +
  • +

    + {diagnostic.severity} + {diagnostic.category} + {diagnostic.reason} + +

    +

    {diagnostic.message}

    +
  • + )} +
    +
+
+ ); +} + +/** + * Values grouped by property, in the order the properties first appear. + * @returns The groups, or nothing when there are none. + */ +function PropertyGroups(props: { + label: string; + entries: readonly T[]; + children: (entry: T) => JSX.Element; +}) { + const groups = createMemo(() => [ + ...Map.groupBy(props.entries, (entry) => entry.property), + ]); + return ( + 0}> +

{props.label}

+
+ + {([property, entries]) => ( +
+
+ {property} +
+
+
    + {(entry) => props.children(entry)} +
+
+
+ )} +
+
+
+ ); +} + +/** + * An IRI, linked to the resource registered under it when the viewer may + * read one. + * @returns The IRI. + */ +function IriText(props: { iri: string; resourceId: string | undefined }) { + return ( + {props.iri}}> + {(id) => {props.iri}} + + ); +} + +/** + * The labels of `DocumentNode.source`, or the neutral note when it is null + * and the viewer may read some revision of the resource under its IRI. + * @returns The labels, or nothing for an anonymous document or one with no + * revision to have come from. + */ +function SourceLabels(props: { + source: + | { + readonly relation: string; + readonly status: string | null | undefined; + readonly revision: { + readonly sequence: number; + readonly resource: { readonly id: string }; + }; + } + | null + | undefined; + /** Whether the viewer may read a revision it could have come from. */ + expected: boolean; +}) { + return ( + + Source revision unknown + + } + > + {(source) => ( + + + {source().relation === "snapshot" ? "Snapshot" : "Derived"} + + Unknown} + > + {(label) => {label()}} + + + {WORDING.sourceLink(source().revision.sequence)} + + + + {WORDING.currentLink} + + + + )} + + ); +} + +/** + * A relation value drawn as one line: a reference, a `Link`, or an embedded + * document that is not expanded. + * @returns The line. + */ +function RelationLine(props: { + $relation: ResourceDocumentRelation_relation$key; +}) { + const data = createFragment( + graphql` + fragment ResourceDocumentRelation_relation on DocumentRelation + @throwOnFieldError { + representation + iri + path + resource { + id + } + } + `, + () => props.$relation, + ); + return ( + + {(relation) => ( + + + + Embedded + + {relation().iri ?? Anonymous} + + + + Link + {relation().iri} + + + Reference + + + + + {WORDING.unreadableReference} + + + + + + )} + + ); +} + +/** + * One document node: its header line and what it holds below it. The root + * stands alone; an embedded document is a disclosure joined to its parent by + * a guide line. + * @returns The node. + */ +function NodeView(props: { + $node: ResourceDocumentParts_node$key; + depth: number; + relations: readonly T[]; + diagnostics: readonly Diagnostic[]; + /** Whether a source could have been recorded; see `SourceLabels`. */ + sourceExpected: boolean; + /** Draws the document an embedded value holds. */ + embedded: (node: NonNullable, relation: T) => JSX.Element; +}) { + const data = createFragment( + graphql` + fragment ResourceDocumentParts_node on DocumentNode @throwOnFieldError { + type + kind + iri + path + addressing { + property + position + iri + resource { + id + } + } + extensions { + key + value + } + source { + relation + status + revision { + sequence + resource { + id + } + } + } + } + `, + () => props.$node, + ); + return ( + + {(node) => { + const path = () => toPath(node().path); + const header = () => ( + + 0}> + Embedded + + + {typeLabel(node().type)} + + {node().kind} + + {node().iri ?? Anonymous} + + + 0}> + + + + ); + const body = () => ( +
+ pathKey(diagnostic.path) === pathKey(path()), + )} + /> + + {(relation) => ( +
  • + } + > + {(child) => props.embedded(child(), relation)} + +
  • + )} +
    + + {(recipient) => ( +
  • + + [{recipient.position}] + + Anonymous} + > + {(iri) => ( + + )} + + + +
  • + )} +
    + 0}> +

    Extension properties

    +
    + + {(extension) => ( +
    +
    + {extension.key} +
    +
    +
    +                          {formatJson(extension.value)}
    +                        
    +
    +
    + )} +
    +
    +
    +
    + ); + return ( + 0} + fallback={ +
    + {header()} + {body()} +
    + } + > +
    + {header()} + {body()} +
    +
    + ); + }} +
    + ); +} + +/** + * A document three levels below the root, whose embedded documents are shown + * as saved JSON. + * @returns The node. + */ +function Level3(props: { + $node: ResourceDocumentLevel3_node$key; + diagnostics: readonly Diagnostic[]; + sourceExpected: boolean; +}) { + const data = createFragment( + graphql` + fragment ResourceDocumentLevel3_node on DocumentNode @throwOnFieldError { + ...ResourceDocumentParts_node + relations { + property + representation + ...ResourceDocumentRelation_relation + node { + document + } + } + } + `, + () => props.$node, + ); + return ( + + {(node) => ( + { + const document: unknown = child.document; + return ( + <> + + + + ); + }} + /> + )} + + ); +} + +/** + * A document two levels below the root. + * @returns The node. + */ +function Level2(props: { + $node: ResourceDocumentLevel2_node$key; + diagnostics: readonly Diagnostic[]; + sourceExpected: boolean; +}) { + const data = createFragment( + graphql` + fragment ResourceDocumentLevel2_node on DocumentNode @throwOnFieldError { + ...ResourceDocumentParts_node + relations { + property + representation + ...ResourceDocumentRelation_relation + resource { + revisions(first: 1) { + edges { + cursor + } + } + } + node { + ...ResourceDocumentLevel3_node + } + } + } + `, + () => props.$node, + ); + return ( + + {(node) => ( + ( + 0 + } + /> + )} + /> + )} + + ); +} + +/** + * A document one level below the root. + * @returns The node. + */ +function Level1(props: { + $node: ResourceDocumentLevel1_node$key; + diagnostics: readonly Diagnostic[]; + sourceExpected: boolean; +}) { + const data = createFragment( + graphql` + fragment ResourceDocumentLevel1_node on DocumentNode @throwOnFieldError { + ...ResourceDocumentParts_node + relations { + property + representation + ...ResourceDocumentRelation_relation + resource { + revisions(first: 1) { + edges { + cursor + } + } + } + node { + ...ResourceDocumentLevel2_node + } + } + } + `, + () => props.$node, + ); + return ( + + {(node) => ( + ( + 0 + } + /> + )} + /> + )} + + ); +} + +/** + * The root document of a revision and what it embeds. + * @returns The document tree. + */ +export function DocumentTree(props: { + $root: ResourceDocumentLevel0_node$key; + diagnostics: readonly Diagnostic[]; +}) { + const data = createFragment( + graphql` + fragment ResourceDocumentLevel0_node on DocumentNode @throwOnFieldError { + ...ResourceDocumentParts_node + relations { + property + representation + ...ResourceDocumentRelation_relation + resource { + revisions(first: 1) { + edges { + cursor + } + } + } + node { + ...ResourceDocumentLevel1_node + } + } + } + `, + () => props.$root, + ); + return ( + + {(node) => ( + ( + 0 + } + /> + )} + /> + )} + + ); +} diff --git a/packages/web/src/components/ResourceRevision.tsx b/packages/web/src/components/ResourceRevision.tsx new file mode 100644 index 00000000..c1ec6be7 --- /dev/null +++ b/packages/web/src/components/ResourceRevision.tsx @@ -0,0 +1,239 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { graphql } from "relay-runtime"; +import { For, Match, Show, Switch, createMemo } from "solid-js"; +import { createFragment } from "solid-relay"; + +import { pathKey, toPath, typeLabel } from "~/resource.ts"; + +import type { ResourceRevision_revision$key } from "./__generated__/ResourceRevision_revision.graphql.ts"; +import { + type Diagnostic, + DiagnosticList, + DocumentTree, + JsonDisclosure, +} from "./ResourceDocument.tsx"; + +import styles from "~/styles/resource.module.css"; + +/** A node of the document tree, as far as the tree draws nodes. */ +interface DrawnNode { + readonly path: unknown; + readonly relations?: readonly { + readonly representation: string; + readonly node?: DrawnNode | null | undefined; + }[]; +} + +/** + * Collects the paths of the nodes the document tree draws: the root and the + * embedded documents three levels below it, as far as the fragment selects. + * @returns The path keys. + */ +const drawnPaths = (node: DrawnNode): readonly string[] => [ + pathKey(toPath(node.path)), + ...(node.relations ?? []).flatMap((relation) => + relation.representation === "embedded" && relation.node != undefined + ? drawnPaths(relation.node) + : [], + ), +]; + +/** + * A stored time, written as stored. + * @returns The time element. + */ +export function TimeText(props: { value: string }) { + return ; +} + +/** + * One revision: how DrFed stored it and what it holds. + * @returns The revision. + */ +export function ResourceRevision(props: { + $revision: ResourceRevision_revision$key; + /** Whether it is the current revision of its resource. */ + head: boolean; +}) { + const data = createFragment( + graphql` + fragment ResourceRevision_revision on ResourceRevision + @throwOnFieldError { + id + sequence + kind + capture + backfilled + created + deleted + formerTypes + interpreted + document + diagnostics { + severity + category + reason + path + message + } + root { + ...ResourceDocumentLevel0_node + path + relations { + representation + node { + path + relations { + representation + node { + path + relations { + representation + node { + path + } + } + } + } + } + } + } + } + `, + () => props.$revision, + ); + const diagnostics = createMemo((): readonly Diagnostic[] => + (data()?.diagnostics ?? []).map((diagnostic) => ({ + severity: diagnostic.severity, + category: diagnostic.category, + reason: diagnostic.reason, + path: toPath(diagnostic.path), + message: diagnostic.message, + })), + ); + // Findings of a node the tree draws are shown on that node; the rest below. + const unplaced = createMemo(() => { + const root = data()?.root; + if (root == undefined) return diagnostics(); + const paths = new Set(drawnPaths(root)); + return diagnostics().filter( + (diagnostic) => !paths.has(pathKey(diagnostic.path)), + ); + }); + const savedDocument = (): unknown => data()?.document; + return ( + + {(revision) => ( +
    +
    +

    {props.head ? "Current revision" : "Earlier revision"}

    +
    +
    +
    Sequence
    +
    {revision().sequence}
    +
    +
    +
    Kind
    +
    {revision().kind}
    +
    +
    +
    Capture
    +
    {revision().capture}
    +
    +
    +
    Backfilled
    +
    + {revision().backfilled + ? "Yes, migrated from legacy records" + : "No"} +
    +
    +
    +
    Stored
    +
    + +
    +
    + + {(deleted) => ( +
    +
    Deleted
    +
    + +
    +
    + )} +
    + + {(types) => ( +
    +
    Former types
    +
    + + {(type) => {typeLabel(type)} } + +
    +
    + )} +
    +
    +
    + + + + DrFed could not interpret this document, so only its saved + JSON is shown. The validator findings below tell why. +

    + } + > + {(root) => ( + + )} +
    + + {/* Keyed so that each revision's disclosure starts anew. */} + + + +
    + +

    + This revision records a deletion. It holds no document. +

    +
    + +

    + No document was retained for this revision. +

    +
    +
    +
    + )} +
    + ); +} diff --git a/packages/web/src/components/ResourceTimeline.tsx b/packages/web/src/components/ResourceTimeline.tsx new file mode 100644 index 00000000..60660fc3 --- /dev/null +++ b/packages/web/src/components/ResourceTimeline.tsx @@ -0,0 +1,173 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { A } from "@solidjs/router"; +import { graphql } from "relay-runtime"; +import { For, Match, Show, Switch, createMemo, createSignal } from "solid-js"; +import { createPaginationFragment } from "solid-relay"; + +import { WORDING, resourceHref, timelineEntries } from "~/resource.ts"; + +import type { ResourceTimeline_resource$key } from "./__generated__/ResourceTimeline_resource.graphql.ts"; +import { TimeText } from "./ResourceRevision.tsx"; + +import styles from "~/styles/resource.module.css"; + +const PAGE_SIZE = 20; + +/** + * The history of a resource as a vertical timeline, newest first, with the + * revisions the viewer may not read counted between them. + * @returns The timeline. + */ +export function ResourceTimeline(props: { + $resource: ResourceTimeline_resource$key; + /** The sequence of the revision shown beside it. */ + selected: number | undefined; +}) { + const data = createPaginationFragment( + graphql` + fragment ResourceTimeline_resource on Resource + @throwOnFieldError + @argumentDefinitions( + count: { type: "Int", defaultValue: 20 } + cursor: { type: "String" } + ) + @refetchable(queryName: "ResourceTimelinePaginationQuery") { + id + currentRevision { + sequence + } + revisions(first: $count, after: $cursor) + @connection(key: "ResourceTimeline_revisions") { + edges { + node { + id + sequence + kind + capture + backfilled + created + } + } + } + } + `, + () => props.$resource, + ); + const [failed, setFailed] = createSignal(false); + const entries = createMemo(() => + timelineEntries( + (data()?.revisions.edges ?? []).map((edge) => edge.node), + data()?.currentRevision?.sequence, + !data.hasNext, + ), + ); + function loadOlder() { + if (!data.hasNext || data.isLoadingNext) return; + setFailed(false); + data.loadNext(PAGE_SIZE, { + onComplete(error) { + if (error) setFailed(true); + }, + }); + } + return ( + + {(resource) => ( +
    +
      + + {(entry) => ( + + +
    1. {WORDING.headUnreadable}
    2. +
      + + {(gap) => ( +
    3. + {WORDING.gap(gap().count)} +
    4. + )} +
      + + {(item) => ( +
    5. + + + #{item().revision.sequence} + + {item().revision.kind} + + Current + + + + {item().revision.capture} + {item().revision.backfilled ? " · backfilled" : ""} + + + + +
    6. + )} +
      +
      + )} +
      +
    + +

    + Could not load older revisions.{" "} + +

    +
    + + Loading older revisions… + + + + +
    + )} +
    + ); +} diff --git a/packages/web/src/resource.ts b/packages/web/src/resource.ts new file mode 100644 index 00000000..59166bcc --- /dev/null +++ b/packages/web/src/resource.ts @@ -0,0 +1,141 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// Calculations and wording of the resource page, apart from rendering. + +const ACTIVITY_STREAMS = "https://www.w3.org/ns/activitystreams#"; +const SEQUENCE_PATTERN = /^[1-9]\d*$/v; +/** The largest value of GraphQL's `Int`. */ +const MAXIMUM_SEQUENCE = 2_147_483_647; + +/** The source keys and list indexes from the root of a saved document. */ +export type Path = readonly (string | number)[]; + +/** + * Narrows a `path` the GraphQL `JSON` scalar returns. + * @returns The path, or `[]` for a value that is not one. + */ +export const toPath = (value: unknown): Path => + Array.isArray(value) && + value.every((token) => typeof token === "string" || Number.isInteger(token)) + ? (value as Path) + : []; + +/** + * A key that compares two paths by their tokens. + * @returns The key. + */ +export const pathKey = (path: Path): string => JSON.stringify(path); + +/** + * Escapes a reference token of a JSON Pointer (RFC 6901, section 3). + * @returns The escaped token. + */ +const pointerToken = (token: string | number) => + String(token).replaceAll("~", "~0").replaceAll("/", "~1"); + +/** + * Writes a source path as a JSON Pointer (RFC 6901). + * @returns The pointer, or `undefined` for the root, which is not shown. + */ +export const formatPointer = (path: Path): string | undefined => + path.length === 0 + ? undefined + : `/${path.map((token) => pointerToken(token)).join("/")}`; + +/** + * The term of an ActivityStreams type, or any other type IRI in full. + * @returns The term or the IRI. + */ +export const typeLabel = (iri: string): string => + iri.startsWith(ACTIVITY_STREAMS) && iri.length > ACTIVITY_STREAMS.length + ? iri.slice(ACTIVITY_STREAMS.length) + : iri; + +/** + * Reads the `revision` search parameter. + * @returns The sequence, or `undefined` for a value that names none. + */ +export const parseSequence = (parameter: string): number | undefined => { + if (!SEQUENCE_PATTERN.test(parameter)) return undefined; + const sequence = Number(parameter); + return sequence <= MAXIMUM_SEQUENCE ? sequence : undefined; +}; + +/** + * The page of a resource, or of one of its revisions. + * @returns The path and search string. + */ +export const resourceHref = (id: string, sequence?: number): string => + sequence === undefined + ? `/resource/${encodeURIComponent(id)}` + : `/resource/${encodeURIComponent(id)}?revision=${sequence}`; + +/** A revision as the timeline places it. */ +export interface TimelineRevision { + readonly sequence: number; +} + +/** One entry of the timeline, newest first. */ +export type TimelineEntry = + | { readonly type: "head-unreadable" } + | { readonly type: "revision"; readonly revision: T; readonly head: boolean } + | { readonly type: "gap"; readonly count: number }; + +/** + * Lays out the loaded revisions with the gaps between their sequences. The + * gap below the oldest is known only once every page is loaded, and the gap + * above an unreadable head is never known. + * @param revisions The loaded revisions, newest first. + * @param head The sequence of the current revision, or `undefined` when the + * viewer may not read it. + * @param complete Whether no older revision is left to load. + * @returns The timeline entries, newest first. + */ +export const timelineEntries = ( + revisions: readonly T[], + head: number | undefined, + complete: boolean, +): readonly TimelineEntry[] => [ + ...(head === undefined && revisions.length > 0 + ? [{ type: "head-unreadable" } as const] + : []), + ...revisions.flatMap((revision, index): readonly TimelineEntry[] => { + const next = revisions[index + 1]; + const last = complete ? revision.sequence - 1 : 0; + const gap = + next === undefined ? last : revision.sequence - next.sequence - 1; + return [ + { type: "revision", revision, head: revision.sequence === head }, + ...(gap > 0 ? [{ type: "gap", count: gap } as const] : []), + ]; + }), +]; + +/** The messages of the resource page. */ +export const WORDING = { + gap: (count: number): string => + count === 1 + ? "1 revision you cannot read" + : `${count} revisions you cannot read`, + headUnreadable: "You cannot read the current revision.", + missingRevision: "This resource has no such revision that you can read.", + showLatest: "Show the latest revision", + unreadableReference: "Details unavailable", + sourceLink: (sequence: number): string => `From revision ${sequence}`, + currentLink: "Current revision", + unknownKind: "Unresolved IRI. DrFed stores no details for it.", +} as const; diff --git a/packages/web/src/routes/resource/[id].tsx b/packages/web/src/routes/resource/[id].tsx new file mode 100644 index 00000000..37a494d2 --- /dev/null +++ b/packages/web/src/routes/resource/[id].tsx @@ -0,0 +1,254 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// A resource and its revisions, at /resource/{id}?revision={sequence}. +// Without `revision`, the latest revision the viewer may read is shown. + +import { Title } from "@solidjs/meta"; +import { + A, + type RouteDefinition, + type RouteSectionProps, + query, + useSearchParams, +} from "@solidjs/router"; +import { graphql } from "relay-runtime"; +import { ErrorBoundary, Match, Show, Suspense, Switch } from "solid-js"; +import { + createLazyLoadQuery, + createPreloadedQuery, + loadQuery, + useRelayEnvironment, +} from "solid-relay"; + +import { CopyButton } from "~/components/CopyButton.tsx"; +import { ResourceRevision } from "~/components/ResourceRevision.tsx"; +import { ResourceTimeline } from "~/components/ResourceTimeline.tsx"; +import { WORDING, parseSequence, resourceHref } from "~/resource.ts"; + +import type { ResourcePageQuery } from "./__generated__/ResourcePageQuery.graphql.ts"; +import type { ResourcePageRevisionQuery } from "./__generated__/ResourcePageRevisionQuery.graphql.ts"; + +import styles from "~/styles/resource.module.css"; + +const resourcePageQuery = graphql` + query ResourcePageQuery($id: ID!) @throwOnFieldError { + node(id: $id) { + ... on Resource @alias(as: "resource") { + id + iri + kind + currentRevision { + sequence + } + latest: revisions(first: 1) { + edges { + node { + sequence + } + } + } + ...ResourceTimeline_resource + } + } + } +`; + +const resourcePageRevisionQuery = graphql` + query ResourcePageRevisionQuery($id: ID!, $sequence: Int!) + @throwOnFieldError { + node(id: $id) { + ... on Resource @alias(as: "resource") { + revision(sequence: $sequence) { + ...ResourceRevision_revision + } + } + } + } +`; + +const loadResourcePageQuery = query( + (id: string) => + loadQuery(useRelayEnvironment()(), resourcePageQuery, { + id, + }), + "ResourcePageQuery", +); + +export const route = { + preload({ params }) { + if (params.id === undefined) { + throw new Error("Missing resource ID route parameter."); + } + return loadResourcePageQuery(params.id); + }, +} satisfies RouteDefinition; + +type RouteData = ReturnType; + +export default function ResourcePage(props: RouteSectionProps) { + return ( +
    + Resource — DrFed + + ← All instances + + + Unable to load this resource. Please reload the page to try again. +

    + } + > + Loading resource…}> + + +
    +
    + ); +} + +function ResourceContent(props: { data: RouteData }) { + const data = createPreloadedQuery( + resourcePageQuery, + () => props.data, + ); + const [search] = useSearchParams<{ revision?: string }>(); + const parameter = () => search.revision; + return ( + + Resource not found.

    }> + {(resource) => { + const latest = () => resource().latest.edges[0]?.node.sequence; + // The sequence to show; undefined when the parameter names none. + const shown = () => { + const value = parameter(); + return value === undefined ? latest() : parseSequence(value); + }; + return ( + <> + {resource().iri} — DrFed +
    +

    + {resource().kind === "unknown" + ? "Unresolved IRI" + : resource().kind} +

    +

    {resource().iri}

    + +
    + + +

    {WORDING.unknownKind}

    +
    + +

    No revisions to show

    +
    + +
    +
    +

    History

    + +
    +
    + + } + > + {(sequence) => ( + Loading revision…} + > + + + )} + +
    +
    +
    +
    + + ); + }} +
    +
    + ); +} + +/** + * The note that `revision` names no revision the viewer may read. + * @returns The heading and note. + */ +function MissingRevision(props: { id: string; parameter: string }) { + return ( + <> +

    Revision {props.parameter}

    +

    + {WORDING.missingRevision}{" "} + {WORDING.showLatest} +

    + + ); +} + +/** + * The revision with a sequence, read on its own so that the timeline keeps + * its loaded pages while another revision is chosen. + * @returns The revision, or the note that there is none to read. + */ +function RevisionPanel(props: { + id: string; + sequence: number; + /** The sequence of the current revision, if the viewer may read it. */ + head: number | undefined; +}) { + const data = createLazyLoadQuery( + resourcePageRevisionQuery, + () => ({ id: props.id, sequence: props.sequence }), + ); + return ( + + + } + > + {(revision) => ( + + )} + + + ); +} diff --git a/packages/web/src/styles/resource.module.css b/packages/web/src/styles/resource.module.css new file mode 100644 index 00000000..2f092e8f --- /dev/null +++ b/packages/web/src/styles/resource.module.css @@ -0,0 +1,405 @@ +/* +DrFed: A web-based platform for developing and debugging ActivityPub apps +Copyright (C) 2026 DrFed team + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ + +/* The resource page: a history rail beside the revision it shows. */ + +.page { + display: grid; + gap: 1.5rem; + min-width: 0; + padding-bottom: 3rem; +} +.backLink { + color: var(--ink-soft); + font-weight: 700; + justify-self: start; + text-decoration: none; +} +.page a { + color: var(--ink); + text-decoration-color: var(--accent-soft); + text-underline-offset: 0.2rem; +} +.page a:focus-visible, +.page summary:focus-visible, +.page button:focus-visible { + outline: 3px solid var(--accent-soft); + outline-offset: 0.2rem; +} +.header { + border-bottom: 1px solid var(--line); + min-width: 0; + padding-bottom: 1.25rem; +} +.header h1 { + font-family: var(--font-mono); + font-size: clamp(1.1rem, 3vw, 1.6rem); + margin: 0; + overflow-wrap: anywhere; +} +.label { + color: var(--accent-strong); + font-weight: 700; + margin: 0 0 0.5rem; +} +.panel { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + min-width: 0; + padding: clamp(1rem, 3vw, 1.75rem); +} +.panel h2 { + font-size: 1.3rem; + margin: 0 0 1rem; +} +.notice { + background: var(--surface-2); + border-left: 3px solid var(--accent-soft); + border-radius: var(--radius-sm); + margin: 1rem 0 0; + padding: 0.75rem 1rem; +} +.empty { + color: var(--ink-soft); + display: block; + margin: 0; +} +.faint { + color: var(--ink-faint); + font-family: var(--font-sans); + font-style: italic; +} +.sectionLabel { + color: var(--ink-soft); + font-size: var(--text-label); + font-weight: 700; + letter-spacing: var(--tracking-label); + margin: 1rem 0 0.5rem; + text-transform: uppercase; +} +.path { + color: var(--ink-soft); + font-family: var(--font-mono); + font-size: 0.8rem; + overflow-wrap: anywhere; +} +.iri { + font-family: var(--font-mono); + font-size: 0.85rem; + min-width: 0; + overflow-wrap: anywhere; +} +.position { + color: var(--ink-soft); + font-family: var(--font-mono); + font-size: 0.85rem; +} + +/* Pills. Source labels are all neutral and told apart by their words. */ +.pill, +.pillEmbedded { + border: 1px solid var(--line-strong); + border-radius: var(--radius-pill); + color: var(--ink-soft); + font-family: var(--font-sans); + font-size: 0.75rem; + font-style: normal; + font-weight: 700; + padding: 0.05rem 0.5rem; + white-space: nowrap; +} +.pillEmbedded { + border-color: var(--accent-soft); + color: var(--accent-strong); +} +.labels { + align-items: baseline; + display: inline-flex; + flex-wrap: wrap; + gap: 0.35rem 0.5rem; +} +.page .sourceLink { + color: var(--ink-soft); + font-family: var(--font-sans); + font-size: 0.8rem; + font-weight: 600; +} + +/* Layout. */ +.railLayout { + align-items: start; + display: grid; + gap: 1.5rem; + grid-template-columns: minmax(14rem, 17rem) minmax(0, 1fr); +} +.loadMore { + background: var(--card); + border: 1px solid var(--line-strong); + border-radius: var(--radius-sm); + color: var(--ink); + cursor: pointer; + font-weight: 700; + margin-top: 1rem; + padding: 0.5rem 1rem; +} +.loadMore:hover { + background: var(--surface-2); +} + +/* The timeline: dots on a line. */ +.timeline { + border-left: 2px solid var(--line-strong); + list-style: none; + margin: 0 0 0 0.45rem; + min-width: 0; + padding: 0; +} +.timeline > li { + padding: 0.5rem 0.5rem 0.5rem 1.1rem; + position: relative; +} +.revisionEntry { + display: grid; + gap: 0.1rem; + min-width: 0; +} +.timeline > .revisionEntry::before { + background: var(--card); + border: 2px solid var(--accent-soft); + border-radius: 50%; + content: ""; + height: 0.7rem; + left: -0.45rem; + position: absolute; + top: 0.85rem; + width: 0.7rem; +} +.timeline > .selectedEntry { + background: var(--surface-2); + border-radius: 0 var(--radius-sm) var(--radius-sm) 0; +} +.timeline > .selectedEntry::before { + background: var(--accent); + border-color: var(--accent); + box-shadow: 0 0 0 0.2rem var(--accent-tint); +} +.timeline > .whiteoutEntry::before { + border-color: var(--danger); +} +.timeline > .whiteoutEntry.selectedEntry::before { + background: var(--danger); +} +.timeline > .gapEntry { + border-left: 2px dashed var(--line-strong); + color: var(--ink-faint); + font-size: 0.85rem; + font-style: italic; + margin-left: -2px; +} +.entryLine { + align-items: baseline; + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.5rem; +} +.page .entrySequence { + font-family: var(--font-mono); + font-weight: 700; +} +.entryDetail { + color: var(--ink-soft); + font-family: var(--font-mono); + font-size: 0.75rem; + overflow-wrap: anywhere; +} + +/* A revision. */ +.revision { + display: grid; + gap: 1rem; + min-width: 0; +} +.revisionHeader h2 { + margin: 0; +} +.fields { + margin: 0.75rem 0 0; +} +.fields > div { + border-top: 1px solid var(--line); + display: grid; + gap: 1rem; + grid-template-columns: 8rem minmax(0, 1fr); + padding: 0.6rem 0; +} +.fields dt { + color: var(--ink-soft); + font-weight: 700; +} +.fields dd { + font-family: var(--font-mono); + font-size: 0.9rem; + margin: 0; + overflow-wrap: anywhere; +} + +/* Saved JSON. */ +.json { + border: 1px solid var(--line); + border-radius: var(--radius-sm); + margin-top: 0.75rem; + min-width: 0; + padding: 0.5rem 0.75rem; +} +.json > summary { + cursor: pointer; + font-weight: 700; +} +.json pre { + font-size: 0.8rem; + overflow-wrap: anywhere; + white-space: pre-wrap; +} + +/* Validator findings. */ +.diagnostics { + display: grid; + gap: 0.5rem; + list-style: none; + margin: 0.75rem 0 0; + padding: 0; +} +.diagnostics > li { + background: var(--surface-2); + border-left: 3px solid var(--warning); + border-radius: var(--radius-sm); + padding: 0.5rem 0.75rem; +} +.diagnostics > li.diagnosticError { + border-left-color: var(--danger); +} +.diagnostics p { + margin: 0; + overflow-wrap: anywhere; +} +.diagnosticHead { + align-items: baseline; + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.75rem; + margin-bottom: 0.25rem; +} +.diagnosticError .diagnosticHead strong { + color: var(--danger); +} +.diagnosticWarning .diagnosticHead strong { + color: var(--warning); +} + +/* Document nodes. */ +.rootNode { + min-width: 0; +} +.nodeHeader { + align-items: baseline; + display: flex; + flex-wrap: wrap; + gap: 0.35rem 0.6rem; + min-width: 0; +} +.nodeType { + font-family: var(--font-mono); + font-size: 1.05rem; + font-weight: 700; + overflow-wrap: anywhere; +} +.nodeSummary { + cursor: pointer; + list-style-position: outside; +} +.nodeSummary .nodeHeader { + display: inline-flex; +} +.nodeBody { + min-width: 0; +} +.groups { + display: grid; + gap: 0.75rem; + margin: 0; +} +.groups dt code { + font-weight: 700; +} +.groups dd { + margin: 0.25rem 0 0; + min-width: 0; +} +.values { + display: grid; + gap: 0.6rem; + list-style: none; + margin: 0; + padding: 0 0 0 1rem; +} +.value { + min-width: 0; +} +.valueLine { + align-items: baseline; + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.6rem; + min-width: 0; +} +.extensionValue { + background: var(--surface-2); + border-radius: var(--radius-sm); + font-family: var(--font-mono); + font-size: 0.8rem; + margin: 0; + overflow-wrap: anywhere; + padding: 0.5rem 0.75rem; + white-space: pre-wrap; +} + +/* An embedded document, joined to its parent by a guide line. */ +.embedded { + min-width: 0; +} +.embedded > .nodeBody { + border-left: 1px solid var(--line-strong); + margin-left: 0.4rem; + padding-left: 1rem; +} + +@media (max-width: 900px) { + .railLayout { + grid-template-columns: minmax(0, 1fr); + } + .railLayout > :first-child { + order: 2; + } +} +@media (max-width: 600px) { + .fields > div { + gap: 0.25rem; + grid-template-columns: 1fr; + } +} From 1b1a55169234979e8deeaed895c7f7320befebdc Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Tue, 17 Nov 2026 15:58:42 +0900 Subject: [PATCH 08/10] Open resource histories from existing pages The resource page could be reached only by its address. Its history is now linked from the pages that show resources: - Each object on an actor page links to its revision history. A filter above the list can include deleted objects, so that the histories of deleted objects can be reached too. Actor.objects takes a filter whose includeDeleted lists them, and Object.deleted tells when one was deleted. - An activity log entry linked to a stored activity links to the history of the activity and, when it is an object or an activity, to that of its object. Entries take three quarters of a row on the side of their direction instead of half of it. A Resource is now returned by node, Activity.object, and the resource of relations and recipients whenever the viewer may read one of its revisions, as the issue thread settled that a later restriction of the current resource must not conceal a revision that was readable. The typed node and Resource.detail still follow the current state. The node lookup tells a Resource node from the typed node sharing its ID by the typename of the global ID. The revision seed gains cases for these pages: listed objects with edits, a long history, and Create deliveries sent, received, and followed by a deletion. https://github.com/fedify-dev/drfed/issues/154 AI assistance: the maintainers chose where to link, the filter, and the layout, and asked Claude Code to implement them and to apply the issue thread's rule to Resource lookups. Claude Code wrote the GraphQL changes, their tests, the components, the seed cases, and the documentation and changelog. The new GraphQL tests were run and shown to fail without the change; the type check, lint, and formatter were run, and the seed was run against a temporary store. The full test suite was not completed, since its run overlapped a development server. Co-authored-by: Hyeonseo Kim Assisted-by: Claude Code:claude-opus-5-5 --- CHANGES.md | 7 +- changes.d/graphql/resource-revisions.md | 7 +- docs/internals/resource-revisions.md | 15 +- packages/graphql/README.md | 28 +- packages/graphql/src/builder.ts | 20 +- packages/graphql/src/object.test.ts | 60 ++++ packages/graphql/src/object.ts | 41 ++- packages/graphql/src/readable.ts | 116 +++++-- packages/graphql/src/resource.ts | 5 +- packages/graphql/src/revision.test.ts | 76 +++++ packages/graphql/src/revision.ts | 13 +- packages/models/src/relations.ts | 1 - .../web/src/components/ActivityLogBox.tsx | 33 ++ .../web/src/components/ActorObjectList.tsx | 99 +++++- .../web/src/components/FilterDisclosure.tsx | 72 +++++ .../web/src/styles/activity-log.module.css | 14 +- packages/web/src/styles/actor.module.css | 20 ++ packages/web/src/styles/filter.module.css | 58 ++++ scripts/seed-revisions/cases-links.mts | 295 ++++++++++++++++++ scripts/seed-revisions/main.mts | 2 + 20 files changed, 913 insertions(+), 69 deletions(-) create mode 100644 packages/web/src/components/FilterDisclosure.tsx create mode 100644 packages/web/src/styles/filter.module.css create mode 100644 scripts/seed-revisions/cases-links.mts diff --git a/CHANGES.md b/CHANGES.md index 22b9f588..d3d26a2b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -62,7 +62,12 @@ To be released. derived from it, and whether that revision is still current, superseded, or deleted; it is null when the viewer may not read that revision, and the embedded document itself stays readable. Deleting a resource or its - author hides none of its revisions by itself. [[#154]] + author hides none of its revisions by itself. A `Resource` is returned by + `node`, `Activity.object`, and relations and recipients whenever the + viewer may read one of its revisions, even after its current state was + restricted, while `Resource.detail` and the typed node stay hidden. + `Actor.objects` takes a `filter` whose `includeDeleted` lists deleted + objects too, and `Object.deleted` tells when one was deleted. [[#154]] - Fixed `Resource.detail` to return `null` without a field error when the resource has no corresponding detail record. [[#150], [#164] by Hong Minhee\] diff --git a/changes.d/graphql/resource-revisions.md b/changes.d/graphql/resource-revisions.md index 732b006c..aad16514 100644 --- a/changes.d/graphql/resource-revisions.md +++ b/changes.d/graphql/resource-revisions.md @@ -19,4 +19,9 @@ links: derived from it, and whether that revision is still current, superseded, or deleted; it is null when the viewer may not read that revision, and the embedded document itself stays readable. Deleting a resource or its - author hides none of its revisions by itself. [[#154]] + author hides none of its revisions by itself. A `Resource` is returned by + `node`, `Activity.object`, and relations and recipients whenever the + viewer may read one of its revisions, even after its current state was + restricted, while `Resource.detail` and the typed node stay hidden. + `Actor.objects` takes a `filter` whose `includeDeleted` lists deleted + objects too, and `Object.deleted` tells when one was deleted. [[#154]] diff --git a/docs/internals/resource-revisions.md b/docs/internals/resource-revisions.md index 1a759eb1..e7011663 100644 --- a/docs/internals/resource-revisions.md +++ b/docs/internals/resource-revisions.md @@ -296,6 +296,14 @@ resource does not hide an earlier public one. A Relay node lookup of a revision checks the revision itself, and `Resource.revisions` leaves out the ones the viewer may not read, so their sequences can skip. +The `Resource` a history is read through follows the same evidence, in +`readableResourceNode()`: a `node` lookup of a `Resource`, a relation's or +recipient's `resource`, and `Activity.object` return it when the viewer may +read it as `Resource.detail` decides or may read any of its revisions. A +`Resource` node shares its ID with the typed `Object` or `Activity` of the +same resource, so the lookup tells them apart by the typename of the global +ID; the typed node and `Resource.detail` keep following the current state. + What a revision embeds never decides whether it is readable. A local `Announce` that embeds a `Note` only one instance received is readable by anyone, as every local revision is, whether it records that `Note`'s revision @@ -312,8 +320,11 @@ same rule to a set of revisions for that check. Deletion hides no revision by itself: deleting a resource appends a whiteout, and its earlier revisions, like those of a resource whose author is deleted, stay readable by their own evidence. Only the existing fields, such as -`Resource.detail`, keep hiding deleted typed rows. A relation's or -recipient's `resource` is opened as `Activity.object` is, deleted or not. +`Resource.detail`, keep hiding deleted typed rows. `Actor.objects` leaves +deleted objects out unless its `filter` sets `includeDeleted`, which lists +them with `Object.deleted` so that their histories can be reached. A +relation's or recipient's `resource` is opened as `Activity.object` is, deleted +or not. `DocumentNode.source` tells where an embedded document came from: its `relation`, `snapshot` or `derived`, the source `revision`, and `status`, diff --git a/packages/graphql/README.md b/packages/graphql/README.md index 671ead6e..c9ac1488 100644 --- a/packages/graphql/README.md +++ b/packages/graphql/README.md @@ -75,9 +75,12 @@ when addressed to the public (section 5.6): `as:Public` and `Public` count as the public as well as its full IRI. What the viewer may not read is left out as if it did not exist: `node` and `nodes` -return null for it, as do `Resource.detail` and `Activity.object`, and -`Actor.objects`, `Object.activities`, and `Collection.items` leave it out -before paging, so that neither cursors nor `totalCount` tell of it. +return null for it, as does `Resource.detail`, and `Actor.objects`, +`Object.activities`, and `Collection.items` leave it out before paging, so +that neither cursors nor `totalCount` tell of it. A `Resource`, which a +history is read through, is returned by `node`, `Activity.object`, and the +`resource` of relations and recipients also when the viewer may read any of +its revisions; see below. [ActivityPub]: https://www.w3.org/TR/activitypub/ @@ -101,15 +104,18 @@ Each revision is read by evidence of its own: anyone reads local revisions, blind recipients included, and revisions addressed to the public; members of a local instance read what a delivery to it carried; and a revision without such evidence is readable only while it is current and its resource is, as -above. Where a revision's embedded documents came from never hides it. +above. A `Resource` with a revision the viewer may read is found even when +its current state is restricted, while its typed details stay hidden. +Where a revision's embedded documents came from never hides it. Deletion hides no revision by itself, while `Resource.detail` and the other -existing fields keep hiding what was deleted. `Resource.revision(sequence:)` -returns one revision by its sequence. `DocumentNode.source` names the -revision an embedded document came from, whether it keeps that revision's -contents or was derived from it, and whether that revision is still current, -superseded, or deleted; it is null when the viewer may not read the source -revision, and nothing else of the document changes. See -[resource revision internals]. +existing fields keep hiding what was deleted; `Actor.objects` lists deleted +objects, with `Object.deleted`, only when its filter sets `includeDeleted`. +`Resource.revision(sequence:)` returns one revision by its sequence. +`DocumentNode.source` names the revision an embedded document came from, +whether it keeps that revision's contents or was derived from it, and whether +that revision is still current, superseded, or deleted; it is null when the +viewer may not read the source revision, and nothing else of the document +changes. See [resource revision internals]. `unreadableRevisions(viewer, ids)` in `@drfed/graphql/readable` tells which revisions a viewer may not read by the same rule. Pass it to diff --git a/packages/graphql/src/builder.ts b/packages/graphql/src/builder.ts index fb27a857..bb0d9306 100644 --- a/packages/graphql/src/builder.ts +++ b/packages/graphql/src/builder.ts @@ -177,13 +177,17 @@ export const builder = new SchemaBuilder({ relay: { nodeQueryOptions: { resolve: async (_, { id }, ctx, __, resolveNode) => { - const [node] = await hideHiddenNodes(ctx, [await resolveNode(id)]); + const [node] = await hideHiddenNodes( + ctx, + [id], + [await resolveNode(id)], + ); return node; }, }, nodesQueryOptions: { resolve: async (_, { ids }, ctx, __, resolveNodes) => - await hideHiddenNodes(ctx, await resolveNodes(ids)), + await hideHiddenNodes(ctx, ids, await resolveNodes(ids)), }, }, scopeAuth: { @@ -223,11 +227,16 @@ const filterDeleted = (node: unknown): unknown => ? null : node; -// A node that belongs to a resource, such as a revision, is hidden as that -// resource is, by hideUnreadableNodes(); its own deletion time, as that of a -// whiteout, tells of the history it records and hides nothing. +const RESOURCE_TYPENAME = "Resource"; + +// A node that belongs to a resource, such as a revision, is hidden by its own +// readability, by hideUnreadableNodes(); its own deletion time, as that of a +// whiteout, tells of the history it records and hides nothing. A `Resource` +// node, which shares its ID with the typed node of the same resource, is +// told apart by the typename its global ID names. const hideHiddenNodes = ( context: UserContext, + ids: readonly { readonly typename: string }[], nodes: readonly unknown[], ): Promise => hideUnreadableNodes( @@ -235,6 +244,7 @@ const hideHiddenNodes = ( nodes.map((node) => owningResourceOf(node) == null ? filterDeleted(node) : node, ), + ids.map(({ typename }) => typename === RESOURCE_TYPENAME), ); /** diff --git a/packages/graphql/src/object.test.ts b/packages/graphql/src/object.test.ts index e63c993d..21692d52 100644 --- a/packages/graphql/src/object.test.ts +++ b/packages/graphql/src/object.test.ts @@ -627,6 +627,66 @@ describe("Actor.objects", () => { assert.deepEqual(previous.data.node.objects.edges, connection.edges); }); }); + + it("lists deleted objects too when the filter includes them", async () => { + await withTestHarness(async ({ db, post }) => { + await seedLocalActor(db); + const [liveId, deletedId] = [uuid(), uuid()]; + const deleted = Temporal.Instant.from("2026-02-01T00:00:00Z"); + await seedObjects( + db, + [liveId, deletedId].map((id, index) => ({ + id, + actorId: localActorId, + type: "Note" as const, + iri: `https://test.example/${id}`, + contentHtml: "test", + published: Temporal.Instant.from( + index === 0 ? "2026-01-02T00:00:00Z" : "2026-01-01T00:00:00Z", + ), + deleted: id === deletedId ? deleted : null, + })), + ); + const query = `query($actor: ID!, $filter: ActorObjectFilter) { + node(id: $actor) { ... on Actor { + objects(first: 10, filter: $filter) { + totalCount edges { node { uuid deleted } } + } + } } + }`; + const list = async (filter: unknown) => + await ( + await post({ + query, + variables: { actor: globalId("Actor", localActorId), filter }, + }) + ).json(); + const live = { node: { uuid: liveId, deleted: null } }; + for (const filter of [null, {}, { includeDeleted: false }]) { + assert.deepEqual(await list(filter), { + data: { node: { objects: { totalCount: 1, edges: [live] } } }, + }); + } + assert.deepEqual(await list({ includeDeleted: true }), { + data: { + node: { + objects: { + totalCount: 2, + edges: [ + live, + { + node: { + uuid: deletedId, + deleted: "2026-02-01T00:00:00Z", + }, + }, + ], + }, + }, + }, + }); + }); + }); }); describe("Query.node", () => { diff --git a/packages/graphql/src/object.ts b/packages/graphql/src/object.ts index 1fdfcb2a..2e4c5b78 100644 --- a/packages/graphql/src/object.ts +++ b/packages/graphql/src/object.ts @@ -125,6 +125,15 @@ const ObjectRef = builder.drizzleNode("objects", { description: "The time the object was stored in DrFed, distinct from its publication time.", }), + deleted: t.expose("deleted", { + type: "DateTime", + nullable: true, + description: + "When the object was deleted, or null while it is not. Only " + + "`Actor.objects` returns deleted objects, when its filter includes " + + "them; its revisions, a whiteout last, stay readable through " + + "`resource`.", + }), }), }); export const ActivityPubObject: DrFedObjectRef = ObjectRef; @@ -164,9 +173,28 @@ builder.drizzleObjectField("objects", "activities", (t) => }), ); +const ActorObjectFilter = builder.inputType("ActorObjectFilter", { + description: "Narrows the objects `Actor.objects` lists.", + fields: (t) => ({ + includeDeleted: t.boolean({ + required: true, + defaultValue: false, + description: + "Whether deleted objects are listed too, so that their histories " + + "can be inspected.", + }), + }), +}); +type ObjectFilter = typeof ActorObjectFilter.$inferInput | null | undefined; +const includesDeleted = (filter: ObjectFilter): boolean => + filter?.includeDeleted === true; + const objectsConnection = drizzleConnectionHelpers(builder, "objects", { - query: (_, ctx) => ({ - where: { RAW: (table) => readableResource(ctx, table.id) }, + query: ({ filter }: { filter?: ObjectFilter }, ctx) => ({ + where: { + ...(includesDeleted(filter) ? {} : { deleted: { isNull: true } }), + RAW: (table) => readableResource(ctx, table.id), + }, orderBy: { published: "desc", id: "desc" }, }), }); @@ -174,8 +202,9 @@ builder.drizzleObjectField("actors", "objects", (t) => t.connection( { type: ActivityPubObject, + args: { filter: t.arg({ type: ActorObjectFilter }) }, description: - "Non-deleted objects the viewer may read, newest publication first. A local actor's objects are readable whatever their addressing; see `Object` for a remote actor's.", + "Objects the viewer may read, newest publication first, without deleted ones unless the filter includes them. A local actor's objects are readable whatever their addressing; see `Object` for a remote actor's.", select(args, ctx, nestedSelection) { return { with: { @@ -191,7 +220,9 @@ builder.drizzleObjectField("actors", "objects", (t) => schema.objects, and( eq(schema.objects.actorId, actor.id), - isNull(schema.objects.deleted), + includesDeleted(args.filter) + ? undefined + : isNull(schema.objects.deleted), readableResource(ctx, schema.objects.id), ), ); @@ -204,7 +235,7 @@ builder.drizzleObjectField("actors", "objects", (t) => fields: (fb) => ({ totalCount: fb.int({ description: - "The number of non-deleted objects authored by this actor that the viewer may read.", + "The number of objects authored by this actor that the viewer may read, counted with the same filter as the list.", resolve: (connection) => connection.totalCount(), }), }), diff --git a/packages/graphql/src/readable.ts b/packages/graphql/src/readable.ts index 1c6e89d5..a696825b 100644 --- a/packages/graphql/src/readable.ts +++ b/packages/graphql/src/readable.ts @@ -134,6 +134,7 @@ const evidencedAddressing = alias(revisionAddressing, "evidenced_addressing"); const evidencedReceipts = alias(revisionReceipts, "evidenced_receipts"); const receiptDeliveries = alias(activityDeliveries, "receipt_deliveries"); const evidencedHeads = alias(resourceHeads, "evidenced_heads"); +const listedRevisions = alias(resourceRevisions, "listed_revisions"); const remoteActivity = (id: SQLWrapper): SQL => sql`exists ( select 1 from ${activities} ${remoteActivities} @@ -326,6 +327,27 @@ export function readableRevision(viewer: Viewer, id: SQLWrapper): SQL { )`; } +/** + * Restricts resources to those the viewer may know of as `Resource` nodes: + * those {@link readableResource} lets the viewer read, and those with a + * revision the viewer may read, as {@link readableRevision} tells. A + * resource's current state, which its legacy typed row describes, may be + * restricted after an earlier revision was public or received; that hides + * neither the revision nor the resource it is read through. The typed + * details of the resource still follow {@link readableResource}. + * @param viewer The viewer and the database. + * @param id The resource ID in an outer query. + * @returns The condition on the ID. + */ +export function readableResourceNode(viewer: Viewer, id: SQLWrapper): SQL { + if (viewer.account?.admin === true) return sql`true`; + return sql`(${readableResource(viewer, id)} or exists ( + select 1 from ${resourceRevisions} ${listedRevisions} + where ${listedRevisions.resourceId} = ${id} + and ${readableRevision(viewer, listedRevisions.id)} + ))`; +} + /** * Finds the revisions among the given IDs that the viewer may not read, as * {@link readableRevision} decides. IDs of no stored revision are never @@ -383,6 +405,39 @@ export const isReadableResource = async ( id: Uuid, ): Promise => !(await unreadableResources(viewer, [id])).has(id); +/** + * Finds the resources among the given IDs that the viewer may not know of as + * `Resource` nodes, as {@link readableResourceNode} decides. IDs of anything + * but a resource are never among them. + * @returns The IDs the viewer may not know of. + */ +export async function unreadableResourceNodes( + viewer: Viewer, + ids: readonly Uuid[], +): Promise> { + if (ids.length === 0 || viewer.account?.admin === true) return new Set(); + const rows = await viewer.db + .select({ id: resources.id }) + .from(resources) + .where( + and( + inArray(resources.id, [...new Set(ids)]), + not(readableResourceNode(viewer, resources.id)), + ), + ); + return new Set(rows.map(({ id }) => id)); +} + +/** + * Determines whether the viewer may know of the resource as a `Resource` + * node. + * @returns Whether {@link readableResourceNode} holds for it. + */ +export const isReadableResourceNode = async ( + viewer: Viewer, + id: Uuid, +): Promise => !(await unreadableResourceNodes(viewer, [id])).has(id); + const uuidOf = (node: unknown, key: "id" | "resourceId"): Uuid | null => node != null && typeof node === "object" && @@ -401,40 +456,57 @@ const uuidOf = (node: unknown, key: "id" | "resourceId"): Uuid | null => export const owningResourceOf = (node: unknown): Uuid | null => uuidOf(node, "resourceId"); +/** How {@link hideUnreadableNodes} checks a node. */ +type NodeKind = "revision" | "resource" | "typed"; + /** * Replaces the Relay nodes the viewer may not read by null, as if they did - * not exist. Activities, objects, and resources share their IDs, so a node's - * ID alone tells whether it is one the viewer may not read; a node that - * belongs to a resource, such as a revision, is checked by - * {@link readableRevision} instead, as {@link owningResourceOf} tells. + * not exist. Activities, objects, and resources share their IDs, so the + * caller tells which nodes are `Resource` nodes, which are checked by + * {@link readableResourceNode}; the ID of any other node tells whether + * {@link readableResource} lets the viewer read it. A node that belongs to a + * resource, such as a revision, is checked by {@link readableRevision} + * instead, as {@link owningResourceOf} tells. + * @param viewer The viewer and the database. + * @param nodes The resolved nodes. + * @param resourceNodes Whether the node at each index is a `Resource` node. * @returns The nodes, in the same order. */ export async function hideUnreadableNodes( viewer: Viewer, nodes: readonly unknown[], + resourceNodes: readonly boolean[] = [], ): Promise { - const revisionIds = nodes.map((node) => - owningResourceOf(node) == null ? null : uuidOf(node, "id"), - ); - const ids = nodes.map((node) => - owningResourceOf(node) == null ? uuidOf(node, "id") : null, - ); - const [hidden, hiddenRevisions] = await Promise.all([ - unreadableResources( - viewer, - ids.filter((id) => id != null), - ), - unreadableRevisions( - viewer, - revisionIds.filter((id) => id != null), - ), + const kindOf = (node: unknown, index: number): NodeKind => + owningResourceOf(node) != null + ? "revision" + : resourceNodes[index] === true + ? "resource" + : "typed"; + const kinds = nodes.map((node, index) => kindOf(node, index)); + const idsOf = (kind: NodeKind) => + nodes.map((node, index) => + kinds[index] === kind ? uuidOf(node, "id") : null, + ); + const ids = { + revision: idsOf("revision"), + resource: idsOf("resource"), + typed: idsOf("typed"), + }; + const present = (list: readonly (Uuid | null)[]) => + list.filter((id) => id != null); + const [hiddenTyped, hiddenResources, hiddenRevisions] = await Promise.all([ + unreadableResources(viewer, present(ids.typed)), + unreadableResourceNodes(viewer, present(ids.resource)), + unreadableRevisions(viewer, present(ids.revision)), ]); return nodes.map((node, index) => { - if (owningResourceOf(node) != null) { - const id = revisionIds[index]; + const kind: NodeKind = kinds[index] ?? "typed"; + const id = ids[kind][index]; + if (kind === "revision") { return id == null || hiddenRevisions.has(id) ? null : node; } - const id = ids[index]; + const hidden = kind === "resource" ? hiddenResources : hiddenTyped; return id != null && hidden.has(id) ? null : node; }); } diff --git a/packages/graphql/src/resource.ts b/packages/graphql/src/resource.ts index 6a2c7f52..6ba5ffd7 100644 --- a/packages/graphql/src/resource.ts +++ b/packages/graphql/src/resource.ts @@ -32,6 +32,7 @@ import { import { type Viewer, isReadableResource, + isReadableResourceNode, readableResource, visibleResource, } from "./readable.ts"; @@ -357,10 +358,10 @@ const ActivityRef = builder.drizzleNode("activities", { nullable: true, description: "The resource the activity acts on, or null when there is none or " + - "the viewer may not read it.", + "the viewer may read neither it nor any of its revisions.", select: { with: { object: true } }, resolve: async (row, _, ctx) => - row.object != null && (await isReadableResource(ctx, row.object.id)) + row.object != null && (await isReadableResourceNode(ctx, row.object.id)) ? row.object : null, }), diff --git a/packages/graphql/src/revision.test.ts b/packages/graphql/src/revision.test.ts index 7d6a56b4..40001ec8 100644 --- a/packages/graphql/src/revision.test.ts +++ b/packages/graphql/src/revision.test.ts @@ -1378,6 +1378,82 @@ describe("Access to revisions by their own evidence", () => { }); }); +describe("Resource nodes read through their revisions", () => { + // The rule for a remote resource with a legacy typed row follows its + // current state, which no delivery to the viewer's workspace opens here; + // only a receipt opens its revision. + it("finds a resource by a revision the viewer may read, but not its typed details", async () => { + await withWriter(async ({ harness, query }) => { + const { db } = harness; + await seedRemoteActor(db); + const workspaceB = await seedWorkspace(db); + const memberB = await seedViewer(db, { memberOf: workspaceB }); + const outsider = await seedViewer(db); + const remoteId = uuidV7(); + const iri = `https://remote.example.com/notes/${remoteId}`; + const document = { type: "Note", content: "private" }; + await seedObjects(db, { + id: remoteId, + actorId: remoteActorId, + type: "Note", + iri, + contentHtml: "private", + document, + addressing: { to: [CAROL] }, + }); + const revision = await db.transaction((tx) => + captureLegacyResourceRevision(tx, remoteId), + ); + await receipt(db, revision, workspaceB); + const like = await embed(db, "Like", { ...document, id: iri }); + const read = `query($id: ID!, $typed: ID!, $like: ID!) { + node(id: $id) { ... on Resource { + iri + detail { __typename } + revisions { edges { node { sequence document } } } + } } + typed: node(id: $typed) { ... on Object { uuid } } + nodes(ids: [$id, $typed]) { id } + like: node(id: $like) { ... on Resource { currentRevision { root { + relations(property: object) { resource { iri } } + } } } } + }`; + const variables = { + id: globalId("Resource", remoteId), + typed: globalId("Object", remoteId), + like: globalId("Resource", like.resourceId), + }; + const relations = (resource: unknown) => ({ + currentRevision: { root: { relations: [{ resource }] } }, + }); + assert.deepEqual(await query(read, variables, memberB.auth), { + data: { + node: { + iri, + // The typed details follow the rule of the current state. + detail: null, + revisions: { edges: [{ node: { sequence: 1, document } }] }, + }, + typed: null, + nodes: [{ id: variables.id }, null], + like: relations({ iri }), + }, + }); + // Without a revision to read, nothing tells of the resource. + for (const init of [undefined, outsider.auth]) { + assert.deepEqual(await query(read, variables, init), { + data: { + node: null, + typed: null, + nodes: [null, null], + like: relations(null), + }, + }); + } + }); + }); +}); + describe("DocumentNode.source", () => { const source = `query($id: ID!) { node(id: $id) { ... on Resource { currentRevision { root { source { relation } relations(property: object) { diff --git a/packages/graphql/src/revision.ts b/packages/graphql/src/revision.ts index 50a87ba0..c77b49cc 100644 --- a/packages/graphql/src/revision.ts +++ b/packages/graphql/src/revision.ts @@ -38,7 +38,7 @@ import type { Uuid } from "@drfed/models/uuid"; import { and, eq, inArray } from "drizzle-orm"; import builder, { type DrFedObjectRef, type UserContext } from "./builder.ts"; -import { readableResource, readableRevision } from "./readable.ts"; +import { readableResourceNode, readableRevision } from "./readable.ts"; import { Resource } from "./resource.ts"; const ACTIVITY_STREAMS = "https://www.w3.org/ns/activitystreams#"; @@ -209,8 +209,8 @@ const resourceLookups = new WeakMap< /** * Finds the resource registered under an IRI, as `Activity.object` opens - * it: only when the viewer may read it. A deleted one is found too, since - * its revisions stay readable. Lookups are shared within a request, since + * it: only when the viewer may read it or one of its revisions. A deleted + * one is found too, since its revisions stay readable. Lookups are shared within a request, since * a document may name one IRI many times. * @returns The resource, or null. */ @@ -230,7 +230,7 @@ function registeredResource( (await ctx.db.query.resources.findFirst({ where: { iri, - RAW: (table) => readableResource(ctx, table.id), + RAW: (table) => readableResourceNode(ctx, table.id), }, })) ?? null)(); lookups.set(iri, lookup); @@ -380,8 +380,9 @@ const occurrenceFields = { "with a compact IRI expanded; null for an anonymous embedded value.", resource: "The resource currently registered under `iri`, or null when there is " + - "none, or when the viewer may not read it. A deleted resource is " + - "returned too, since its revisions stay readable. It is never fetched.", + "none, or when the viewer may read neither it nor any of its " + + "revisions. A deleted resource is returned too, since its revisions " + + "stay readable. It is never fetched.", } as const; DocumentRelation.implement({ diff --git a/packages/models/src/relations.ts b/packages/models/src/relations.ts index ee770ec5..e848c384 100644 --- a/packages/models/src/relations.ts +++ b/packages/models/src/relations.ts @@ -423,7 +423,6 @@ export const relations = defineRelations(schema, (r) => ({ objects: r.many.objects({ from: r.actors.id, to: r.objects.actorId, - where: { deleted: { isNull: true } }, }), instance: r.one.instances({ from: r.actors.instanceId, diff --git a/packages/web/src/components/ActivityLogBox.tsx b/packages/web/src/components/ActivityLogBox.tsx index 2e36e96f..9601cc39 100644 --- a/packages/web/src/components/ActivityLogBox.tsx +++ b/packages/web/src/components/ActivityLogBox.tsx @@ -14,10 +14,13 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +import { A } from "@solidjs/router"; import { graphql } from "relay-runtime"; import { For, Show, createMemo, createSignal } from "solid-js"; import { createFragment } from "solid-relay"; +import { resourceHref } from "~/resource.ts"; + import type { ActivityLogBox_log$key } from "./__generated__/ActivityLogBox_log.graphql.ts"; import { ActivityLogSource } from "./ActivityLogSource.tsx"; import { CopyButton } from "./CopyButton.tsx"; @@ -46,6 +49,15 @@ export function ActivityLogBox(props: { $log: ActivityLogBox_log$key }) { created payload rawBody + activity { + resource { + id + } + object { + id + kind + } + } } `, () => props.$log, @@ -117,6 +129,27 @@ export function ActivityLogBox(props: { $log: ActivityLogBox_log$key }) { + + {(activity) => ( +

    + + Activity history + + + {(object) => ( + Object history + )} + +

    + )} +

    {log().direction === "inbound" && log().payload == undefined ? "Raw received body" diff --git a/packages/web/src/components/ActorObjectList.tsx b/packages/web/src/components/ActorObjectList.tsx index c44dfc9e..83221be6 100644 --- a/packages/web/src/components/ActorObjectList.tsx +++ b/packages/web/src/components/ActorObjectList.tsx @@ -14,24 +14,38 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +import { A } from "@solidjs/router"; import { graphql } from "relay-runtime"; -import { For, Show } from "solid-js"; -import { createFragment } from "solid-relay"; +import { For, Show, createSignal } from "solid-js"; +import { createRefetchableFragment } from "solid-relay"; + +import { resourceHref } from "~/resource.ts"; import type { ActorObjectList_actor$key } from "./__generated__/ActorObjectList_actor.graphql.ts"; +import type { ActorObjectListRefetchQuery } from "./__generated__/ActorObjectListRefetchQuery.graphql.ts"; import { CopyButton } from "./CopyButton.tsx"; +import { FilterCheckbox, FilterDisclosure } from "./FilterDisclosure.tsx"; import styles from "~/styles/actor.module.css"; /** - * Displays an actor's latest objects with their raw HTML content. + * Displays an actor's latest objects with their raw HTML content, and those + * it deleted when the filter asks for them. * @returns The object list or its empty state. */ export function ActorObjectList(props: { $actor: ActorObjectList_actor$key }) { - const data = createFragment( + const [data, refetch] = createRefetchableFragment< + ActorObjectListRefetchQuery, + ActorObjectList_actor$key + >( graphql` - fragment ActorObjectList_actor on Actor @throwOnFieldError { - objects(first: 20) { + fragment ActorObjectList_actor on Actor + @throwOnFieldError + @argumentDefinitions( + includeDeleted: { type: "Boolean", defaultValue: false } + ) + @refetchable(queryName: "ActorObjectListRefetchQuery") { + objects(first: 20, filter: { includeDeleted: $includeDeleted }) { edges { node { id @@ -39,7 +53,11 @@ export function ActorObjectList(props: { $actor: ActorObjectList_actor$key }) { name contentHtml published + deleted iri + resource { + id + } } } } @@ -47,12 +65,48 @@ export function ActorObjectList(props: { $actor: ActorObjectList_actor$key }) { `, () => props.$actor, ); + const [includeDeleted, setIncludeDeleted] = createSignal(false); + const [pending, setPending] = createSignal(false); + const [failed, setFailed] = createSignal(false); + function filterDeleted(checked: boolean) { + setIncludeDeleted(checked); + setPending(true); + setFailed(false); + refetch( + { includeDeleted: checked }, + { + fetchPolicy: "store-and-network", + onComplete(error) { + setPending(false); + setFailed(error != undefined); + }, + }, + ); + } return ( - + {(actor) => (

    -

    Objects

    +
    +

    Objects

    + + + +
    + + Loading objects… + + + + 0} fallback={

    No objects yet.

    } @@ -62,10 +116,29 @@ export function ActorObjectList(props: { $actor: ActorObjectList_actor$key }) { {(edge) => ( {(object) => ( -
  • +
  • -

    {object().type}

    +

    + {object().type} + + {(deleted) => ( + + {" "} + · Deleted{" "} + + + )} + +

    {object().name ?? "Untitled object"}

    @@ -76,6 +149,12 @@ export function ActorObjectList(props: { $actor: ActorObjectList_actor$key }) { label="object IRI" />
    + + Revision history + diff --git a/packages/web/src/components/FilterDisclosure.tsx b/packages/web/src/components/FilterDisclosure.tsx new file mode 100644 index 00000000..40d24f70 --- /dev/null +++ b/packages/web/src/components/FilterDisclosure.tsx @@ -0,0 +1,72 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import { type JSX, Show } from "solid-js"; + +import styles from "~/styles/filter.module.css"; + +/** + * A disclosure above a list that opens the conditions it is filtered by. + * @returns The disclosure, with the number of active conditions on its + * toggle. + */ +export function FilterDisclosure(props: { + /** What the conditions filter, for the group's accessible name. */ + label: string; + /** How many conditions differ from their defaults. */ + active: number; + children: JSX.Element; +}) { + return ( +
    + + Filter + 0}> + ({props.active}) + + +
    + Show in {props.label} + {props.children} +
    +
    + ); +} + +/** + * One checkbox condition of a {@link FilterDisclosure}. + * @returns The labelled checkbox. + */ +export function FilterCheckbox(props: { + label: string; + checked: boolean; + disabled?: boolean; + onChange: (checked: boolean) => void; +}) { + return ( + + ); +} diff --git a/packages/web/src/styles/activity-log.module.css b/packages/web/src/styles/activity-log.module.css index 2bb5f357..15f7a0fc 100644 --- a/packages/web/src/styles/activity-log.module.css +++ b/packages/web/src/styles/activity-log.module.css @@ -32,9 +32,11 @@ along with this program. If not, see . gap: 0.75rem; } +/* Each entry takes three quarters of the row, on the side of its direction, + so that the two directions stay apart without leaving half a row empty. */ .row { display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1rem; } @@ -43,11 +45,11 @@ along with this program. If not, see . } .incoming { - grid-column: 1; + grid-column: 1 / span 3; } .outgoing { - grid-column: 2; + grid-column: 2 / span 3; } .box { @@ -70,6 +72,12 @@ along with this program. If not, see . display: block; } +.resourceLinks { + display: flex; + flex-wrap: wrap; + gap: 0.5rem 1rem; +} + .source pre { white-space: pre-wrap; overflow-wrap: anywhere; diff --git a/packages/web/src/styles/actor.module.css b/packages/web/src/styles/actor.module.css index 558ba9fc..93ab992a 100644 --- a/packages/web/src/styles/actor.module.css +++ b/packages/web/src/styles/actor.module.css @@ -63,6 +63,13 @@ along with this program. If not, see . margin: 0; font-size: 1.3rem; } +.panelHeader { + display: flex; + flex-wrap: wrap; + align-items: start; + justify-content: space-between; + gap: 0.75rem 1rem; +} .fields { margin: 1.25rem 0 0; } @@ -154,6 +161,11 @@ along with this program. If not, see . grid-column: 1 / -1; min-width: 0; } +.objectHistory { + grid-column: 1 / -1; + justify-self: start; + font-size: 0.8rem; +} .objectIri { flex: 1; min-width: 0; @@ -177,6 +189,14 @@ along with this program. If not, see . .objectContent code { font: inherit; } +.deletedObject .objectContent { + border-left-color: var(--line-strong); + color: var(--ink-soft); +} +.deletedLabel { + color: var(--ink-soft); + font-weight: 400; +} .objectEmpty { color: var(--ink-soft); margin: 1.25rem 0 0; diff --git a/packages/web/src/styles/filter.module.css b/packages/web/src/styles/filter.module.css new file mode 100644 index 00000000..4ca840fa --- /dev/null +++ b/packages/web/src/styles/filter.module.css @@ -0,0 +1,58 @@ +/* +DrFed: A web-based platform for developing and debugging ActivityPub apps +Copyright (C) 2026 DrFed team + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ + +.filter { + position: relative; +} +.toggle { + cursor: pointer; + display: inline-block; + border: 1px solid var(--line-strong); + border-radius: var(--radius-sm); + padding: 0.35rem 0.75rem; + color: var(--ink); + font-size: 0.85rem; + font-weight: 700; +} +.toggle:focus-visible { + outline: 3px solid var(--accent-soft); + outline-offset: 0.2rem; +} +.count { + color: var(--accent-strong); +} +.conditions { + display: grid; + gap: 0.5rem; + margin: 0.75rem 0 0; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 0.75rem 1rem; +} +.legend { + padding: 0 0.25rem; + color: var(--ink-soft); + font-size: 0.8rem; + font-weight: 700; +} +.condition { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.9rem; +} diff --git a/scripts/seed-revisions/cases-links.mts b/scripts/seed-revisions/cases-links.mts new file mode 100644 index 00000000..050f8c3d --- /dev/null +++ b/scripts/seed-revisions/cases-links.mts @@ -0,0 +1,295 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// The pages that link to a resource page read legacy typed rows: the actor +// page lists objects, and the activity log links a delivery to its stored +// `Create`. The common write stores revisions only, so these cases create +// objects as the `createObject` mutation does, and record the deliveries of +// their `Create`s directly, as no path delivers between seeded instances. +// +// Keep dependent database writes sequential. +// oxlint-disable no-await-in-loop + +import { + type JsonObject, + type LegacyObjectInput, + createLegacyObject, + isLocalWriteError, +} from "@drfed/federation/local-write"; +import { type Database, schema } from "@drfed/models"; +import { PUBLIC_IRI } from "@drfed/models/resource"; +import { type Uuid, uuidV7 } from "@drfed/models/uuid"; + +import { + type CaseContext, + type SeedCase, + type SeededResource, +} from "./case.mts"; +import type { Workspace } from "./environment.mts"; +import { loadHead } from "./writer.mts"; + +/** More edits than the timeline loads at once, which is 20 revisions. */ +const LONG_HISTORY_EDITS = 24; +const ACCEPTED = 202; +const SERVER_ERROR = 500; + +/** A legacy object with its `Create`. */ +interface LegacyNote { + readonly object: SeededResource; + readonly create: SeededResource; +} + +/** How an outbound delivery ended. */ +interface Outcome { + readonly status: "sent" | "failed"; + readonly statusCode: number; + readonly error?: string; +} + +/** + * Reads the IRI of a resource. + * @returns The labelled resource. + */ +async function resourceOf( + db: Database, + label: string, + id: Uuid, +): Promise { + const resource = await db.query.resources.findFirst({ where: { id } }); + if (resource == null) throw new Error(`No resource ${id}.`); + return { label, id, iri: resource.iri }; +} + +/** + * Creates a public object of workspace A as the `createObject` mutation + * does, so that it is listed on the actor page. + * @returns The object and its `Create`. + */ +async function createLegacy( + { db, env, alice }: CaseContext, + label: string, + input: Pick, +): Promise { + const created = await createLegacyObject( + env, + { accountId: alice.member.accountId }, + { + actorId: alice.actorId, + summary: null, + language: null, + sensitive: false, + addressing: { to: [PUBLIC_IRI] }, + ...input, + }, + ); + if (isLocalWriteError(created)) throw new Error(JSON.stringify(created)); + if (created.activityId == null) throw new Error("Missing the Create."); + return { + object: await resourceOf(db, label, created.id), + create: await resourceOf(db, `Create of the ${label}`, created.activityId), + }; +} + +/** + * Edits a legacy object's content once for each of the given versions. + */ +async function editContents( + { writer }: CaseContext, + objectId: Uuid, + contents: readonly string[], +): Promise { + for (const content of contents) { + await writer.edit(objectId, { content: `

    ${content}

    ` }); + } +} + +/** + * Reads the inbox of a workspace's actor. + * @returns The inbox URL. + */ +async function inboxOf(db: Database, { actorId }: Workspace): Promise { + const actor = await db.query.actors.findFirst({ where: { id: actorId } }); + if (actor == null) throw new Error(`No actor ${actorId}.`); + return actor.inboxUrl; +} + +/** + * The `Create` as DrFed delivers it: its saved document without blind + * recipients. + * @returns The payload. + */ +async function payloadOf(db: Database, createId: Uuid): Promise { + const { + bto: _bto, + bcc: _bcc, + ...payload + } = (await loadHead(db, createId)).document; + return payload; +} + +/** + * Records that workspace A sent a `Create` to the actor of another + * workspace, and, when it was sent, that the other workspace received it. + */ +async function recordDelivery( + { db, alice }: CaseContext, + { object, create }: LegacyNote, + recipient: Workspace, + outcome: Outcome, +): Promise { + const payload = await payloadOf(db, create.id); + const inboxUrl = await inboxOf(db, recipient); + const completed = Temporal.Now.instant(); + const common = { + type: "Create", + types: ["Create"], + activityIri: create.iri, + activityId: create.id, + objectType: "Note", + objectIri: object.iri, + inboxUrl, + requestUrl: inboxUrl, + payload, + completed, + } satisfies Partial; + await db.insert(schema.activityDeliveries).values({ + ...common, + id: uuidV7(), + instanceId: alice.instanceId, + actorId: alice.actorId, + direction: "outbound", + status: outcome.status, + statusCode: outcome.statusCode, + error: outcome.error ?? null, + recipientIris: [recipient.actorIri], + }); + if (outcome.status !== "sent") return; + await db.insert(schema.activityDeliveries).values({ + ...common, + id: uuidV7(), + instanceId: recipient.instanceId, + actorId: recipient.actorId, + direction: "inbound", + status: "received", + verificationMechanism: "http_signature", + verificationResult: "verified", + carriedSnapshot: true, + carriedObjectSnapshot: true, + remoteActorIri: alice.actorIri, + remoteHost: alice.host, + body: Buffer.from(JSON.stringify(payload)), + statusCode: ACCEPTED, + }); +} + +const listedObjects: SeedCase = async (context) => { + const note = await createLegacy(context, "Note", { + type: "Note", + contentHtml: "

    Listed, first version

    ", + name: null, + }); + await editContents(context, note.object.id, [ + "Listed, second version", + "Listed, third version", + ]); + const article = await createLegacy(context, "Article", { + type: "Article", + contentHtml: "

    An article, first version

    ", + name: "A titled article", + }); + await editContents(context, article.object.id, [ + "An article, second version", + ]); + return { + number: 21, + title: + "Objects on A's actor page with Revision history links: " + + "a Note edited twice and an Article edited once", + resources: [note.object, article.object], + }; +}; + +const longHistory: SeedCase = async (context) => { + const note = await createLegacy(context, "Note", { + type: "Note", + contentHtml: "

    Version 1

    ", + name: null, + }); + await editContents( + context, + note.object.id, + Array.from( + { length: LONG_HISTORY_EDITS }, + (_, index) => `Version ${index + 2}`, + ), + ); + return { + number: 22, + title: + `A Note on A's actor page edited ${LONG_HISTORY_EDITS} times, ` + + "more than the timeline loads at once", + resources: [note.object], + }; +}; + +const deliveredCreate: SeedCase = async (context) => { + const note = await createLegacy(context, "Note", { + type: "Note", + contentHtml: "

    Delivered to B

    ", + name: null, + }); + await recordDelivery(context, note, context.bob, { + status: "sent", + statusCode: ACCEPTED, + }); + await editContents(context, note.object.id, ["Edited after delivery"]); + return { + number: 23, + title: + "A Create sent by A and received by B: Activity and Object history " + + "links in both activity logs, the Note edited after delivery", + resources: [note.create, note.object], + }; +}; + +const deletedAfterFailure: SeedCase = async (context) => { + const note = await createLegacy(context, "Note", { + type: "Note", + contentHtml: "

    Undelivered, then deleted

    ", + name: null, + }); + await recordDelivery(context, note, context.bob, { + status: "failed", + statusCode: SERVER_ERROR, + error: "The remote inbox answered 500 Internal Server Error.", + }); + await context.writer.remove(note.object.id); + return { + number: 24, + title: + "A Create whose delivery from A failed, then its Note deleted: " + + "gone from A's actor page, but linked from A's activity log", + resources: [note.create, note.object], + }; +}; + +/** Cases 21 to 24: the pages that link to resource pages. */ +export const LINK_CASES: readonly SeedCase[] = [ + listedObjects, + longHistory, + deliveredCreate, + deletedAfterFailure, +]; diff --git a/scripts/seed-revisions/main.mts b/scripts/seed-revisions/main.mts index 000fd2c6..b18a0eae 100644 --- a/scripts/seed-revisions/main.mts +++ b/scripts/seed-revisions/main.mts @@ -25,6 +25,7 @@ import process from "node:process"; import type { SeedCase, SeededCase } from "./case.mts"; import { ACCESS_CASES } from "./cases-access.mts"; import { DOCUMENT_CASES } from "./cases-documents.mts"; +import { LINK_CASES } from "./cases-links.mts"; import { SOURCE_CASES } from "./cases-sources.mts"; import { openSeedEnvironment } from "./environment.mts"; import { type Viewer, reportCases } from "./report.mts"; @@ -36,6 +37,7 @@ const CASES: readonly SeedCase[] = [ ...DOCUMENT_CASES, ...SOURCE_CASES, ...ACCESS_CASES, + ...LINK_CASES, ]; // The development server reads its origins from this file; use the same. From f4e06712e93370158e9312762cb3417f4b6fc65c Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Tue, 17 Nov 2026 16:06:38 +0900 Subject: [PATCH 09/10] Add modern-web-guidance and taste-skill skills Two agent skill collections are now installed as Git development dependencies, and pnpm links their skills into .agents/skills and .crush/skills: - GoogleChrome/modern-web-guidance provides modern-web-guidance, which retrieves web platform guides through the modern-web-guidance npm CLI, and chrome-extensions. - leonxlnx/taste-skill provides design-taste-frontend, a frontend design skill with a browser-based checker. Both are pinned to their current upstream commits, and their skills are approved in pnpm-workspace.yaml for those commits only. https://developer.chrome.com/blog/modern-web-guidance-v1 https://github.com/GoogleChrome/modern-web-guidance https://github.com/leonxlnx/taste-skill AI assistance: the maintainer asked Claude Code to install the two skill collections. Claude Code added the dependencies, approved their skills, and updated the skill source list. Co-authored-by: Hyeonseo Kim Assisted-by: Claude Code:claude-opus-5-5 --- .agents/skills/README.md | 16 ++++++++++------ package.json | 2 ++ pnpm-lock.yaml | 20 ++++++++++++++++++++ pnpm-workspace.yaml | 4 ++++ 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/.agents/skills/README.md b/.agents/skills/README.md index 4a0e9457..f55ac0d9 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -6,12 +6,14 @@ tarball integrity are recorded in *pnpm-lock.yaml*. There are no checked-in skill copies. *.claude/skills* points to this directory; pnpm also links the same dependency skills into *.crush/skills/*. -| Git development dependency | Skills | Source | -| --------------------------- | ------------------------------------------- | -------------------------- | -| `@open-circle/agent-skills` | `formisch`, `valibot` | [open-circle/agent-skills] | -| `@chillicream/agent-skills` | `graphql-schema-design` | [ChilliCream/agent-skills] | -| `relay-github-root` | `relay-best-practices`, `relay-performance` | [facebook/relay] | -| `@dahlia/sacho` | `sacho` | [dahlia/sacho] | +| Git development dependency | Skills | Source | +| --------------------------- | ------------------------------------------- | ---------------------------------- | +| `@open-circle/agent-skills` | `formisch`, `valibot` | [open-circle/agent-skills] | +| `@chillicream/agent-skills` | `graphql-schema-design` | [ChilliCream/agent-skills] | +| `relay-github-root` | `relay-best-practices`, `relay-performance` | [facebook/relay] | +| `@dahlia/sacho` | `sacho` | [dahlia/sacho] | +| `modern-web-guidance` | `modern-web-guidance`, `chrome-extensions` | [GoogleChrome/modern-web-guidance] | +| `@leonxlnx/taste-skill` | `design-taste-frontend` | [leonxlnx/taste-skill] | The pinned skill contents match the latest upstream versions checked during this migration. ChilliCream is pinned to the last change to its GraphQL schema @@ -38,3 +40,5 @@ updated source approval in *pnpm-workspace.yaml* together. [ChilliCream/agent-skills]: https://github.com/ChilliCream/agent-skills [facebook/relay]: https://github.com/facebook/relay [dahlia/sacho]: https://github.com/dahlia/sacho +[GoogleChrome/modern-web-guidance]: https://github.com/GoogleChrome/modern-web-guidance +[leonxlnx/taste-skill]: https://github.com/leonxlnx/taste-skill diff --git a/package.json b/package.json index 597490b0..98456aff 100644 --- a/package.json +++ b/package.json @@ -8,12 +8,14 @@ "@drfed/models": "workspace:*", "@electric-sql/pglite": "catalog:", "@fedify/fedify": "catalog:", + "@leonxlnx/taste-skill": "github:leonxlnx/taste-skill#f6b76575f949707b4e3c37cd86cb44b0b98643e8", "@logtape/logtape": "catalog:", "@open-circle/agent-skills": "github:open-circle/agent-skills#21d123742218d3cd748056fad78aa88d7da3dc96", "@sigstore/oci": "0.7.2", "@types/node": "catalog:", "drizzle-orm": "catalog:", "graphql": "catalog:", + "modern-web-guidance": "github:GoogleChrome/modern-web-guidance#64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65", "relay-github-root": "github:facebook/relay#52c2e68711a698a9708997b9bdf7532c4d7ecdd6", "vitepress": "^1.6.4" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2ea61361..5c13e327 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -151,6 +151,9 @@ importers: '@fedify/fedify': specifier: 'catalog:' version: 2.4.3 + '@leonxlnx/taste-skill': + specifier: github:leonxlnx/taste-skill#f6b76575f949707b4e3c37cd86cb44b0b98643e8 + version: https://codeload.github.com/leonxlnx/taste-skill/tar.gz/f6b76575f949707b4e3c37cd86cb44b0b98643e8 '@logtape/logtape': specifier: 'catalog:' version: 2.3.0-dev.840 @@ -169,6 +172,9 @@ importers: graphql: specifier: 'catalog:' version: 16.14.2 + modern-web-guidance: + specifier: github:GoogleChrome/modern-web-guidance#64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65 + version: https://codeload.github.com/GoogleChrome/modern-web-guidance/tar.gz/64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65 relay-github-root: specifier: github:facebook/relay#52c2e68711a698a9708997b9bdf7532c4d7ecdd6 version: https://codeload.github.com/facebook/relay/tar.gz/52c2e68711a698a9708997b9bdf7532c4d7ecdd6 @@ -1449,6 +1455,10 @@ packages: peerDependencies: solid-js: ^1.8.8 + '@leonxlnx/taste-skill@https://codeload.github.com/leonxlnx/taste-skill/tar.gz/f6b76575f949707b4e3c37cd86cb44b0b98643e8': + resolution: {gitHosted: true, integrity: sha512-lhWLSUyUP92EoOgg0zUSkYVFEhGfCjcPBC7lD4XLQnC1P70rKpt5JN3omhrZeVPBWMSGLlnaL4kOg0KppOyiaw==, tarball: https://codeload.github.com/leonxlnx/taste-skill/tar.gz/f6b76575f949707b4e3c37cd86cb44b0b98643e8} + version: 0.0.0 + '@logtape/drizzle-orm@2.2.2': resolution: {integrity: sha512-Z/TrI5BbOCSJPmoyogy9RERtAxs/hlyI+e/uay1PSY68/ZddPqfudbS6MGgFylAiACprJ0d0zEiGeysUQUcQ2A==} peerDependencies: @@ -3863,6 +3873,12 @@ packages: mitt@3.0.1: resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} + modern-web-guidance@https://codeload.github.com/GoogleChrome/modern-web-guidance/tar.gz/64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65: + resolution: {gitHosted: true, integrity: sha512-YsINlbv4kBwhCe6MZOlYygyLZci7gRLka9GHgYMpbKPXgeOfPgLsttbKT8wqnC9jhmtFIm7EXGIXLJEwjx58RA==, tarball: https://codeload.github.com/GoogleChrome/modern-web-guidance/tar.gz/64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65} + version: 1.0.1 + engines: {node: '>=22.0.0', vscode: ^1.90.0} + hasBin: true + ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -5624,6 +5640,8 @@ snapshots: '@solid-primitives/utils': 6.4.1(solid-js@1.9.17) solid-js: 1.9.17 + '@leonxlnx/taste-skill@https://codeload.github.com/leonxlnx/taste-skill/tar.gz/f6b76575f949707b4e3c37cd86cb44b0b98643e8': {} + '@logtape/drizzle-orm@2.2.2(@logtape/logtape@2.3.0-dev.840)': dependencies: '@logtape/logtape': 2.3.0-dev.840 @@ -7645,6 +7663,8 @@ snapshots: mitt@3.0.1: {} + modern-web-guidance@https://codeload.github.com/GoogleChrome/modern-web-guidance/tar.gz/64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65: {} + ms@2.1.3: {} nanoid@3.3.19: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 3e108f18..78e20172 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -28,6 +28,10 @@ permissions: skills: true "@optique/core": skills: true + "modern-web-guidance@https://codeload.github.com/GoogleChrome/modern-web-guidance/tar.gz/64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65": + skills: true + "@leonxlnx/taste-skill@https://codeload.github.com/leonxlnx/taste-skill/tar.gz/f6b76575f949707b4e3c37cd86cb44b0b98643e8": + skills: true solid-relay: skills: true From e3190a59a7185294e46e36c30176ced930ba1bc4 Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <2chanhaeng@gmail.com> Date: Tue, 17 Nov 2026 16:40:12 +0900 Subject: [PATCH 10/10] Refine the resource views and raise border contrast The views added for resource histories follow the platform's guidance more closely: - The links to an embedded document's source revision move out of its summary, which holds no interactive element of its own. - The object filter sits in a search landmark, keeps its disclosure marker, and themes its checkbox with accent-color, drawing the box only where that is unsupported. - Loading messages are labelled progress bars instead of live regions, the resource page's sections are no longer named landmarks, the timeline keeps its list semantics in Safari, and standalone links and buttons are at least 24px tall, 44px on touch. Their boxes give way to hairlines: the tinted notices and validator findings lose their coloured side stripes, labels lose their rounded outlines, the history rail and the revision are split by a line instead of two cards, and the selected timeline entry loses its halo. Borders across the web app now stand out of the ground. A new --rule token, halfway between --line-strong and --ink-faint, draws separators and boxes, and the boundaries of controls take --ink-faint, at 3:1 against the ground in both colour schemes. The revision seed gains a document nested six levels deep, with a source declared at every depth, to check the views past the levels the resource page expands. https://github.com/fedify-dev/drfed/issues/154 AI assistance: the maintainer asked Claude Code to apply the modern-web-guidance and taste skills to the views this branch added, to remove boxed and striped styling, to raise border contrast globally, and to seed a deep document. Claude Code chose the changes from the retrieved guides, computed the contrast ratios, and wrote the styles, components, and seed case. The type check, lint, formatter, web build, and seed were run; the pages were not checked in a browser. Co-authored-by: Hyeonseo Kim Assisted-by: Claude Code:claude-opus-5-5 --- .../web/src/components/ActorObjectList.tsx | 3 +- .../web/src/components/FilterDisclosure.tsx | 32 ++-- .../web/src/components/LoadingIndicator.tsx | 32 ++++ .../web/src/components/ResourceDocument.tsx | 16 +- .../web/src/components/ResourceRevision.tsx | 5 +- .../web/src/components/ResourceTimeline.tsx | 7 +- packages/web/src/routes/resource/[id].tsx | 16 +- .../web/src/styles/activity-log.module.css | 12 +- packages/web/src/styles/actor.module.css | 18 +- packages/web/src/styles/app.module.css | 4 +- packages/web/src/styles/buttons.module.css | 2 +- packages/web/src/styles/drfed.css | 4 + packages/web/src/styles/filter.module.css | 76 ++++++++- packages/web/src/styles/form.module.css | 6 +- packages/web/src/styles/instance.module.css | 10 +- packages/web/src/styles/loading.module.css | 30 ++++ packages/web/src/styles/object.module.css | 6 +- packages/web/src/styles/resource.module.css | 84 ++++----- packages/web/src/styles/toast.module.css | 2 +- packages/web/src/styles/workspace.module.css | 10 +- scripts/seed-revisions/cases-depth.mts | 159 ++++++++++++++++++ scripts/seed-revisions/main.mts | 2 + 22 files changed, 430 insertions(+), 106 deletions(-) create mode 100644 packages/web/src/components/LoadingIndicator.tsx create mode 100644 packages/web/src/styles/loading.module.css create mode 100644 scripts/seed-revisions/cases-depth.mts diff --git a/packages/web/src/components/ActorObjectList.tsx b/packages/web/src/components/ActorObjectList.tsx index 83221be6..b9eb26eb 100644 --- a/packages/web/src/components/ActorObjectList.tsx +++ b/packages/web/src/components/ActorObjectList.tsx @@ -25,6 +25,7 @@ import type { ActorObjectList_actor$key } from "./__generated__/ActorObjectList_ import type { ActorObjectListRefetchQuery } from "./__generated__/ActorObjectListRefetchQuery.graphql.ts"; import { CopyButton } from "./CopyButton.tsx"; import { FilterCheckbox, FilterDisclosure } from "./FilterDisclosure.tsx"; +import { LoadingIndicator } from "./LoadingIndicator.tsx"; import styles from "~/styles/actor.module.css"; @@ -100,7 +101,7 @@ export function ActorObjectList(props: { $actor: ActorObjectList_actor$key }) { - Loading objects… +
    - - Filter - 0}> - ({props.active}) - - -
    - Show in {props.label} - {props.children} -
    -
    + +
    + + Filter + 0}> + ({props.active}) + + +
    + Show in {props.label} + {props.children} +
    +
    +
    ); } @@ -60,13 +63,14 @@ export function FilterCheckbox(props: { ); } diff --git a/packages/web/src/components/LoadingIndicator.tsx b/packages/web/src/components/LoadingIndicator.tsx new file mode 100644 index 00000000..32a38777 --- /dev/null +++ b/packages/web/src/components/LoadingIndicator.tsx @@ -0,0 +1,32 @@ +// DrFed: A web-based platform for developing and debugging ActivityPub apps +// Copyright (C) 2026 DrFed team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import styles from "~/styles/loading.module.css"; + +/** + * An indeterminate progress bar named by its visible label, for a part of a + * page that is loading. A progress bar tells assistive technology of the + * wait without the noise of a live region. + * @returns The labelled progress bar. + */ +export function LoadingIndicator(props: { label: string }) { + return ( + + ); +} diff --git a/packages/web/src/components/ResourceDocument.tsx b/packages/web/src/components/ResourceDocument.tsx index a4a379d0..80b9d47c 100644 --- a/packages/web/src/components/ResourceDocument.tsx +++ b/packages/web/src/components/ResourceDocument.tsx @@ -385,16 +385,20 @@ function NodeView(props: { {node().iri ?? Anonymous} - 0}> - - ); + // The source links stay out of the summary, which must hold no + // interactive element of its own. const body = () => (
    + 0}> +

    + +

    +
    pathKey(diagnostic.path) === pathKey(path()), diff --git a/packages/web/src/components/ResourceRevision.tsx b/packages/web/src/components/ResourceRevision.tsx index c1ec6be7..56d2d12e 100644 --- a/packages/web/src/components/ResourceRevision.tsx +++ b/packages/web/src/components/ResourceRevision.tsx @@ -139,10 +139,7 @@ export function ResourceRevision(props: { return ( {(revision) => ( -
    +

    {props.head ? "Current revision" : "Earlier revision"}

    diff --git a/packages/web/src/components/ResourceTimeline.tsx b/packages/web/src/components/ResourceTimeline.tsx index 60660fc3..53aa4cc7 100644 --- a/packages/web/src/components/ResourceTimeline.tsx +++ b/packages/web/src/components/ResourceTimeline.tsx @@ -22,6 +22,7 @@ import { createPaginationFragment } from "solid-relay"; import { WORDING, resourceHref, timelineEntries } from "~/resource.ts"; import type { ResourceTimeline_resource$key } from "./__generated__/ResourceTimeline_resource.graphql.ts"; +import { LoadingIndicator } from "./LoadingIndicator.tsx"; import { TimeText } from "./ResourceRevision.tsx"; import styles from "~/styles/resource.module.css"; @@ -89,7 +90,9 @@ export function ResourceTimeline(props: { {(resource) => (
    -
      + {/* Safari drops list semantics without list markers. */} + {/* oxlint-disable-next-line jsx-a11y/no-redundant-roles */} +
        {(entry) => ( @@ -159,7 +162,7 @@ export function ResourceTimeline(props: {

        - Loading older revisions… +