@drfed/models 0.2.0-dev.639 → 0.2.0-dev.682

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +340 -188
  2. package/dist/activity-delivery.d.mts +1 -1
  3. package/dist/activity-delivery.d.mts.map +1 -1
  4. package/dist/activity-delivery.mjs +34 -9
  5. package/dist/activity-delivery.mjs.map +1 -1
  6. package/dist/{db-DtcLuISw.d.mts → db-BBw4F4HU.d.mts} +478 -6
  7. package/dist/{db-DtcLuISw.d.mts.map → db-BBw4F4HU.d.mts.map} +1 -1
  8. package/dist/db.d.mts +1 -1
  9. package/dist/document.d.mts +200 -0
  10. package/dist/document.d.mts.map +1 -0
  11. package/dist/document.mjs +1264 -0
  12. package/dist/document.mjs.map +1 -0
  13. package/dist/index.d.mts +3 -2
  14. package/dist/index.mjs +2 -1
  15. package/dist/instance.d.mts +1 -1
  16. package/dist/key.d.mts +1 -1
  17. package/dist/login.d.mts +1 -1
  18. package/dist/migrations-manifest.json +12 -0
  19. package/dist/relations.d.mts +1 -1
  20. package/dist/relations.mjs +65 -0
  21. package/dist/relations.mjs.map +1 -1
  22. package/dist/resource-revision-BuG5kUlA.d.mts +103 -0
  23. package/dist/resource-revision-BuG5kUlA.d.mts.map +1 -0
  24. package/dist/resource-revision-DWg6et77.mjs +313 -0
  25. package/dist/resource-revision-DWg6et77.mjs.map +1 -0
  26. package/dist/resource-revision.d.mts +2 -0
  27. package/dist/resource-revision.mjs +3 -0
  28. package/dist/resource.d.mts +1 -1
  29. package/dist/schema.d.mts +2 -2
  30. package/dist/schema.mjs +104 -5
  31. package/dist/schema.mjs.map +1 -1
  32. package/drizzle/20261026181201_resource_revision_storage/migration.sql +72 -0
  33. package/drizzle/20261026181201_resource_revision_storage/snapshot.json +4501 -0
  34. package/drizzle/20261026181206_guard_resource_revisions/migration.sql +175 -0
  35. package/drizzle/20261026181206_guard_resource_revisions/snapshot.json +4501 -0
  36. package/drizzle/20261026192411_capture_legacy_resource_revisions/migration.sql +249 -0
  37. package/drizzle/20261026192411_capture_legacy_resource_revisions/snapshot.json +4501 -0
  38. package/package.json +19 -7
package/README.md CHANGED
@@ -7,6 +7,314 @@ both PGlite (embedded) and PostgreSQL.
7
7
  [DrFed]: https://drfed.org/
8
8
 
9
9
 
