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: "
",
+ 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: "
+
+
+
+
+ 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) => (
+
+ )}
+
+ );
+}
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
+
+
+ >
+ );
+}
+
+/**
+ * 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) => (
+
+
+ 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})
+
+
+
+
+ );
+}
+
+/**
+ * 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: "
",
+ 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 }) {
-
+
diff --git a/packages/web/src/components/FilterDisclosure.tsx b/packages/web/src/components/FilterDisclosure.tsx
index 40d24f70..b33c4e8a 100644
--- a/packages/web/src/components/FilterDisclosure.tsx
+++ b/packages/web/src/components/FilterDisclosure.tsx
@@ -19,7 +19,8 @@ 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.
+ * A disclosure above a list that opens the conditions it is filtered by,
+ * within a `search` landmark.
* @returns The disclosure, with the number of active conditions on its
* toggle.
*/
@@ -31,18 +32,20 @@ export function FilterDisclosure(props: {
children: JSX.Element;
}) {
return (
-
-
- Filter
- 0}>
- ({props.active})
-
-
-
-
+
+
+
+ Filter
+ 0}>
+ ({props.active})
+
+
+
+
+
);
}
@@ -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 = () => (