@fedify/vocab-runtime 2.4.0-pr.936.41 → 2.5.0-dev.2271

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 (138) hide show
  1. package/deno.json +4 -2
  2. package/dist/{tests/docloader-Ck8bcBir.mjs → contexts-BK1CqBR5.cjs} +164 -275
  3. package/dist/{tests/docloader-S_gQZ2tt.cjs → contexts-DPuJ4UYL.js} +160 -294
  4. package/dist/{docloader-C_dir7Xb.d.ts → docloader-CYwqh5Df.d.cts} +66 -2
  5. package/dist/{docloader-D2DTRiyA.d.cts → docloader-CYwqh5Df.d.ts} +66 -2
  6. package/dist/internal/jsonld-cache.cjs +70 -1
  7. package/dist/internal/jsonld-cache.d.cts +35 -2
  8. package/dist/internal/jsonld-cache.d.ts +35 -2
  9. package/dist/internal/jsonld-cache.js +67 -2
  10. package/dist/internal/portable-dereference.cjs +721 -0
  11. package/dist/internal/portable-dereference.d.cts +349 -0
  12. package/dist/internal/portable-dereference.d.ts +349 -0
  13. package/dist/internal/portable-dereference.js +702 -0
  14. package/dist/internal/signed-representation.cjs +378 -0
  15. package/dist/internal/signed-representation.d.cts +144 -0
  16. package/dist/internal/signed-representation.d.ts +144 -0
  17. package/dist/internal/signed-representation.js +371 -0
  18. package/dist/jsonld.cjs +2 -2
  19. package/dist/mod.cjs +711 -4527
  20. package/dist/mod.d.cts +400 -8
  21. package/dist/mod.d.ts +400 -9
  22. package/dist/mod.js +692 -4522
  23. package/dist/portable-DqtfLy_1.d.cts +160 -0
  24. package/dist/portable-DtWsu2yU.d.ts +160 -0
  25. package/dist/tests/body-CVR1bABr.mjs +130 -0
  26. package/dist/tests/body-T_yQWql3.cjs +153 -0
  27. package/dist/tests/body.test.cjs +89 -0
  28. package/dist/tests/body.test.d.cts +1 -0
  29. package/dist/tests/body.test.d.mts +1 -0
  30. package/dist/tests/body.test.mjs +90 -0
  31. package/dist/tests/contexts-CIKsin4e.mjs +4512 -0
  32. package/dist/tests/contexts-DizzBjz4.cjs +4523 -0
  33. package/dist/tests/decimal.test.cjs +8 -7
  34. package/dist/tests/decimal.test.mjs +8 -6
  35. package/dist/tests/digest-3FeH2Y-Q.cjs +176 -0
  36. package/dist/tests/digest-COC7xDiQ.mjs +141 -0
  37. package/dist/tests/digest.test.cjs +102 -0
  38. package/dist/tests/digest.test.d.cts +1 -0
  39. package/dist/tests/digest.test.d.mts +1 -0
  40. package/dist/tests/digest.test.mjs +103 -0
  41. package/dist/tests/docloader-C6yApEts.mjs +373 -0
  42. package/dist/tests/docloader-CJK2w3l-.cjs +396 -0
  43. package/dist/tests/docloader.test.cjs +692 -39
  44. package/dist/tests/docloader.test.mjs +686 -34
  45. package/dist/tests/internal/multicodec.test.cjs +2 -3
  46. package/dist/tests/internal/multicodec.test.mjs +2 -2
  47. package/dist/tests/internal/portable-dereference.test.cjs +172 -0
  48. package/dist/tests/internal/portable-dereference.test.d.cts +1 -0
  49. package/dist/tests/internal/portable-dereference.test.d.mts +1 -0
  50. package/dist/tests/internal/portable-dereference.test.mjs +173 -0
  51. package/dist/tests/jsonld-cache-BPQmOZWD.mjs +342 -0
  52. package/dist/tests/jsonld-cache-C07AyNOY.cjs +397 -0
  53. package/dist/tests/jsonld-cache.test.cjs +101 -298
  54. package/dist/tests/jsonld-cache.test.mjs +94 -289
  55. package/dist/tests/{key-_wXwomh_.cjs → key-C-AYkdJJ.cjs} +11 -4
  56. package/dist/tests/{key-CDGDH_vC.mjs → key-C2Db_TAJ.mjs} +11 -3
  57. package/dist/tests/key.test.cjs +6 -5
  58. package/dist/tests/key.test.mjs +6 -4
  59. package/dist/tests/langstr.test.cjs +4 -4
  60. package/dist/tests/langstr.test.mjs +2 -2
  61. package/dist/tests/link.test.cjs +2 -3
  62. package/dist/tests/link.test.mjs +2 -2
  63. package/dist/tests/multibase/multibase.test.cjs +8 -9
  64. package/dist/tests/multibase/multibase.test.mjs +6 -6
  65. package/dist/tests/{multibase-Bz_UUDtL.cjs → multibase-B5Mea7Ip.cjs} +19 -2
  66. package/dist/tests/{multibase-B4bvakyA.mjs → multibase-BPnF_L4e.mjs} +12 -1
  67. package/dist/tests/portable-dereference-BNXtgg5U.cjs +278 -0
  68. package/dist/tests/portable-dereference-DRE5bz-l.mjs +249 -0
  69. package/dist/tests/portable-media-C4LEXJk4.mjs +148 -0
  70. package/dist/tests/portable-media-D05JJIJg.cjs +153 -0
  71. package/dist/tests/portable-media.test.cjs +222 -0
  72. package/dist/tests/portable-media.test.d.cts +1 -0
  73. package/dist/tests/portable-media.test.d.mts +1 -0
  74. package/dist/tests/portable-media.test.mjs +223 -0
  75. package/dist/tests/portable-workers.test.cjs +36 -0
  76. package/dist/tests/portable-workers.test.d.cts +2 -0
  77. package/dist/tests/portable-workers.test.d.mts +2 -0
  78. package/dist/tests/portable-workers.test.mjs +35 -0
  79. package/dist/tests/{request-uk51rkhO.cjs → request-C-VZ9TLj.cjs} +10 -4
  80. package/dist/tests/{request-C8CaGwtt.mjs → request-Cf-A3DU-.mjs} +8 -2
  81. package/dist/tests/request.test.cjs +7 -4
  82. package/dist/tests/request.test.mjs +5 -2
  83. package/dist/tests/signed-representation.test.cjs +588 -0
  84. package/dist/tests/signed-representation.test.d.cts +1 -0
  85. package/dist/tests/signed-representation.test.d.mts +1 -0
  86. package/dist/tests/signed-representation.test.mjs +589 -0
  87. package/dist/tests/temporal.test.cjs +1 -2
  88. package/dist/tests/temporal.test.mjs +1 -1
  89. package/dist/tests/url-BNakuZ8k.cjs +998 -0
  90. package/dist/tests/url-DMxmp7ZG.mjs +859 -0
  91. package/dist/tests/url.test.cjs +489 -6
  92. package/dist/tests/url.test.mjs +489 -5
  93. package/dist/url-DrGTR8yv.cjs +993 -0
  94. package/dist/url-Dzyp-NsC.js +860 -0
  95. package/package.json +27 -4
  96. package/scripts/test-bun.mjs +17 -0
  97. package/src/body.test.ts +125 -0
  98. package/src/body.ts +152 -0
  99. package/src/contexts/cid-v1.json +114 -0
  100. package/src/contexts/fep-22cd.json +21 -0
  101. package/src/contexts/miscellany.json +17 -0
  102. package/src/contexts.ts +39 -1
  103. package/src/digest.test.ts +220 -0
  104. package/src/digest.ts +229 -0
  105. package/src/docloader.test.ts +918 -27
  106. package/src/docloader.ts +320 -105
  107. package/src/internal/jsonld-cache.ts +97 -1
  108. package/src/internal/portable-dereference.test.ts +254 -0
  109. package/src/internal/portable-dereference.ts +1000 -0
  110. package/src/internal/signed-representation.ts +565 -0
  111. package/src/jsonld-cache.test.ts +89 -0
  112. package/src/key.test.ts +9 -0
  113. package/src/key.ts +11 -1
  114. package/src/mod.ts +28 -0
  115. package/src/multibase/multibase.test.ts +5 -5
  116. package/src/portable-media.test.ts +293 -0
  117. package/src/portable-media.ts +264 -0
  118. package/src/portable-workers.test.ts +81 -0
  119. package/src/portable.ts +180 -0
  120. package/src/preprocessor.ts +7 -0
  121. package/src/request.test.ts +10 -1
  122. package/src/request.ts +9 -1
  123. package/src/signed-representation.test.ts +338 -0
  124. package/src/url.test.ts +823 -3
  125. package/src/url.ts +700 -23
  126. package/tsdown.config.ts +2 -0
  127. package/dist/tests/url-CsOV_B_P.cjs +0 -482
  128. package/dist/tests/url-Du7RQQgP.mjs +0 -392
  129. package/dist/url-DD4F0ULf.cjs +0 -483
  130. package/dist/url-DGVbSVVi.js +0 -393
  131. /package/dist/{chunk-M78iaK0I.cjs → rolldown-runtime-B7lfambq.cjs} +0 -0
  132. /package/dist/tests/{langstr-CbAxaeEZ.cjs → langstr-C4Fl80ae.cjs} +0 -0
  133. /package/dist/tests/{langstr-Di5AvKpB.mjs → langstr-CQ26J_L7.mjs} +0 -0
  134. /package/dist/tests/{link-NUUWCdnK.mjs → link-Cevmc87v.mjs} +0 -0
  135. /package/dist/tests/{link-FguCydMA.cjs → link-DlKm8bEr.cjs} +0 -0
  136. /package/dist/tests/{multicodec-CxGVGa91.cjs → multicodec-CLRPeW4N.cjs} +0 -0
  137. /package/dist/tests/{multicodec-CyFp54fI.mjs → multicodec-CRIj_05H.mjs} +0 -0
  138. /package/dist/tests/{chunk-C2EiDwsr.cjs → rolldown-runtime-emK7D4bc.cjs} +0 -0