10
+ Document validation
11
+ -------------------
12
+
13
+ `@drfed/models/document` exports synchronous
14
+ `validateDocument(document: unknown)` and `prepareDocument(document, options)`,
15
+ plus the `diagnosticReasons` registry. Public types are
16
+ `DocumentValidationResult`, `Diagnostic`, `DiagnosticReason`,
17
+ `DiagnosticCategory`, `DiagnosticSeverity`, `FieldPath`, `JsonValue`,
18
+ `NormalizationChange`, `DocumentAuthority`, `ServerOwnedField`, and
19
+ `DocumentPreparationOptions`. Pass parsed JSON, not JSON text. Validation
20
+ performs no network access, database writes, permission checks, or delivery,
21
+ and never mutates input.
22
+
23
+ ### Consumer contract
24
+
25
+ The structured builder (#140) supplies its document; the raw editor (#141)
26
+ parses JSON first and owns syntax errors and text locations. Both call the same
27
+ validator. Paths identify original property names and zero-based list indexes,
28
+ including aliases; `[]` identifies the root. Map these paths to controls or
29
+ source locations without comparing human-readable messages.
30
+
31
+ ~~~~ ts
32
+ import { validateDocument } from "@drfed/models/document";
33
+
34
+ const result = validateDocument({
35
+ "@context": "https://www.w3.org/ns/activitystreams",
36
+ type: "Accept",
37
+ object: [{ type: "Follow", actor: false }],
38
+ });
39
+ // invalid_value_shape at ["object", 0, "actor"]
40
+ const structurallyAccepted =
41
+ result.complete &&
42
+ !result.diagnostics.some(({ severity }) => severity === "error");
43
+ ~~~~
44
+
45
+ | Result field | Caller interpretation |
46
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
47
+ | complete | Checks finished. A definite malformed-input result can be complete; this is not a validity or permission flag. |
48
+ | diagnostics | Each finding has a stable reason, category, severity, original-input path, and display message. Use reason for machine decisions; messages may change. |
49
+ | changes | Proposed changes with operation, reason, path, message, and before/after values as applicable. Empty when no preview is available. |
50
+ | normalizedDocument | Independent preview, present only when changes are proposed, checking is complete, and no errors occur. Input remains unchanged. |
51
+
52
+ Vocabulary errors describe malformed supported input. Support errors describe
53
+ unimplemented types, properties, or representations and make `complete` false.
54
+ Compatibility warnings do not automatically reject the document. An omitted
55
+ context uses the standard ActivityStreams context with a warning. The exported
56
+ authority category is used by prepareDocument for caller-reported denials and
57
+ server-owned-field conflicts. validateDocument itself emits no authority
58
+ findings.
59
+
60
+ Document-only normalization proposes omission of empty arrays on supported,
61
+ applicable properties. For example, a Note with `to: []` receives the
62
+ `empty_property_list` warning and a removal change with reason
63
+ `omit_empty_property_list`; its preview omits `to`. Present changes for an
64
+ explicit caller decision. Validation does not apply them or save the preview.
65
+ Identifiers set to null or a nonempty array containing only null receive an
66
+ `absent_identifier` warning and a removal change with reason
67
+ `omit_absent_identifier`. This also applies to `@id` and supported aliases.
68
+ The preview omits these absent identifiers so Fedify can parse it; the submitted
69
+ document is preserved. Arrays containing any non-null identifier remain errors.
70
+ It does not assign IDs or timestamps, replace actor/attribution identities,
71
+ deduplicate recipients, or convert references to embedded values.
72
+
73
+ ### Preparing server-owned creation fields
74
+
75
+ `prepareDocument(document, options)` returns the same DocumentValidationResult
76
+ shape. It combines structural validation with explicit authority outcomes and
77
+ server-owned values supplied by trusted server code. The exported
78
+ DocumentPreparationOptions, DocumentAuthority, and ServerOwnedField types define
79
+ these inputs. Never populate options directly from editor/client JSON.
80
+
81
+ ~~~~ ts
82
+ import { prepareDocument } from "@drfed/models/document";
83
+
84
+ // Server code has already checked permission and allocated these values.
85
+ const result = prepareDocument(submittedDocument, {
86
+ authority: [{ allowed: true, path: [] }],
87
+ serverOwnedFields: [
88
+ { path: ["id"], value: allocatedObjectIri },
89
+ { path: ["attributedTo"], value: authorizedActorIri },
90
+ { path: ["published"], value: allocatedPublicationTimestamp },
91
+ ],
92
+ });
93
+ ~~~~
94
+
95
+ At least one explicit authority outcome is required. A denied outcome produces
96
+ unauthorized\_local\_identity (authority/error) at the supplied original path;
97
+ use `[]` for an operation-level denial. The function only reports this outcome:
98
+ `allowed: true` is not an authorization check or a reusable permission token.
99
+ Nested creations need the caller's separate permission outcomes. Embedded
100
+ values alone never request creation or modification of resources.
101
+ Authority paths are caller-supplied diagnostic locations; they are not checked
102
+ against writable document targets. This differs from server-owned field paths.
103
+
104
+ Owned-field paths must name id, actor, attributedTo, published, or updated on
105
+ existing supported root/nested documents. Supported aliases resolve to the same
106
+ field; diagnostics and changes retain original source spellings and indexes.
107
+ Conflicts in arrays point to the non-null entries. When filling an absent value,
108
+ preparation prefers the requested key if it exists, then an existing alias,
109
+ and otherwise adds the requested key.
110
+ References and opaque extension data cannot be targets. The caller lists only
111
+ the fields it owns for that explicit creation operation; no default fields are
112
+ invented, and no values are generated from the clock or random IDs here.
113
+
114
+ | Submitted value | Preparation behavior |
115
+ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
116
+ | Missing | Propose an add change with reason assign\_server\_owned\_field. |
117
+ | Null or a supported array containing only null | Propose a replace change retaining the original value in before. |
118
+ | Exactly one non-null string matching the server value | Preserve the submitted representation; non-null id arrays remain invalid. |
119
+ | Different value, embedded identity, or additional non-null values | Report server\_owned\_field\_conflict (authority/error); never silently replace it. |
120
+ | Structurally malformed or unsupported input | Return its vocabulary/support diagnostics; do not prepare a successful preview. |
121
+
122
+ Matching uses exact string equality, not URL canonicalization, timestamp
123
+ rewriting, or remote lookup. Structural multiplicity errors remain vocabulary
124
+ errors. Both identity strings and timestamps supplied by the server are checked
125
+ for supported syntax. Invalid trusted configuration, duplicate semantic field
126
+ declarations, or paths outside existing supported documents throw TypeError
127
+ before document errors or denied authority stop preparation; these are caller
128
+ programming errors. Missing parent paths are checked without evaluating
129
+ accessors. If malformed documents, unsupported types/contexts, or truncated
130
+ checking prevent target or alias resolution, preparation retains document
131
+ diagnostics instead of treating that uncertainty as a caller path error.
132
+ Resolvable standard property names and trusted values are still checked.
133
+
134
+ The preview combines server-field additions with existing empty-property
135
+ omissions, preserves custom properties, and is structurally revalidated. It
136
+ is returned only when checking completes without errors and changes exist.
137
+ When a server-owned replacement targets a proposed omission at the same source
138
+ path, preparation returns only the replacement and updates the warning to
139
+ describe it. The final preview contains the supplied value; unrelated omission
140
+ proposals remain unchanged.
141
+ Denied authority, conflicts, unsupported input, and truncated diagnostics
142
+ withhold both preview and changes. The input and trusted options are unchanged.
143
+
144
+ #152 owns actual permission checks, value allocation, preview-to-commit
145
+ coordination, persistence, and permission rechecks at write time. It must keep
146
+ the committed values consistent with the accepted preview. This module neither
147
+ saves anything nor adapts createObject. Both editors can display the shared
148
+ results; saving, publication, and sending remain separate operations.
149
+
150
+ ### Supported types and properties
151
+
152
+ The checker admits both activity base types and all 28 named activity subtypes,
153
+ plus Object, Note, Article, Application, Group, Organization, Person, Service,
154
+ Collection, OrderedCollection, CollectionPage, OrderedCollectionPage, Link,
155
+ and Mention. Optional properties stay optional. Each document needs one
156
+ supported type string; all type arrays, including singleton arrays, are
157
+ unsupported. Unknown types are retained without being converted to Note.
158
+
159
+ Type detection uses Fedify's public registry and inheritance, with an explicit
160
+ implemented-type set. Link and Mention use their exported classes because the
161
+ installed registry excludes them. Models and federation share the catalog
162
+ version of `@fedify/vocab` (currently 2.4.3); context data comes from the
163
+ matching `@fedify/vocab-runtime`. Recognition by Fedify alone does not
164
+ establish checker coverage. No vocabulary parser or full JSON-LD expansion runs
165
+ here.
166
+
167
+ In the table, Object includes its admitted subtypes, including activities,
168
+ actors, and collections. References are absolute IRIs or supported embedded
169
+ Object/Link values. Reference lists retain order, duplicates, and source
170
+ indexes.
171
+
172
+ | Applies to | Properties and rules |
173
+ | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
174
+ | Object and Link | id: one IRI; mediaType: one MIME type; preview: references/lists; name/nameMap: text without HTML. |
175
+ | Object | summary/content and summaryMap/contentMap: text, including HTML and empty strings; location and attributedTo: references/lists. |
176
+ | Object | published, updated, startTime, endTime: one date-time each; to, cc, bto, bcc, audience: references/lists, with empty-array omission previews. |
177
+ | Activity | actor, object, target, origin, result, instrument: references/lists. IntransitiveActivity, Arrive, Travel, and Question reject non-null object values. |
178
+ | Actor types | preferredUsername: text; inbox/outbox: one IRI or embedded OrderedCollection or OrderedCollectionPage; following/followers/liked: one IRI or embedded Collection subtype. |
179
+ | Collection and subtypes | items/orderedItems: references/lists; totalItems: non-negative integer; current/first/last: one IRI or CollectionPage subtype. Counts need not match visible members. |
180
+ | CollectionPage subtypes | partOf: one IRI or Collection subtype; next/prev: one IRI or CollectionPage subtype. |
181
+ | OrderedCollectionPage | startIndex: non-negative integer. |
182
+ | Link and Mention | href: one IRI; hreflang: one language tag; rel: relation tokens/IRIs or lists; height/width: non-negative integers. Object-only fields, such as content and location, receive property\_not\_applicable. |
183
+
184
+ Except for id, single-value properties accept a scalar or array containing at
185
+ most one non-null value; multiple values receive `invalid_multiplicity`. Null
186
+ means absence, including null list entries. Empty arrays on supported
187
+ properties receive `empty_property_list` and an inspectable omission preview;
188
+ nested lists remain unsupported. Type and context arrays do not use this
189
+ omission rule. Unknown custom arrays are preserved as opaque data, while empty
190
+ arrays on unsupported or inapplicable fields retain their existing errors.
191
+ Identifiers require an IRI string when present. Null, empty arrays, and
192
+ null-only arrays receive omission previews; arrays containing non-null values
193
+ receive `invalid_value_shape`, even when they contain only one identifier.
194
+ Embedded activity actors and Object `attributedTo` values must use Application,
195
+ Group, Organization, Person, or Service for Fedify compatibility. Other
196
+ ActivityStreams-permitted embedded types receive `unsupported_value_form`; IRI
197
+ references remain supported without remote type checks. Object-only fields such
198
+ as `attributedTo` on Link receive `property_not_applicable`. Link `preview` and
199
+ `nameMap` remain supported by the vocabulary and Fedify's decoder. Collection
200
+ navigation accepts embedded CollectionPage values for current, first, last,
201
+ next, and prev, and Collection values for partOf, including subtypes. Embedded
202
+ Links in these fields receive `unsupported_value_form` because Fedify rejects
203
+ them. Diagnostics retain the original field/list paths.
204
+
205
+ Text accepts strings, flat lists, and supported `@value`/`@language` objects.
206
+ Language maps contain strings or null. Complex text attributes are unsupported.
207
+ Dates require a timezone and uppercase T/Z. Calendar checks use Temporal;
208
+ invalid dates receive `invalid_datetime`. ActivityStreams permits omitted
209
+ seconds, but representations Fedify cannot consume without failure or precision
210
+ loss receive `unsupported_value_form`: omitted seconds, fractions without
211
+ seconds, and fractions exceeding nine digits. Leap-second timestamps remain
212
+ unsupported. Validation preserves these values without adding seconds or
213
+ truncating precision. Timestamp validation does not establish server ownership
214
+ or ordering between fields.
215
+
216
+ Question is supported standalone and inside Create/Update using shared rules.
217
+ Its `oneOf`, `anyOf`, and `closed` fields remain unsupported pending #155's
218
+ poll rules. Open-ended Question needs no choices. Other types without
219
+ implemented rules, such as Place, receive support findings.
220
+
221
+ For 0.2.0, Object property rules for `tag`, `inReplyTo`, `url`, `attachment`,
222
+ `replies`, `icon`, `image`, `context`, `source`, `duration`, and `generator`
223
+ remain unimplemented. Null values are treated as absent and preserved without
224
+ diagnostics or normalization. On Object documents, non-null values produce
225
+ `unsupported_property` errors and set `complete: false`, preventing successful
226
+ validation even when their values are valid ActivityStreams. This limits which
227
+ documents pasted from fediverse servers can pass validation. Unknown custom
228
+ properties instead receive `extension_property_unchecked` warnings and can
229
+ survive successful validation without their semantics being checked. Full
230
+ coverage for the listed properties is deferred beyond 0.2.0 and tracked in
231
+ [#168].
232
+
233
+ [#168]: https://github.com/fedify-dev/drfed/issues/168
234
+
235
+ ### Context and preservation limits
236
+
237
+ The context allowlist includes the standard ActivityStreams context (HTTPS and
238
+ its accepted HTTP spelling) and `https://w3id.org/security/v1`. Flat context
239
+ arrays and simple inline term/prefix definitions are supported. Effective
240
+ contexts must include the standard ActivityStreams vocabulary; standard terms
241
+ cannot be overridden. Embedded values inherit context; local alias overrides
242
+ are isolated from siblings.
243
+
244
+ Bundled context tables initialize on first use, not module import; an
245
+ unsupported bundled definition can throw during validation, and failed
246
+ initialization is retried rather than cached.
247
+
248
+ Aliases must have compatible coercion and containers. For example, an object
249
+ alias needs `@type: "@id"`; matching a property IRI alone is insufficient.
250
+ Functional aliases are counted together without merging source values.
251
+ Malformed context definitions receive `invalid_context`; unavailable contexts
252
+ receive `context_unavailable_offline`, not an empty replacement. There are no
253
+ remote lookups or remote lookup failures to interpret in this API.
254
+ Inline terms must be nonempty, and resolved mapping IRIs must not contain
255
+ unescaped whitespace, control characters, or forbidden IRI punctuation.
256
+
257
+ Scoped contexts, custom base/vocabulary/default-language directives, context
258
+ resets, JSON literals, and other complex forms remain unsupported. Relative
259
+ IRIs remain unsupported until a trusted base policy exists. Custom properties,
260
+ mapped or unmapped, are preserved as opaque JSON and receive the compatibility
261
+ warning `extension_property_unchecked`. Their semantics are not validated.
262
+ Otherwise supported documents can finish with `complete: true` and no errors;
263
+ normalization previews preserve the custom fields and their nested values.
264
+ Opaque values are checked for JSON safety, including cycles and accessors,
265
+ without interpreting nested type or context keys as ActivityStreams.
266
+ Language-tagged value objects also require a string or null `@value` and a
267
+ string or null `@language`; malformed values receive `invalid_value_shape`
268
+ at the original keyword path. A null language tag leaves the value untagged.
269
+ Explicit `@id` values inside extensions must be strings. Explicit `@type`
270
+ values must be strings or arrays of strings; malformed entries receive
271
+ `invalid_value_shape` at the original keyword or list-entry path. These shape
272
+ checks do not require custom type strings to appear in the implemented-type
273
+ set. An `@json` value's payload remains ordinary JSON, including keys spelled
274
+ `@id` or `@type`, and is checked only for JSON safety. These bounded checks do
275
+ not establish full JSON-LD validity or interpret nested contexts and keyword
276
+ aliases.
277
+
278
+ This warning policy does not admit unknown types, unsupported contexts,
279
+ JSON-LD keywords, or known vocabulary properties without implemented rules.
280
+ Known unimplemented properties set to null are treated as absent; otherwise,
281
+ those forms still block validation. Passing validation does not guarantee custom
282
+ fields survive Fedify serialization or sending. This supersedes the earlier
283
+ policy that rejected all custom properties.
284
+
285
+ Diagnostics are capped at 100. Exactly 100 findings are retained without a
286
+ truncation marker. If a further finding occurs, the last slot becomes a
287
+ `diagnostic_limit_reached` error; checking remains incomplete and no preview
288
+ is returned. This limits diagnostic output, not the amount of processing.
289
+ Traversal is iterative. Embedded document and opaque-extension traversal paths
290
+ may contain at most 64 segments, counting property names and list indexes;
291
+ the root has depth zero. At depth 65, checking reports
292
+ `processing_limit_exceeded` (support/error) at the original path without
293
+ descending further. The result is incomplete and has no preview or changes;
294
+ other branches can still be checked. Preparation treats targets beyond this
295
+ boundary as unavailable rather than as caller path errors. This is an
296
+ operational support limit, not an ActivityStreams validity rule.
297
+ There is no total value-count or work budget; the depth limit does not bound
298
+ wide arrays or overall document size.
299
+ Cycles in traversed values receive `non_json_value`; shared sibling objects
300
+ are allowed.
301
+
302
+ ### Executable examples
303
+
304
+ All 138 cases in [the fixture file] are exercised by [the document tests]
305
+ through the built package export. Cases include `undo-nested-number`,
306
+ `accept-follow-list-actor`, `addressing-empty`, `context-alias-number`, and
307
+ `extension-mixed-type`. Fixture expectations contain reasons and paths;
308
+ category and severity are checked against the registry. Input preservation and
309
+ preview contents are asserted. Additional tests exercise network avoidance,
310
+ contexts, representation limits, and nested traversal. Preparation tests
311
+ exercise supplied authority outcomes and generated-field previews. Database
312
+ permission enforcement and transaction integration remain #152 responsibilities.
313
+
314
+ [the fixture file]: ../../fixtures/document-validation/initial.json
315
+ [the document tests]: src/document.test.ts
316
+
317
+
10
318
  Schema
11
319
  ------
12
320
 
@@ -17,200 +325,44 @@ Schema
17
325
  | `instance_members` | `instanceId` → `instances`, `accountId` → `accounts` |
18
326
 
19
327
 
20
- Migrations
21
- ----------
328
+ Resource revisions
329
+ ------------------
22
330
 
23
- Generate a migration after changing *src/schema.ts*:
331
+ `@drfed/models/resource-revision` provides trusted append and history reads for
332
+ full ActivityStreams JSON, with compare-and-swap heads and terminal deletion
333
+ markers. Existing local and inbound Create writers capture their documents in
334
+ the same transaction. Retained JSON can contain blind recipients; model reads
335
+ do not authorize access or prepare wire documents.
24
336
 
25
- ~~~~ sh
26
- mise run generate:migrate --name your_migration_name
27
- ~~~~
337
+ See the [resource revision internals] for API examples, projections, legacy
338
+ upgrades and the boundaries of editor, federation and dispatch integration.
28
339
 
29
- After reviewing newly generated SQL, register its identity:
340
+ [resource revision internals]: https://drfed.org/internals/resource-revisions
30
341
 
31
- ~~~~ sh
32
- mise run manifest:migrations --append
33
- ~~~~
34
342
 
35
- This appends SHA-256 hashes of raw SQL bytes to *migrations-manifest.json* and
36
- refuses to rewrite or remove existing entries. Builds verify the SQL against
37
- this file and copy it to *dist/migrations-manifest.json*. `mise run check`
38
- checks the same identities, and pull request CI compares the manifest with the
39
- base commit to catch simultaneous changes to historical SQL and its hash.
40
- Migration SQL is checked out with LF endings on every platform, so Git's
41
- `core.autocrlf` setting does not change these raw-byte identities.
42
- A base commit from before the manifest's introduction starts the baseline.
43
-
44
- `@drfed/models/migration-manifest` exposes `verifyMigrationManifest()` for
45
- installed package checks without connecting to a database. These checks do
46
- not change the migration runner's database behavior.
47
-
48
- `@drfed/models/migration-state` exposes `inspectMigrationState(client)`.
49
- It uses only `SELECT` statements, verifies the installed manifest, and never
50
- owns or closes the supplied query client. Exact named history is `ready`;
51
- a strict prefix is `pending`. Changed hashes, diverged history, newer
52
- migrations, unsupported table formats, and DrFed tables without tracked
53
- history are reported separately. Legacy history must match both generation
54
- seconds and hashes, and reports `upgrade-required` without altering metadata.
55
- Named rows from Drizzle's legacy upgrade retain generation milliseconds and
56
- have SQL `NULL` in `applied_at`; these also match by generation second, name,
57
- and hash. Other named rows require the exact manifest timestamp.
58
- Database query failures propagate instead of being treated as a fresh database.
59
- Connections subject to row-level security on migration history are rejected,
60
- since filtered rows cannot prove that the history is complete.
61
-
62
- `@drfed/models/migration-session` exposes `preparePostgresDatabase()` for
63
- PostgreSQL. It verifies bundled SQL, connects a fresh owned [`pg.Client`], takes
64
- a session advisory lock, inspects history before any metadata DDL, applies
65
- verified pending SQL or legacy upgrades, and checks exact history afterward.
66
- The optional client factory must return an unconnected, exclusive client;
67
- the runner owns `connect()` and `end()` and never reconnects after failure.
68
- The runner hashes the exact SQL bytes again after acquiring the lock and gives
69
- Drizzle a private temporary snapshot, so a concurrent installation change cannot
70
- supply unverified SQL between validation and application.
71
-
72
- `lockTimeoutMs` bounds connection and lock acquisition; SQL application is
73
- not limited by that deadline. `signal` aborts waiting or closes an active
74
- connection. PostgreSQL can retain an interrupted statement and its lock until
75
- it observes the disconnect, so another runner continues to wait rather than
76
- stealing the lock. Migration errors have fixed codes and omit raw DB errors
77
- and credentials; the `drfed.models.migration` debug category records the
78
- backend PID after locking. Use a direct database connection or a proxy that
79
- preserves sessions; transaction pooling is unsupported.
80
-
81
- `@drfed/models/pglite-preparation` exposes `preparePgliteDatabase({ store })`
82
- for a store returned by `openPersistentPglite()`. It verifies SQL and history,
83
- refuses incompatible or untracked schemas before metadata DDL, applies exact
84
- verified snapshots, then requires ready history. Verified legacy milliseconds
85
- are preserved during metadata upgrade. Preparers sharing one client are
86
- serialized, so a later request inspects the first request's committed history.
87
-
88
- The caller owns the store throughout preparation and must refrain from other
89
- queries until it settles. Preparation never closes the database or releases
90
- its native lock, even after failure. `signal` is checked at safe boundaries;
91
- active WASM SQL settles before an aborted operation completes. Drain preparation
92
- before `store.close()`.
93
-
94
- The existing `migrate()` remains a low-level API whose caller must ensure
95
- exclusive access. The CLI uses the safe preparation APIs described above.
96
-
97
- For contributor tests, point `DRFED_TEST_POSTGRES_URL` at an isolated
98
- PostgreSQL cluster with `CREATEDB` and `CREATEROLE` permissions, then run:
99
-
100
- ~~~~ sh
101
- mise run test:postgres
102
- ~~~~
343
+ Database lifecycle
344
+ ------------------
345
+
346
+ See [database lifecycle internals] for migration
347
+ manifests, history inspection, safe PostgreSQL and PGlite preparation, native
348
+ file locks, and contributor verification commands. The caller owns borrowed
349
+ clients and stores; preparation does not replace runtime cleanup.
350
+
351
+ [database lifecycle internals]: https://drfed.org/internals/database-lifecycle
352
+
353
+
354
+ Activity deliveries
355
+ -------------------
356
+
357
+ `@drfed/models/activity-delivery` stores delivery observations separately from
358
+ ActivityPub resources. See [activity delivery internals] for
359
+ recording, attempt history, snapshot receipts and observed signing keys.
360
+
361
+ [activity delivery internals]: https://drfed.org/internals/activity-deliveries
362
+
103
363
 
104
- This task creates and removes unique test databases and roles. Ordinary
105
- `mise run test` skips the service-dependent cases when that variable is absent.
106
-
107
- The *drizzle/* directory is included in the published npm package so that
108
- installed users can run migrations without access to the repository source.
109
-
110
- [`pg.Client`]: https://node-postgres.com/apis/client
111
-
112
-
113
- Persistent PGlite ownership
114
- ---------------------------
115
-
116
- `@drfed/models/pglite-store` exposes `openPersistentPglite(dataPath)`. It
117
- creates the directory, resolves its real absolute path, acquires an exclusive
118
- native file lock, then constructs PGlite. Register the returned `close()`
119
- immediately and await `ready` before querying. This promise maps asynchronous
120
- initialization failures to the fixed `PgliteStoreError` code `open-failed`;
121
- `close()` remains available even after an initialization failure. The shared
122
- close promise shuts PGlite down before releasing its lock. If database close
123
- fails, the lock stays held until that owner process exits.
124
-
125
- [fs-native-extensions] supplies prebuilt Node addons for macOS, Windows and
126
- Linux on x64/ARM64. Its file-description locks prevent another owner in the
127
- same or a different process; suspension does not make a lock stale, and process
128
- exit releases it. Loading an unavailable addon fails closed; there is no
129
- compiler, heartbeat or PID-based fallback. Use a local filesystem. Network
130
- filesystems and shared directories across container/PID namespaces are
131
- unsupported.
132
-
133
- The stable *.drfed.lock* file stays in the data directory after shutdown. Never
134
- remove or replace it while an owner may be alive: two different inodes would
135
- allow separate owners. A leftover file is harmless once the OS has released
136
- its lock. After a failed close, stop that owner before reopening. Other code
137
- that directly constructs PGlite bypasses this ownership API; coordinate all
138
- access through it. The CLI uses this store for persistent PGlite databases.
139
-
140
- The ordinary test task covers duplicate owners, a simultaneous process race,
141
- symlink aliases, close ordering and failed-close ownership. POSIX-only tests
142
- also suspend and forcibly terminate an owned child process before reopening.
143
-
144
- [fs-native-extensions]: https://github.com/holepunchto/fs-native-extensions
145
-
146
-
147
- Activity delivery storage
148
- -------------------------
149
-
150
- `activity_deliveries` stores delivery observations separately from ActivityPub
151
- `activities`. `@drfed/models/activity-delivery` exposes `recordInbound`,
152
- `receiveInbound`, `recordOutbound`, and `settleOutbound`. `receiveInbound`
153
- marks an `acknowledged` inbound delivery `received` once a queued inbox
154
- listener ran. An inbound delivery keeps the received
155
- octets in `body` and the request headers in `headers`; `payload` is the body
156
- parsed as JSON, and is SQL `NULL` when it does not parse or holds U+0000 or an
157
- unpaired surrogate, which jsonb cannot store. `error` and `response_body`
158
- are stored with U+FFFD for each U+0000, which text cannot store, so that a
159
- remote response never keeps a delivery from being written. `created` is when
160
- a request arrived or a delivery started, and `completed` when DrFed answered
161
- the request or the delivery last changed status.
162
-
163
- `settleOutbound` settles the most recent pending (`queued` or `failed`)
164
- delivery to an inbox and never changes a `sent`, `permanently_failed`, or
165
- `abandoned` one. Each attempt that ends is kept in
166
- `activity_delivery_attempts`, so a retry never rewrites the outcome of an
167
- earlier attempt.
168
-
169
- `activity_id` links a delivery to the stored activity it carried.
170
- `linkInboundActivity` links an inbound delivery only when it was verified and
171
- answered with 2xx, by the activity IRI it recorded; `recordOutbound` takes the
172
- `activityId` of the activity it sends. `recordInbound` does not take one, and
173
- a CHECK constraint refuses a linked inbound delivery that is not verified,
174
- `received` or `acknowledged`. A delivery outlives its activity.
175
- `carried_snapshot` marks an inbound delivery whose payload is the stored
176
- activity's document, and `carried_object_snapshot` one that carried the object
177
- stored with that activity as well: the object was taken from the activity, or
178
- `objects.fetched` says it was fetched and the delivery's `fetched_object`, what
179
- its inbox listener fetched, is the stored document. Neither record function
180
- takes a mark; `linkInboundActivity` decides both anew on every link, and
181
- `recordFetchedObject` again for a delivery linked before its listener ran, so
182
- that a mark left from a deleted activity never carries over to another stored
183
- under the same IRI.
184
-
185
- `activity_delivery_actors` relates a delivery to each local actor it concerns,
186
- as the owner of the inbox, as an addressed recipient, or as the sender, with
187
- one row per delivery and actor. An addressed actor keeps every way it was
188
- addressed: `addressed_directly` when the activity named the actor itself, and
189
- a row in `activity_delivery_actor_collections` for each addressed collection
190
- it was a member of. Each row copies the delivery's `created`, by which an
191
- actor's deliveries are ordered. Both record functions insert these rows in
192
- the same transaction as the delivery. They record nothing and throw when the
193
- inbox owner, the sender, or an addressed actor is not a local actor of the
194
- delivery's instance, since neither foreign key can tell.
195
-
196
- `@drfed/models/key` exposes public-JWK validation, RFC 7638/RFC 8037 SHA-256
197
- thumbprints, and `observeKeyVersion`. `keys` identifies each exact key IRI;
198
- `key_versions` retains immutable public material per fingerprint. Returning to
199
- an earlier key reuses its version. Observation timestamps do not describe
200
- remote rotation times or continuous use. Deliveries retain referenced versions
201
- with `ON DELETE RESTRICT`, independently of Fedify cache expiry.
202
-
203
- The `drfed-server` facade now uses these safe preparation APIs for automatic
204
- migration and `inspectMigrationState()` for `--no-migrate`. Its persistent
205
- PGlite owner remains held through preparation, serving and database cleanup.
206
- The older `migrate()` function remains a low-level compatibility API; it does
207
- not provide this facade ownership and history validation contract.
208
-
209
- `preparePostgresDatabase` also accepts explicit node-postgres connection
210
- settings as `credentials.connection`, without a `connectionString`. The facade
211
- uses this form so that decoded host names, database names, credentials and TLS
212
- policy are the same during migration and runtime. Both connections explicitly
213
- verify the configured host identity for TLS, including IP addresses.
364
+ Database upgrades
365
+ -----------------
214
366
 
215
367
  Installed users can run `drfed-migrate` from `@drfed/drfed` to prepare the
216
368
  database; `drfed-migrate --check` only inspects history and exits 0 for ready
@@ -1,4 +1,4 @@
1
- import { M as NewActivityDelivery, N as NewActivityDeliveryActor, o as ActivityDelivery, r as Transaction, t as Database } from "./db-DtcLuISw.mjs";
1
+ import { M as NewActivityDelivery, N as NewActivityDeliveryActor, o as ActivityDelivery, r as Transaction, t as Database } from "./db-BBw4F4HU.mjs";
2
2
  import { t as Uuid } from "./uuid-CKMzlIND.mjs";
3
3
  //#region src/activity-delivery.d.ts
4
4
  /** The marks of what a delivery carried are the model's to decide. */
@@ -1 +1 @@
1
- {"version":3,"file":"activity-delivery.d.mts","names":[],"sources":["../src/activity-delivery.ts"],"mappings":";;;;KAsCK,gBAAgB,KACnB;UAIe;WACN,SAAS;WACT;;;;;;;;;KAUC,uBAAuB,KACjC;;;;WAMS,KAAK;WACL;WACA,oBAAoB,YAAY;WAChC,MAAM;WACN,qBAAqB;;WAErB,SAAS,SAAS;;WAElB,WAAW,SAAS;;;KAInB,wBAAwB,KAClC;WAUS;;KAGN,WAAW,KAAK;;WAEV;;;;;;;iBAQK,iBAAiB;WACtB,UAAU;WACV,qBAAqB;IAC5B;;;;;;;;iBAgJkB,cACpB,IAAI,YACF,WAAW,MAAM,OAAkB,SAAS,uBAC7C,QAAQ;;;;;;iBAuBW,eAAe,IAAI,UAAU,IAAI,OAAO;;;;;;;;;;;;iBA0ExC,oBACpB,IAAI,WAAW,aACf,YAAY,OACX;;;;;;;iBA+BmB,oBACpB,IAAI,UACJ,YAAY,MACZ,oBACC;;;;;;;;iBAyBmB,eACpB,IAAI,UACJ,OAAO,wBACN,QAAQ;;UAoBM;WACN;WACA;WACA;WACA;WACA;WACA;;WAEA;;WAEA,KAAK;;;;;;;;iBASM,eACpB,IAAI,UACJ,OAAO,qBACN"}
1
+ {"version":3,"file":"activity-delivery.d.mts","names":[],"sources":["../src/activity-delivery.ts"],"mappings":";;;;KAwCK,gBAAgB,KACnB;UAIe;WACN,SAAS;WACT;;;;;;;;;KAUC,uBAAuB,KACjC;;;;WAMS,KAAK;WACL;WACA,oBAAoB,YAAY;WAChC,MAAM;WACN,qBAAqB;;WAErB,SAAS,SAAS;;WAElB,WAAW,SAAS;;;KAInB,wBAAwB,KAClC;WAUS;;KAGN,WAAW,KAAK;;WAEV;;;;;;;iBAQK,iBAAiB;WACtB,UAAU;WACV,qBAAqB;IAC5B;;;;;;;;iBAgJkB,cACpB,IAAI,YACF,WAAW,MAAM,OAAkB,SAAS,uBAC7C,QAAQ;;;;;;iBAuBW,eAAe,IAAI,UAAU,IAAI,OAAO;;;;;;;;;;;;iBAsJxC,oBACpB,IAAI,WAAW,aACf,YAAY,OACX;;;;;;;iBA+BmB,oBACpB,IAAI,UACJ,YAAY,MACZ,oBACC;;;;;;;;iBAyBmB,eACpB,IAAI,UACJ,OAAO,wBACN,QAAQ;;UAoBM;WACN;WACA;WACA;WACA;WACA;WACA;;WAEA;;WAEA,KAAK;;;;;;;;iBASM,eACpB,IAAI,UACJ,OAAO,qBACN"}
@@ -1,4 +1,4 @@
1
- import { activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, actors, objects, resources } from "./schema.mjs";
1
+ import { activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, actors, objects, resourceRevisions, resources, revisionReceipts } from "./schema.mjs";
2
2
  import { uuidV7 } from "./uuid.mjs";
3
3
  import { storableText } from "./text.mjs";
4
4
  import { and, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
@@ -133,20 +133,45 @@ async function receiveInbound(db, id) {
133
133
  * and carries nothing. An unlinked delivery is left as is.
134
134
  */
135
135
  async function decideCarried(tx, deliveryId) {
136
- const [row] = await tx.select({
136
+ const [delivery] = await tx.select({
137
+ activityId: activityDeliveries.activityId,
137
138
  payload: activityDeliveries.payload,
138
- fetchedObject: activityDeliveries.fetchedObject,
139
- activity: activities.document,
140
- object: objects.document,
139
+ fetchedObject: activityDeliveries.fetchedObject
140
+ }).from(activityDeliveries).where(and(eq(activityDeliveries.id, deliveryId), eq(activityDeliveries.direction, "inbound"))).for("update");
141
+ if (delivery === void 0) return;
142
+ const [activity] = delivery.activityId === null ? [] : await tx.select({
143
+ id: activities.id,
144
+ document: activities.document
145
+ }).from(activities).where(eq(activities.id, delivery.activityId));
146
+ const [object] = activity === void 0 ? [] : await tx.select({
147
+ id: objects.id,
148
+ document: objects.document,
141
149
  fetched: objects.fetched
142
- }).from(activityDeliveries).innerJoin(activities, eq(activities.id, activityDeliveries.activityId)).leftJoin(objects, eq(objects.activityId, activityDeliveries.activityId)).where(and(eq(activityDeliveries.id, deliveryId), eq(activityDeliveries.direction, "inbound")));
143
- if (row == null) return;
144
- const carriedSnapshot = row.payload != null && isDeepStrictEqual(row.payload, row.activity);
145
- const carriedObjectSnapshot = carriedSnapshot && row.fetched != null && (!row.fetched || row.fetchedObject != null && isDeepStrictEqual(row.fetchedObject, row.object));
150
+ }).from(objects).where(eq(objects.activityId, activity.id)).for("key share");
151
+ await tx.delete(revisionReceipts).where(eq(revisionReceipts.deliveryId, deliveryId));
152
+ if (activity === void 0) return;
153
+ const carriedSnapshot = delivery.payload != null && isDeepStrictEqual(delivery.payload, activity.document);
154
+ const carriedObjectSnapshot = carriedSnapshot && object !== void 0 && (!object.fetched || delivery.fetchedObject != null && isDeepStrictEqual(delivery.fetchedObject, object.document));
146
155
  await tx.update(activityDeliveries).set({
147
156
  carriedSnapshot,
148
157
  carriedObjectSnapshot
149
158
  }).where(eq(activityDeliveries.id, deliveryId));
159
+ if (!carriedSnapshot) return;
160
+ const revisions = await tx.select().from(resourceRevisions).where(and(inArray(resourceRevisions.resourceId, object === void 0 ? [activity.id] : [activity.id, object.id]), eq(resourceRevisions.sequence, 1), eq(resourceRevisions.kind, "snapshot")));
161
+ const activityRevision = revisions.find((revision) => revision.resourceId === activity.id);
162
+ if (activityRevision === void 0 || !isDeepStrictEqual(activityRevision.document, activity.document)) return;
163
+ const receipts = [{
164
+ deliveryId,
165
+ revisionId: activityRevision.id,
166
+ role: "activity"
167
+ }];
168
+ const objectRevision = object === void 0 ? void 0 : revisions.find((revision) => revision.resourceId === object.id);
169
+ if (carriedObjectSnapshot && object !== void 0 && objectRevision !== void 0 && isDeepStrictEqual(objectRevision.document, object.document)) receipts.push({
170
+ deliveryId,
171
+ revisionId: objectRevision.id,
172
+ role: "object"
173
+ });
174
+ await tx.insert(revisionReceipts).values(receipts);
150
175
  }
151
176
  /**
152
177
  * Link an inbound delivery to the stored activity its activity IRI names.