@@ -0,0 +1,702 @@
1
+
2
+ import { t as preloadedContexts } from "../contexts-DPuJ4UYL.js";
3
+ import { _ as parseIri, h as parseGatewayOrigin, i as canonicalizePortableUri, o as formatIri, s as fromCompatibleEf61Id, t as GATEWAY_HINT_PARAMETER, u as haveSameFe34Origin, y as toCompatibleEf61Id } from "../url-Dzyp-NsC.js";
4
+ import jsonld_default from "../jsonld.js";
5
+ import { createScopedContextLoader, registerDocumentLoaderWrapper, unwrapReleasedDocumentLoader } from "./jsonld-cache.js";
6
+ import { getLogger } from "@logtape/logtape";
7
+ import { SpanStatusCode } from "@opentelemetry/api";
8
+ //#region src/internal/portable-dereference.ts
9
+ const logger = getLogger([
10
+ "fedify",
11
+ "vocab",
12
+ "gateway"
13
+ ]);
14
+ /**
15
+ * The maximum number of `@gateway` location hints to try for one reference.
16
+ * Hints come from possibly untrusted documents, so they are bounded to keep
17
+ * a single accessor call from fanning out to many servers.
18
+ */
19
+ const MAX_GATEWAY_HINTS = 5;
20
+ const BASELINE_CONTEXT_URLS = /* @__PURE__ */ new Set([
21
+ "https://w3id.org/identity/v1",
22
+ "https://www.w3.org/ns/activitystreams",
23
+ "https://w3id.org/security/v1",
24
+ "https://w3id.org/security/data-integrity/v1"
25
+ ]);
26
+ /**
27
+ * The maximum number of links in a referrer chain passed to a
28
+ * {@link PortableObjectVerifier}. Longer chains are cut off and marked as
29
+ * truncated.
30
+ */
31
+ const MAX_REFERRER_CHAIN_LENGTH = 32;
32
+ const provenances = /* @__PURE__ */ new WeakMap();
33
+ function getObjectId(object) {
34
+ if (object == null || typeof object !== "object" || !("id" in object)) return null;
35
+ const id = object.id;
36
+ return id instanceof URL ? id : null;
37
+ }
38
+ /**
39
+ * Checks whether a vocabulary object is part of a chain of portable objects,
40
+ * i.e., whether it has a portable ID, has an FEP-ef61 compatible identifier
41
+ * as its ID (even a malformed one, so that it fails closed), or was obtained
42
+ * from a portable object. Accessors of such objects dereference references
43
+ * as portable objects.
44
+ *
45
+ * Being part of a chain does not mean that the object itself is verified:
46
+ * an object parsed from arbitrary JSON-LD is in a chain just because of its
47
+ * ID. Only {@link dereferencePortableIri} records that an object was
48
+ * accepted by a verifier.
49
+ *
50
+ * @internal Technically exported for generated vocabulary classes, but not
51
+ * part of the public API contract. This is not considered public API for
52
+ * Semantic Versioning decisions.
53
+ */
54
+ function isInPortableChain(object) {
55
+ if (provenances.has(object)) return true;
56
+ const id = getObjectId(object);
57
+ return id != null && (isPortableIri(id) || isCompatibleEf61Iri(id));
58
+ }
59
+ /**
60
+ * Checks whether a vocabulary object was accepted without an integrity
61
+ * proof, e.g., as an unsecured portable collection served by a trusted
62
+ * gateway. Objects embedded in such an object must not be trusted because
63
+ * of their origin.
64
+ *
65
+ * @internal Technically exported for generated vocabulary classes, but not
66
+ * part of the public API contract. This is not considered public API for
67
+ * Semantic Versioning decisions.
68
+ */
69
+ function isUnsecuredPortableObject(object) {
70
+ return provenances.get(object)?.acceptance === "unsecured";
71
+ }
72
+ /**
73
+ * Checks whether a URL is an FEP-ef61 compatible identifier, i.e., an HTTP(S)
74
+ * URL under a gateway's `/.well-known/apgateway/` path that stands for
75
+ * a portable object. Malformed compatible identifiers count as compatible
76
+ * identifiers too.
77
+ *
78
+ * @internal Technically exported for generated vocabulary classes, but not
79
+ * part of the public API contract. This is not considered public API for
80
+ * Semantic Versioning decisions.
81
+ */
82
+ function isCompatibleEf61Iri(url) {
83
+ try {
84
+ return fromCompatibleEf61Id(url) != null;
85
+ } catch (error) {
86
+ if (error instanceof TypeError) return true;
87
+ throw error;
88
+ }
89
+ }
90
+ /**
91
+ * Records that a vocabulary object returned by a property accessor was
92
+ * obtained through the given property of a portable object, so that later
93
+ * dereferences from it can tell where it came from. Nothing is recorded if
94
+ * the parent is not in a portable chain, or if the child already has its
95
+ * provenance.
96
+ *
97
+ * @internal Technically exported for generated vocabulary classes, but not
98
+ * part of the public API contract. This is not considered public API for
99
+ * Semantic Versioning decisions.
100
+ */
101
+ function recordPortableReferrer(parent, child, property) {
102
+ if (child == null || typeof child !== "object") return;
103
+ if (provenances.has(child) || !isInPortableChain(parent)) return;
104
+ provenances.set(child, { referrer: {
105
+ object: parent,
106
+ property
107
+ } });
108
+ }
109
+ /**
110
+ * Copies the provenance of a vocabulary object to its clone. The clone
111
+ * keeps where the original came from and the restriction on unsecured
112
+ * objects, but not a positive verification status nor a collection context,
113
+ * since the clone may have different property values.
114
+ *
115
+ * @internal Technically exported for generated vocabulary classes, but not
116
+ * part of the public API contract. This is not considered public API for
117
+ * Semantic Versioning decisions.
118
+ */
119
+ function copyPortableProvenance(from, to) {
120
+ const provenance = provenances.get(from);
121
+ if (provenance == null) return;
122
+ provenances.set(to, {
123
+ referrer: provenance.referrer,
124
+ ...provenance.acceptance === "unsecured" ? { acceptance: "unsecured" } : {}
125
+ });
126
+ }
127
+ /**
128
+ * Recognizes an FEP-ef61 compatible identifier to dereference as a portable
129
+ * object.
130
+ *
131
+ * @returns `undefined` if the URL is not a compatible identifier; `null` if
132
+ * it is a malformed compatible identifier; otherwise, the portable
133
+ * ID it stands for and the gateway it names.
134
+ * @internal Technically exported for generated vocabulary classes, but not
135
+ * part of the public API contract. This is not considered public API for
136
+ * Semantic Versioning decisions.
137
+ */
138
+ function parseCompatibleEf61Reference(url) {
139
+ try {
140
+ const id = fromCompatibleEf61Id(url);
141
+ if (id == null) return void 0;
142
+ if (typeof url === "string") url = new URL(url);
143
+ return {
144
+ id,
145
+ gateway: new URL(url.origin)
146
+ };
147
+ } catch (error) {
148
+ if (error instanceof TypeError) {
149
+ logger.debug("Invalid FEP-ef61 compatible identifier {url}: {error}", {
150
+ url: typeof url === "string" ? url : url.href,
151
+ error
152
+ });
153
+ return null;
154
+ }
155
+ throw error;
156
+ }
157
+ }
158
+ /**
159
+ * Checks whether a property accessor call on a vocabulary object applies the
160
+ * FEP-ef61 portable object policy, i.e., whether the `verifyPortableObject`
161
+ * option is given or the object is part of a chain of portable objects.
162
+ * In this mode, compatible identifiers are dereferenced as portable objects,
163
+ * and fetched documents that turn out to stand for portable objects are
164
+ * verified as such.
165
+ *
166
+ * @internal Technically exported for generated vocabulary classes, but not
167
+ * part of the public API contract. This is not considered public API for
168
+ * Semantic Versioning decisions.
169
+ */
170
+ function isPortableMode(object, options) {
171
+ return options.verifyPortableObject != null || isInPortableChain(object);
172
+ }
173
+ /**
174
+ * Checks whether an object embedded in a property of a vocabulary object has
175
+ * to be dereferenced by its `@id` and verified as a portable object rather
176
+ * than trusted as embedded, even with `crossOrigin: "trust"`. This is the
177
+ * case in {@link isPortableMode | portable mode} if its `@id` is an FEP-ef61
178
+ * compatible identifier, or a portable IRI whose DID differs from the
179
+ * owner's portable ID.
180
+ *
181
+ * @param parent The object whose property embeds the object.
182
+ * @param ownerId The ID of the object that vouches for embedded objects, or
183
+ * `null` if embedded objects are not trusted by their owner.
184
+ * @param id The `@id` of the embedded object.
185
+ * @param options The options of the accessor.
186
+ * @internal Technically exported for generated vocabulary classes, but not
187
+ * part of the public API contract. This is not considered public API for
188
+ * Semantic Versioning decisions.
189
+ */
190
+ function mustDereferencePortableObject(parent, ownerId, id, options) {
191
+ if (!isPortableMode(parent, options)) return false;
192
+ if (isCompatibleEf61Iri(id)) return true;
193
+ if (!isPortableIri(id)) return false;
194
+ return ownerId == null || !isPortableIri(ownerId) || !haveSameFe34Origin(ownerId, id);
195
+ }
196
+ const PORTABLE_IRI_PATTERN = /^ap(?:\+ef61)?:/i;
197
+ /**
198
+ * Finds out whether a document fetched as an ordinary HTTP(S) document
199
+ * claims to be a portable object: its final URL is a portable IRI or an
200
+ * FEP-ef61 compatible identifier, or else its `@id` is. The final URL takes
201
+ * precedence, so a document whose `@id` claims another object fails the
202
+ * identity check against the final URL.
203
+ *
204
+ * @param documentUrl The final URL of the document.
205
+ * @param objectId The `@id` of the parsed document.
206
+ * @returns `undefined` if the document does not claim to be a portable
207
+ * object; `null` if the claim is malformed; otherwise, the claim.
208
+ * @internal Technically exported for generated vocabulary classes, but not
209
+ * part of the public API contract. This is not considered public API for
210
+ * Semantic Versioning decisions.
211
+ */
212
+ function getPortableResponseClaim(documentUrl, objectId) {
213
+ if (PORTABLE_IRI_PATTERN.test(documentUrl)) {
214
+ let id;
215
+ try {
216
+ id = parseIri(documentUrl);
217
+ if (canonicalizePortableUri(documentUrl) !== canonicalizePortableUri(formatIri(id))) return null;
218
+ } catch (error) {
219
+ if (error instanceof TypeError) return null;
220
+ throw error;
221
+ }
222
+ return {
223
+ id,
224
+ inferredGateways: getPortableGatewayCandidates(id)
225
+ };
226
+ }
227
+ for (const url of [documentUrl, objectId]) {
228
+ if (url == null) continue;
229
+ const compatible = parseCompatibleEf61Reference(url);
230
+ if (compatible === null) return null;
231
+ if (compatible != null) return {
232
+ id: compatible.id,
233
+ inferredGateways: [compatible.gateway]
234
+ };
235
+ if (url instanceof URL && isPortableIri(url)) return {
236
+ id: url,
237
+ inferredGateways: getPortableGatewayCandidates(url)
238
+ };
239
+ }
240
+ }
241
+ const unverifiedPortableClaims = /* @__PURE__ */ new WeakSet();
242
+ /**
243
+ * Records that an object fetched as an ordinary HTTP(S) object stands for
244
+ * a portable object if its reference, its final URL, or its `@id` is
245
+ * a portable IRI or an FEP-ef61 compatible identifier. Accessors do not
246
+ * cache such objects in their parents, so that a later call with the
247
+ * `verifyPortableObject` option dereferences and verifies them.
248
+ *
249
+ * @internal Technically exported for generated vocabulary classes, but not
250
+ * part of the public API contract. This is not considered public API for
251
+ * Semantic Versioning decisions.
252
+ */
253
+ function markUnverifiedPortableClaim(object, reference, documentUrl) {
254
+ const objectId = getObjectId(object);
255
+ if (isPortableIri(reference) || isCompatibleEf61Iri(reference) || PORTABLE_IRI_PATTERN.test(documentUrl) || isCompatibleEf61Iri(documentUrl) || objectId != null && (isPortableIri(objectId) || isCompatibleEf61Iri(objectId))) unverifiedPortableClaims.add(object);
256
+ }
257
+ /**
258
+ * Checks whether an object was fetched as an ordinary HTTP(S) object although
259
+ * it stands for a portable object. See {@link markUnverifiedPortableClaim}.
260
+ *
261
+ * @internal Technically exported for generated vocabulary classes, but not
262
+ * part of the public API contract. This is not considered public API for
263
+ * Semantic Versioning decisions.
264
+ */
265
+ function isUnverifiedPortableClaim(object) {
266
+ return unverifiedPortableClaims.has(object);
267
+ }
268
+ /**
269
+ * Rejects a malformed FEP-ef61 compatible identifier found in a reference,
270
+ * the final URL of a fetched document, or its `@id`, when it would be
271
+ * dereferenced as a portable object. It is rejected without a request (or
272
+ * without returning the fetched document), since it cannot be verified as
273
+ * a portable object, and fetching it as an ordinary HTTP(S) object would
274
+ * skip the portable object policy.
275
+ *
276
+ * @param url The rejected URL, for the log message.
277
+ * @param options The options of the accessor.
278
+ * @returns Always `null`.
279
+ * @throws {Error} If `crossOrigin` is `"throw"` and `suppressError` is not
280
+ * set.
281
+ * @internal Technically exported for generated vocabulary classes, but not
282
+ * part of the public API contract. This is not considered public API for
283
+ * Semantic Versioning decisions.
284
+ */
285
+ function rejectMalformedCompatibleReference(url, options) {
286
+ const message = "Refusing to dereference {url}, because it is a malformed FEP-ef61 compatible identifier, which cannot be verified as a portable object.";
287
+ if (options.crossOrigin === "throw" && !options.suppressError) throw new PortableObjectRejectedError(message.replace("{url}", url));
288
+ logger.warn(message, { url });
289
+ return null;
290
+ }
291
+ /**
292
+ * Logs that an embedded object without `@id` in an object accepted without
293
+ * an integrity proof is dropped, because it cannot be dereferenced and
294
+ * verified on its own.
295
+ *
296
+ * @internal Technically exported for generated vocabulary classes, but not
297
+ * part of the public API contract. This is not considered public API for
298
+ * Semantic Versioning decisions.
299
+ */
300
+ function warnUnverifiableEmbeddedObject(parent, property) {
301
+ logger.warn("Dropping an embedded object without @id in the {property} property of {parentId}, because the parent was accepted without an integrity proof and the embedded object cannot be verified on its own.", {
302
+ property,
303
+ parentId: getObjectId(parent)?.href ?? null
304
+ });
305
+ }
306
+ function buildReferrerChain(link, depth = 0) {
307
+ if (link == null) return void 0;
308
+ const provenance = provenances.get(link.object);
309
+ const base = {
310
+ object: link.object,
311
+ id: getObjectId(link.object),
312
+ property: link.property,
313
+ ...provenance?.acceptance == null ? {} : { acceptance: provenance.acceptance },
314
+ ...provenance?.collectionContext === void 0 ? {} : { collectionContext: provenance.collectionContext }
315
+ };
316
+ if (provenance?.referrer == null) return base;
317
+ if (depth + 1 >= MAX_REFERRER_CHAIN_LENGTH) return {
318
+ ...base,
319
+ truncated: true
320
+ };
321
+ return {
322
+ ...base,
323
+ referrer: buildReferrerChain(provenance.referrer, depth + 1)
324
+ };
325
+ }
326
+ /**
327
+ * Checks whether a URL is an FEP-ef61 portable ActivityPub IRI.
328
+ *
329
+ * @internal Technically exported for generated vocabulary classes, but not
330
+ * part of the public API contract. This is not considered public API for
331
+ * Semantic Versioning decisions.
332
+ */
333
+ function isPortableIri(url) {
334
+ return url.protocol === "ap+ef61:" || url.protocol === "ap:";
335
+ }
336
+ /**
337
+ * Picks the ordered list of FEP-ef61 gateways to fetch a portable IRI from.
338
+ *
339
+ * If `gateways` is given, it is used as is (even when empty), and `@gateway`
340
+ * location hints in the IRI are ignored. Otherwise, up to
341
+ * {@link MAX_GATEWAY_HINTS} valid `@gateway` hints are used. Duplicate
342
+ * gateways are dropped in both cases.
343
+ *
344
+ * @throws {TypeError} If an explicit gateway is not an HTTP(S) origin.
345
+ * @internal
346
+ */
347
+ function getPortableGatewayCandidates(url, gateways) {
348
+ const candidates = [];
349
+ const seen = /* @__PURE__ */ new Set();
350
+ const add = (gateway) => {
351
+ if (seen.has(gateway.href)) return;
352
+ seen.add(gateway.href);
353
+ candidates.push(gateway);
354
+ };
355
+ if (gateways != null) {
356
+ for (const gateway of gateways) {
357
+ const parsed = parseGatewayOrigin(gateway);
358
+ if (parsed == null) throw new TypeError("FEP-ef61 gateways must be HTTP(S) origins with no credentials, path, query, or fragment: " + String(gateway));
359
+ add(parsed);
360
+ }
361
+ return candidates;
362
+ }
363
+ for (const hint of new URLSearchParams(url.search).getAll(GATEWAY_HINT_PARAMETER)) {
364
+ if (candidates.length >= MAX_GATEWAY_HINTS) break;
365
+ const parsed = parseGatewayOrigin(hint);
366
+ if (parsed == null) {
367
+ logger.debug("Ignoring an invalid FEP-ef61 gateway hint {hint} in {url}.", {
368
+ hint,
369
+ url: formatIri(url)
370
+ });
371
+ continue;
372
+ }
373
+ add(parsed);
374
+ }
375
+ return candidates;
376
+ }
377
+ /**
378
+ * Gets the gateways through which a portable reference without location hints
379
+ * can be dereferenced, from the portable actor that the reference belongs to.
380
+ *
381
+ * The references in a portable actor's own document, such as its `outbox`,
382
+ * usually have no `@gateway` hints, as they are not needed there, since
383
+ * the actor's `gateways` already tells where to retrieve them. So this walks
384
+ * from the object whose property is being dereferenced up through the objects
385
+ * it was obtained from, e.g., from a collection page to the collection and
386
+ * then to the actor, and returns the `gateways` of the first object that has
387
+ * any, but only if that object has the same DID as the reference. The
388
+ * gateways only tell where to look; whatever they serve is still verified.
389
+ *
390
+ * @param object The object whose property is being dereferenced.
391
+ * @param url The portable IRI to dereference.
392
+ * @returns Up to {@link MAX_GATEWAY_HINTS} valid gateways, or `undefined` if
393
+ * the IRI has valid `@gateway` hints or no such object is found.
394
+ * @internal Technically exported for generated vocabulary classes, but not
395
+ * part of the public API contract. This is not considered public API for
396
+ * Semantic Versioning decisions.
397
+ */
398
+ function getReferrerGateways(object, url) {
399
+ if (getPortableGatewayCandidates(url).length > 0) return void 0;
400
+ const visited = /* @__PURE__ */ new Set();
401
+ let current = object;
402
+ while (current != null && !visited.has(current)) {
403
+ visited.add(current);
404
+ const gateways = "gateways" in current ? current.gateways : void 0;
405
+ if (Array.isArray(gateways) && gateways.length > 0) {
406
+ const id = getObjectId(current);
407
+ const portableId = id == null ? null : isPortableIri(id) ? id : getCompatibleEf61Target(id);
408
+ if (portableId == null || !haveSameFe34Origin(portableId, url)) return;
409
+ const candidates = [];
410
+ for (const gateway of gateways) {
411
+ if (candidates.length >= MAX_GATEWAY_HINTS) break;
412
+ if (typeof gateway !== "string" && !(gateway instanceof URL)) continue;
413
+ const parsed = parseGatewayOrigin(gateway);
414
+ if (parsed == null) continue;
415
+ if (candidates.some((c) => c.href === parsed.href)) continue;
416
+ candidates.push(parsed);
417
+ }
418
+ return candidates.length > 0 ? candidates : void 0;
419
+ }
420
+ current = provenances.get(current)?.referrer?.object;
421
+ }
422
+ }
423
+ function getCompatibleEf61Target(id) {
424
+ try {
425
+ return fromCompatibleEf61Id(id);
426
+ } catch {
427
+ return null;
428
+ }
429
+ }
430
+ /**
431
+ * Creates a context loader that returns the same context documents for the
432
+ * whole dereference operation, so that the identity check, the proof
433
+ * verifier, and the parser interpret the fetched document identically even
434
+ * if the underlying loader is nondeterministic. Failed loads are not
435
+ * remembered, so a transient failure does not affect the next gateway.
436
+ *
437
+ * The parsed object keeps the loader for its own later dereferences, so
438
+ * `release()` turns it into a plain pass-through to the underlying loader
439
+ * once the operation is over.
440
+ *
441
+ * @internal Technically exported for generated vocabulary classes, but not
442
+ * part of the public API contract. This is not considered public API for
443
+ * Semantic Versioning decisions.
444
+ */
445
+ function createSnapshotContextLoader(contextLoader, suppressError) {
446
+ contextLoader = unwrapReleasedDocumentLoader(contextLoader);
447
+ const cache = /* @__PURE__ */ new Map();
448
+ let released = false;
449
+ const release = () => {
450
+ released = true;
451
+ state.released = true;
452
+ cache.clear();
453
+ };
454
+ const loader = async (url, options) => {
455
+ if (released) return await contextLoader(url, options);
456
+ const key = URL.canParse(url) ? new URL(url).href : url;
457
+ if (BASELINE_CONTEXT_URLS.has(key)) return {
458
+ contextUrl: null,
459
+ document: structuredClone(preloadedContexts[key]),
460
+ documentUrl: key
461
+ };
462
+ let promise = cache.get(key);
463
+ if (promise == null) {
464
+ const loading = contextLoader(url, suppressError ? {
465
+ ...options,
466
+ suppressError: true
467
+ } : options).then((document) => structuredClone(document));
468
+ promise = loading;
469
+ cache.set(key, loading);
470
+ loading.catch(() => {
471
+ if (cache.get(key) === loading) cache.delete(key);
472
+ });
473
+ }
474
+ return structuredClone(await promise);
475
+ };
476
+ const state = {
477
+ base: contextLoader,
478
+ released: false
479
+ };
480
+ registerDocumentLoaderWrapper(loader, state);
481
+ return {
482
+ loader,
483
+ release
484
+ };
485
+ }
486
+ /**
487
+ * The error thrown by {@link dereferencePortableIri} under
488
+ * `crossOrigin: "throw"` when gateways returned objects but none of them
489
+ * satisfied the identity and proof checks.
490
+ *
491
+ * @internal Not part of the public API contract.
492
+ */
493
+ var PortableObjectRejectedError = class extends Error {
494
+ constructor(message) {
495
+ super(message);
496
+ this.name = "PortableObjectRejectedError";
497
+ }
498
+ };
499
+ var PortableObjectRejection = class {
500
+ message;
501
+ values;
502
+ constructor(message, values = {}) {
503
+ this.message = message;
504
+ this.values = values;
505
+ }
506
+ };
507
+ /**
508
+ * Dereferences an FEP-ef61 portable IRI through its gateways.
509
+ *
510
+ * Gateways are tried one by one until one of them returns a single-node
511
+ * document whose `@id`, if any, canonically matches the requested IRI and
512
+ * which passes `verifyPortableObject`. When there is no gateway to try, the
513
+ * document loader is asked for the portable IRI itself, and its result is
514
+ * validated the same way. If the `response` option is given, only that
515
+ * document is validated, and nothing is fetched.
516
+ *
517
+ * @returns The parsed object, or `null` if no valid object was retrieved and
518
+ * `suppressError` is set or the failure was a rejected object
519
+ * (unless `crossOrigin` is `"throw"`).
520
+ * @throws {TypeError} If `gateways` has an invalid entry (always), if no
521
+ * verifier is given, or if the IRI cannot be turned into
522
+ * a gateway URL (unless `suppressError` is set).
523
+ * @internal Technically exported for generated vocabulary classes, but not
524
+ * part of the public API contract. This is not considered public API for
525
+ * Semantic Versioning decisions.
526
+ */
527
+ async function dereferencePortableIri(url, options) {
528
+ url = parseIri(url);
529
+ const lookupUrl = formatIri(url);
530
+ const { span } = options;
531
+ const explicitGateways = options.gateways == null ? void 0 : getPortableGatewayCandidates(url, options.gateways);
532
+ const inferredGateways = options.inferredGateways ?? (explicitGateways == null ? getPortableGatewayCandidates(url) : []);
533
+ const gateways = [...inferredGateways];
534
+ for (const gateway of explicitGateways ?? []) if (!gateways.some((g) => g.href === gateway.href)) gateways.push(gateway);
535
+ const fail = (error) => {
536
+ span?.setStatus({
537
+ code: SpanStatusCode.ERROR,
538
+ message: String(error)
539
+ });
540
+ if (options.suppressError) {
541
+ logger.warn("Failed to dereference {url}: {error}", {
542
+ url: lookupUrl,
543
+ error
544
+ });
545
+ return null;
546
+ }
547
+ throw error;
548
+ };
549
+ const verify = options.verifyPortableObject;
550
+ if (verify == null) return fail(/* @__PURE__ */ new TypeError("Dereferencing the portable object " + lookupUrl + " requires the verifyPortableObject option, e.g., verifyPortableObject() from @fedify/fedify. Passing a Fedify Context as the options gives it, and objects parsed with the option use it by default."));
551
+ const requestUrls = [];
552
+ let expectedId;
553
+ try {
554
+ expectedId = canonicalizePortableUri(lookupUrl);
555
+ if (options.response != null) requestUrls.push({
556
+ url: options.response.documentUrl,
557
+ gateway: null,
558
+ response: options.response
559
+ });
560
+ else for (const gateway of gateways) requestUrls.push({
561
+ url: toCompatibleEf61Id(url, gateway).href,
562
+ gateway
563
+ });
564
+ } catch (error) {
565
+ return fail(error);
566
+ }
567
+ if (requestUrls.length < 1) requestUrls.push({
568
+ url: lookupUrl,
569
+ gateway: null
570
+ });
571
+ const snapshot = createSnapshotContextLoader(options.contextLoader, options.suppressError);
572
+ const contextLoader = snapshot.loader;
573
+ const scopedDocument = createScopedContextLoader(options.documentLoader, options.suppressError);
574
+ const attempts = [];
575
+ const { signal } = options;
576
+ const gatewayHints = explicitGateways == null && inferredGateways.length > 0 ? inferredGateways : void 0;
577
+ const referrer = buildReferrerChain(options.referrer);
578
+ try {
579
+ for (const { url: requestUrl, gateway, response } of requestUrls) {
580
+ signal?.throwIfAborted();
581
+ let remoteDocument;
582
+ try {
583
+ remoteDocument = response ?? await options.documentLoader(requestUrl, {
584
+ signal,
585
+ suppressError: options.suppressError
586
+ });
587
+ } catch (error) {
588
+ signal?.throwIfAborted();
589
+ logger.debug("Failed to fetch {url} from {requestUrl}: {error}", {
590
+ url: lookupUrl,
591
+ requestUrl,
592
+ error
593
+ });
594
+ attempts.push({
595
+ type: "error",
596
+ error
597
+ });
598
+ continue;
599
+ }
600
+ const { document } = remoteDocument;
601
+ try {
602
+ await checkPortableObjectId(document, expectedId, contextLoader);
603
+ let documentUrl;
604
+ try {
605
+ documentUrl = parseIri(remoteDocument.documentUrl);
606
+ } catch {
607
+ documentUrl = void 0;
608
+ }
609
+ let result;
610
+ try {
611
+ result = await verify(document, {
612
+ documentLoader: scopedDocument.loader,
613
+ contextLoader,
614
+ tracerProvider: options.tracerProvider,
615
+ ...documentUrl == null ? {} : { documentUrl },
616
+ ...explicitGateways == null ? {} : { gateways: explicitGateways },
617
+ ...gatewayHints == null ? {} : { gatewayHints },
618
+ ...referrer == null ? {} : { referrer }
619
+ });
620
+ } catch (error) {
621
+ throw new PortableObjectRejection("the proof verifier failed: {error}", { error });
622
+ }
623
+ if (!result.verified) throw new PortableObjectRejection("it does not satisfy the FEP-ef61 proof policy: {result}", { result });
624
+ const object = await options.parse(document, {
625
+ contextLoader,
626
+ baseUrl: url
627
+ });
628
+ signal?.throwIfAborted();
629
+ if (object != null && typeof object === "object") provenances.set(object, {
630
+ acceptance: result.unsecured === true ? "unsecured" : "verified",
631
+ ...result.collectionContext === void 0 ? {} : { collectionContext: result.collectionContext },
632
+ ...options.referrer == null ? {} : { referrer: options.referrer }
633
+ });
634
+ if (gateway != null) span?.setAttribute("activitypub.gateway", gateway.href);
635
+ return object;
636
+ } catch (error) {
637
+ signal?.throwIfAborted();
638
+ if (error instanceof PortableObjectRejection) {
639
+ logger.warn("Rejected the portable object {url} served from {requestUrl}, because " + error.message, {
640
+ ...error.values,
641
+ url: lookupUrl,
642
+ requestUrl
643
+ });
644
+ attempts.push({
645
+ type: "rejected",
646
+ source: requestUrl
647
+ });
648
+ continue;
649
+ }
650
+ logger.debug("Failed to parse {url} from {requestUrl}: {error}", {
651
+ url: lookupUrl,
652
+ requestUrl,
653
+ error
654
+ });
655
+ attempts.push({
656
+ type: "error",
657
+ error
658
+ });
659
+ }
660
+ }
661
+ } finally {
662
+ scopedDocument.release();
663
+ snapshot.release();
664
+ }
665
+ const rejected = attempts.filter((a) => a.type === "rejected");
666
+ if (rejected.length > 0) {
667
+ const message = "No gateway returned a valid portable object for " + lookupUrl + "; refusing to return the object. Objects retrieved from: " + rejected.map((a) => a.source).join(", ") + ".";
668
+ if (options.suppressError || options.crossOrigin !== "throw") {
669
+ span?.setStatus({
670
+ code: SpanStatusCode.ERROR,
671
+ message
672
+ });
673
+ logger.warn(message);
674
+ return null;
675
+ }
676
+ throw new PortableObjectRejectedError(message);
677
+ }
678
+ const errors = attempts.flatMap((a) => a.type === "error" ? [a.error] : []);
679
+ return fail(errors.length === 1 ? errors[0] : new AggregateError(errors, "Failed to dereference " + lookupUrl + " through any of its gateways: " + requestUrls.map((r) => r.url).join(", ")));
680
+ }
681
+ async function checkPortableObjectId(document, expectedId, contextLoader) {
682
+ if (document == null || typeof document !== "object" || Array.isArray(document)) throw new PortableObjectRejection("it is not a single JSON object");
683
+ const expanded = await jsonld_default.expand(document, {
684
+ documentLoader: contextLoader,
685
+ keepFreeFloatingNodes: true
686
+ });
687
+ if (expanded.length !== 1) throw new PortableObjectRejection("it does not have exactly one top-level node");
688
+ const id = expanded[0]["@id"];
689
+ if (id == null) return;
690
+ if (typeof id !== "string") throw new PortableObjectRejection("it has an invalid @id");
691
+ let actualId;
692
+ try {
693
+ const portable = fromCompatibleEf61Id(id);
694
+ actualId = canonicalizePortableUri(portable == null ? id : formatIri(portable));
695
+ } catch (error) {
696
+ if (!(error instanceof TypeError)) throw error;
697
+ actualId = null;
698
+ }
699
+ if (actualId !== expectedId) throw new PortableObjectRejection("its @id ({objectId}) does not match the requested portable ID", { objectId: id });
700
+ }
701
+ //#endregion
702
+ export { PortableObjectRejectedError, copyPortableProvenance, createSnapshotContextLoader, dereferencePortableIri, getPortableGatewayCandidates, getPortableResponseClaim, getReferrerGateways, isCompatibleEf61Iri, isInPortableChain, isPortableIri, isPortableMode, isUnsecuredPortableObject, isUnverifiedPortableClaim, markUnverifiedPortableClaim, mustDereferencePortableObject, parseCompatibleEf61Reference, recordPortableReferrer, rejectMalformedCompatibleReference, warnUnverifiableEmbeddedObject };