@fedify/fedify 2.4.0-dev.2122 → 2.4.0-dev.2129

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 (98) hide show
  1. package/dist/{builder-BCXywsZF.mjs → builder-C0bxZDL0.mjs} +3 -3
  2. package/dist/compat/mod.d.cts +1 -1
  3. package/dist/compat/mod.d.ts +1 -1
  4. package/dist/compat/transformers.test.mjs +1 -1
  5. package/dist/{compound-proof-Fxd45Oy5.mjs → compound-proof-D9Kljk_7.mjs} +3 -3
  6. package/dist/{context-tOiJfBoD.d.ts → context-Cz1w5Krc.d.ts} +31 -5
  7. package/dist/{context-CoNRxGYp.mjs → context-DfSVPcJ8.mjs} +6 -3
  8. package/dist/{context-SMNOiiY6.d.cts → context-Dvec_D_h.d.cts} +31 -5
  9. package/dist/{deno-BZrnW0Qz.mjs → deno-_o3lkDlG.mjs} +1 -1
  10. package/dist/{docloader-3BHaS20Z.mjs → docloader-BbS0rO-Y.mjs} +7 -7
  11. package/dist/federation/builder.test.mjs +1 -1
  12. package/dist/federation/compound-fanout.test.mjs +3 -3
  13. package/dist/federation/handler-compound-proof.test.mjs +4 -4
  14. package/dist/federation/handler.test.mjs +6 -6
  15. package/dist/federation/hashlink-media.test.mjs +2 -2
  16. package/dist/federation/idempotency.test.mjs +2 -2
  17. package/dist/federation/metrics.test.mjs +1 -1
  18. package/dist/federation/middleware.test.mjs +8 -8
  19. package/dist/federation/mod.cjs +1 -1
  20. package/dist/federation/mod.d.cts +2 -2
  21. package/dist/federation/mod.d.ts +2 -2
  22. package/dist/federation/mod.js +1 -1
  23. package/dist/federation/outgoing-proof.test.mjs +6 -6
  24. package/dist/federation/portable-actor.test.mjs +3 -3
  25. package/dist/federation/portable-chain.test.d.mts +2 -0
  26. package/dist/federation/portable-chain.test.mjs +358 -0
  27. package/dist/federation/portable-gateway-keys.test.mjs +77 -6
  28. package/dist/federation/portable-inbox.test.mjs +9 -4
  29. package/dist/federation/portable.test.mjs +3 -3
  30. package/dist/federation/send.test.mjs +3 -3
  31. package/dist/federation/tasks/enqueue.test.mjs +2 -2
  32. package/dist/federation/tasks/tasks.test.mjs +3 -3
  33. package/dist/federation/temporal.test.mjs +1 -1
  34. package/dist/federation/webfinger.test.mjs +2 -2
  35. package/dist/{federation-Ml6NrgRV.cjs → federation-DRY8KrkB.cjs} +46 -22
  36. package/dist/{http-4bmgw-mA.cjs → http-B1J6E-bT.cjs} +384 -33
  37. package/dist/{http-B9BQDNIy.mjs → http-BpOiZE09.mjs} +18 -12
  38. package/dist/{http-D76Py0M4.d.cts → http-C-x_OLSp.d.ts} +57 -14
  39. package/dist/{http-BETASGl0.js → http-C2M6wcs8.js} +374 -35
  40. package/dist/{http-BrQgkJay.d.ts → http-CjezPjFX.d.cts} +57 -14
  41. package/dist/{key-PyYvun0F.mjs → key-DolJjJab.mjs} +103 -16
  42. package/dist/{kv-cache-CPqUxRL3.mjs → kv-cache-Bq2cah0c.mjs} +1 -1
  43. package/dist/{kv-cache-C4mv2ZFQ.js → kv-cache-D7TiyMxv.js} +6 -6
  44. package/dist/{kv-cache-D2Bz6t_c.cjs → kv-cache-D9nRbG2Q.cjs} +6 -6
  45. package/dist/{ld-u4JOD4iO.mjs → ld-Dwc176V4.mjs} +3 -3
  46. package/dist/{metrics-DCLoLvLz.mjs → metrics-CDaHfBXY.mjs} +1 -1
  47. package/dist/{middleware-B7bmtONC.mjs → middleware-CmB1FD8A.mjs} +1 -1
  48. package/dist/{middleware-DWlAGlyP.js → middleware-CylX-pvI.js} +52 -28
  49. package/dist/{middleware-CgOqRkK-.mjs → middleware-DN3MdTDg.mjs} +64 -39
  50. package/dist/{mod-CTh7ijx5.d.ts → mod-Bz9tFXI2.d.ts} +14 -3
  51. package/dist/{mod-Cwdt_CWU.d.ts → mod-CZetqT5h.d.ts} +1 -1
  52. package/dist/{mod-Cr79cQlc.d.cts → mod-D4g9ffEn.d.cts} +1 -1
  53. package/dist/{mod-DnElMslb.d.cts → mod-DGOIxEfb.d.cts} +1 -1
  54. package/dist/{mod-DMdGFMEl.d.cts → mod-S--JxYjo.d.cts} +14 -3
  55. package/dist/{mod-COWgSo2v.d.ts → mod-owwElvpw.d.ts} +1 -1
  56. package/dist/mod.cjs +8 -8
  57. package/dist/mod.d.cts +5 -5
  58. package/dist/mod.d.ts +5 -5
  59. package/dist/mod.js +5 -5
  60. package/dist/nodeinfo/handler.test.mjs +2 -2
  61. package/dist/{owner-CPFM-sqo.mjs → owner-BNHhwjNu.mjs} +37 -4
  62. package/dist/{sig-C1xOA4ml.js → portable-collection-CRpTUHCY.mjs} +5 -4
  63. package/dist/portable-collection-CgglAI9B.js +656 -0
  64. package/dist/{sig-Cb9VSeiF.cjs → portable-collection-PTGD0q70.cjs} +253 -2
  65. package/dist/portable-key-DqX2emHQ.mjs +395 -0
  66. package/dist/{portable-key-id-T7lecIbt.mjs → portable-key-id-Bg259c4Z.mjs} +69 -2
  67. package/dist/{proof-BCOg7Njv.mjs → proof-B4_0E-KU.mjs} +5 -5
  68. package/dist/{send-C8eOPat3.mjs → send-Dpu5qbP5.mjs} +3 -3
  69. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  70. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  71. package/dist/sig/compound-proof-verification.test.mjs +2 -2
  72. package/dist/sig/compound-proof.test.mjs +2 -2
  73. package/dist/sig/http.test.mjs +2 -2
  74. package/dist/sig/key.test.mjs +1 -1
  75. package/dist/sig/ld.test.mjs +2 -2
  76. package/dist/sig/mod.cjs +5 -6
  77. package/dist/sig/mod.d.cts +2 -2
  78. package/dist/sig/mod.d.ts +2 -2
  79. package/dist/sig/mod.js +2 -3
  80. package/dist/sig/owner.test.mjs +1 -1
  81. package/dist/sig/portable-collection.test.mjs +20 -431
  82. package/dist/sig/portable-key.test.mjs +479 -5
  83. package/dist/sig/proof.test.mjs +3 -3
  84. package/dist/{temporal-vjHOhBpy.mjs → temporal-78JVR3GK.mjs} +1 -1
  85. package/dist/testing/kv.test.mjs +1 -1
  86. package/dist/testing/mod.d.mts +30 -4
  87. package/dist/testing/mod.mjs +2 -2
  88. package/dist/{testing-BWq1dCzx.mjs → testing-otQhu4aD.mjs} +1 -1
  89. package/dist/utils/docloader.test.mjs +81 -2
  90. package/dist/utils/kv-cache.test.mjs +1 -1
  91. package/dist/utils/mod.cjs +1 -1
  92. package/dist/utils/mod.d.cts +1 -1
  93. package/dist/utils/mod.d.ts +1 -1
  94. package/dist/utils/mod.js +1 -1
  95. package/package.json +7 -7
  96. package/dist/owner-DkA0Lz7v.cjs +0 -225
  97. package/dist/owner-wNinn7RK.js +0 -215
  98. package/dist/portable-key-DyylakVV.mjs +0 -214
@@ -0,0 +1,656 @@
1
+ import { Temporal } from "temporal-polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
+ import { Ct as version, L as exportJwk, R as fetchActorDocument, St as name, W as verifyKeyOwnership, _t as isCompatibleKeyId, bt as isPortableUri, c as fetchPortableGatewayKey, g as verifyPortableObjectProof, l as resolvePortableActorKey, pt as getCanonicalPortableId, v as verifyPortableObjectProofWithRoot, vt as isPortableId, xt as isSamePublicKey$1 } from "./http-C2M6wcs8.js";
4
+ import { getLogger } from "@logtape/logtape";
5
+ import { CollectionPage, CryptographicKey, Object as Object$1, isActor } from "@fedify/vocab";
6
+ import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
+ import { canonicalizePortableUri, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, parseIri } from "@fedify/vocab-runtime";
8
+ import { dereferencePortableIri, getPortableGatewayCandidates } from "@fedify/vocab-runtime/internal/portable-dereference";
9
+ //#region src/sig/owner.ts
10
+ const logger$1 = getLogger([
11
+ "fedify",
12
+ "sig",
13
+ "owner"
14
+ ]);
15
+ /**
16
+ * Checks if the actor of the given activity owns the specified key.
17
+ *
18
+ * Ownership is never taken from what the activity or the key say about
19
+ * themselves, as both are written by whoever sent the activity. It is
20
+ * established from a document that the owner itself serves: either the key's
21
+ * claimed owner links back to the key, or the actor the activity claims lists
22
+ * the key as its own.
23
+ *
24
+ * @param activity The activity to check.
25
+ * @param key The public key to check.
26
+ * @param options Options for checking the key ownership.
27
+ * @returns Whether the actor is the owner of the key.
28
+ */
29
+ async function doesActorOwnKey(activity, key, options) {
30
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.verify_key_ownership", {
31
+ kind: SpanKind.INTERNAL,
32
+ attributes: {
33
+ "activitypub.actor.id": activity.actorId?.href ?? "",
34
+ "activitypub.key.id": key.id?.href ?? ""
35
+ }
36
+ }, async (span) => {
37
+ try {
38
+ const actorId = activity.actorId;
39
+ if (actorId == null) {
40
+ span.setAttribute("activitypub.key_ownership.verified", false);
41
+ span.setAttribute("activitypub.key_ownership.method", "none");
42
+ return false;
43
+ }
44
+ if (key.id != null && isPortableUri(key.id)) {
45
+ const owner = await getPortableActorKeyOwner(key, options);
46
+ const ownerId = owner?.id == null ? null : getCanonicalPortableId(owner.id);
47
+ const verified = ownerId != null && ownerId === getCanonicalPortableId(actorId);
48
+ span.setAttribute("activitypub.key_ownership.verified", verified);
49
+ span.setAttribute("activitypub.key_ownership.method", "portable_actor_key");
50
+ return verified;
51
+ }
52
+ if (key.id != null && isCompatibleKeyId(key.id)) {
53
+ const owner = await getPortableGatewayKeyOwner(key, options);
54
+ if (owner !== void 0) {
55
+ const ownerId = owner?.id == null ? null : getCanonicalPortableId(owner.id);
56
+ const verified = ownerId != null && ownerId === getCanonicalPortableId(actorId);
57
+ span.setAttribute("activitypub.key_ownership.verified", verified);
58
+ span.setAttribute("activitypub.key_ownership.method", "portable_gateway_key");
59
+ return verified;
60
+ }
61
+ }
62
+ if (key.ownerId != null) {
63
+ const owner = await verifyKeyOwnership(key, options);
64
+ if (owner?.id != null && owner.id.href === actorId.href) {
65
+ span.setAttribute("activitypub.key_ownership.verified", true);
66
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
67
+ return true;
68
+ }
69
+ }
70
+ const actor = await fetchActorDocument(actorId, options);
71
+ if (actor != null && await doesActorListKey(actor, key, options)) {
72
+ span.setAttribute("activitypub.key_ownership.verified", true);
73
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
74
+ return true;
75
+ }
76
+ logger$1.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
77
+ actorId: actorId.href,
78
+ keyId: key.id?.href
79
+ });
80
+ span.setAttribute("activitypub.key_ownership.verified", false);
81
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
82
+ return false;
83
+ } catch (error) {
84
+ span.recordException(error);
85
+ span.setStatus({
86
+ code: SpanStatusCode.ERROR,
87
+ message: String(error)
88
+ });
89
+ throw error;
90
+ } finally {
91
+ span.end();
92
+ }
93
+ });
94
+ }
95
+ /**
96
+ * Determines whether the given actor's own document lists the given key among
97
+ * its public keys.
98
+ *
99
+ * Keys are matched by id, which is what an actor document links to. A key
100
+ * document may leave its id implicit, though, and then there is no id for the
101
+ * actor to link to; the key material itself is the only thing the two can
102
+ * have in common, so that is what gets compared.
103
+ */
104
+ async function doesActorListKey(actor, key, options) {
105
+ if (key.id != null) {
106
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
107
+ return false;
108
+ }
109
+ if (key.publicKey == null) return false;
110
+ const publicKeys = actor.getPublicKeys({
111
+ ...options,
112
+ suppressError: true
113
+ });
114
+ for await (const publicKey of publicKeys) {
115
+ if (publicKey.publicKey == null) continue;
116
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
117
+ }
118
+ return false;
119
+ }
120
+ /**
121
+ * Compares two public keys by their key material, ignoring the metadata that
122
+ * surrounds it.
123
+ */
124
+ async function isSamePublicKey(a, b) {
125
+ const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
126
+ return x.kty === y.kty && x.crv === y.crv && x.n === y.n && x.e === y.e && x.x === y.x && x.y === y.y;
127
+ }
128
+ /**
129
+ * Gets the actor that owns the specified key. Returns `null` if the key has no
130
+ * known owner.
131
+ *
132
+ * The owner is only returned when the key and the owner link to each other:
133
+ * a document that merely claims to own a key is not enough, as the claim and
134
+ * the key can come from the same host.
135
+ *
136
+ * @param keyId The ID of the key to check, or the key itself.
137
+ * @param options Options for getting the key owner.
138
+ * @returns The actor that owns the key, or `null` if the key has no known
139
+ * owner.
140
+ * @since 0.7.0
141
+ */
142
+ async function getKeyOwner(keyId, options) {
143
+ const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
144
+ const documentLoader = options.documentLoader ?? getDocumentLoader();
145
+ const fetchOptions = {
146
+ documentLoader,
147
+ contextLoader: options.contextLoader ?? getDocumentLoader(),
148
+ tracerProvider
149
+ };
150
+ const id = keyId instanceof CryptographicKey ? keyId.id : keyId;
151
+ if (id != null && isPortableUri(id)) return await getPortableActorKeyOwner(keyId, fetchOptions);
152
+ if (id != null && isCompatibleKeyId(id)) {
153
+ const owner = await getPortableGatewayKeyOwner(keyId, fetchOptions);
154
+ if (owner !== void 0) return owner;
155
+ }
156
+ if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
157
+ let keyDoc;
158
+ let documentUrl = keyId;
159
+ try {
160
+ const remoteDocument = await documentLoader(keyId.href);
161
+ keyDoc = remoteDocument.document;
162
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
163
+ } catch (_) {
164
+ return null;
165
+ }
166
+ let object;
167
+ try {
168
+ object = await Object$1.fromJsonLd(keyDoc, {
169
+ ...fetchOptions,
170
+ baseUrl: documentUrl
171
+ });
172
+ } catch (e) {
173
+ if (!(e instanceof TypeError)) throw e;
174
+ try {
175
+ object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
176
+ } catch (e) {
177
+ if (e instanceof TypeError) return null;
178
+ throw e;
179
+ }
180
+ }
181
+ if (object instanceof CryptographicKey) {
182
+ if (object.id != null && object.id.href !== keyId.href) return null;
183
+ return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
184
+ }
185
+ if (!isActor(object)) return null;
186
+ if (object.id == null || isPortableId(object.id) || object.id.origin !== documentUrl.origin) {
187
+ logger$1.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
188
+ documentUrl: documentUrl.href,
189
+ actorId: object.id?.href,
190
+ keyId: keyId.href
191
+ });
192
+ return null;
193
+ }
194
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
195
+ return null;
196
+ }
197
+ /**
198
+ * Resolves the owner of a key at a compatible identifier, if the key turns
199
+ * out to be a gateway key of an [FEP-ef61] portable actor.
200
+ *
201
+ * [FEP-ef61]: https://w3id.org/fep/ef61
202
+ * @param key The key, or its ID, which must be a compatible identifier.
203
+ * @param options Options for fetching the key.
204
+ * @returns `undefined` if the key is not a gateway key, i.e., the document at
205
+ * the key ID is not a portable actor, so the usual checks apply.
206
+ * Otherwise, the portable actor if its signed document vouches for
207
+ * the key, and the given key, if any, has the same key material, or
208
+ * `null` if not.
209
+ */
210
+ async function getPortableGatewayKeyOwner(key, options) {
211
+ const keyId = key instanceof CryptographicKey ? key.id : key;
212
+ if (keyId == null) return void 0;
213
+ const resolution = await fetchPortableGatewayKey(keyId, options);
214
+ if (resolution.type === "legacy") return void 0;
215
+ if (resolution.type === "rejected") return null;
216
+ if (key instanceof CryptographicKey) {
217
+ if (key.publicKey == null || !await isSamePublicKey$1(key.publicKey, resolution.key.publicKey)) {
218
+ logger$1.debug("The key {keyId} does not have the same key material as the gateway key its portable actor vouches for.", { keyId: keyId.href });
219
+ return null;
220
+ }
221
+ }
222
+ return resolution.actor;
223
+ }
224
+ /**
225
+ * Resolves the owner of a key of an [FEP-ef61] portable actor at an `ap:` or
226
+ * `ap+ef61:` key ID.
227
+ *
228
+ * [FEP-ef61]: https://w3id.org/fep/ef61
229
+ * @param key The key, or its ID, which must be an `ap:` or `ap+ef61:` URI.
230
+ * @param options Options for fetching the key.
231
+ * @returns The portable actor if its signed document vouches for the key,
232
+ * and the given key, if any, has the same key material, or `null`
233
+ * if not.
234
+ */
235
+ async function getPortableActorKeyOwner(key, options) {
236
+ const keyId = key instanceof CryptographicKey ? key.id : key;
237
+ if (keyId == null) return null;
238
+ const resolution = await resolvePortableActorKey(keyId, options);
239
+ if (resolution.type !== "verified") return null;
240
+ if (key instanceof CryptographicKey) {
241
+ if (key.publicKey == null || !await isSamePublicKey$1(key.publicKey, resolution.key.publicKey)) {
242
+ logger$1.debug("The key {keyId} does not have the same key material as the key its portable actor vouches for.", { keyId: keyId.href });
243
+ return null;
244
+ }
245
+ }
246
+ return resolution.actor;
247
+ }
248
+ //#endregion
249
+ //#region src/sig/portable-collection.ts
250
+ const logger = getLogger([
251
+ "fedify",
252
+ "sig",
253
+ "proof"
254
+ ]);
255
+ const AS_NAMESPACE = "https://www.w3.org/ns/activitystreams#";
256
+ const AS_ATTRIBUTED_TO = `${AS_NAMESPACE}attributedTo`;
257
+ const AS_PART_OF = `${AS_NAMESPACE}partOf`;
258
+ /**
259
+ * The properties through which a collection refers to its pages, and a page
260
+ * to other pages of the same collection.
261
+ */
262
+ const PAGING_PROPERTIES = new Set([
263
+ "first",
264
+ "last",
265
+ "current",
266
+ "next",
267
+ "prev"
268
+ ].map((p) => AS_NAMESPACE + p));
269
+ /**
270
+ * The properties through which an actor refers to its own collections.
271
+ */
272
+ const ACTOR_COLLECTION_PROPERTIES = /* @__PURE__ */ new Set([
273
+ "http://www.w3.org/ns/ldp#inbox",
274
+ `${AS_NAMESPACE}outbox`,
275
+ `${AS_NAMESPACE}followers`,
276
+ `${AS_NAMESPACE}following`,
277
+ `${AS_NAMESPACE}liked`
278
+ ]);
279
+ const contextStates = /* @__PURE__ */ new WeakMap();
280
+ function createContext(state) {
281
+ const token = Object.freeze(Object.create(null));
282
+ contextStates.set(token, state);
283
+ return token;
284
+ }
285
+ function getContextState(context) {
286
+ if (context == null || typeof context !== "object") return void 0;
287
+ return contextStates.get(context);
288
+ }
289
+ function canonicalize(id) {
290
+ try {
291
+ const portable = fromCompatibleEf61Id(id);
292
+ if (portable != null) return canonicalizePortableUri(formatIri(portable));
293
+ return canonicalizePortableUri(typeof id === "string" ? id : formatIri(id));
294
+ } catch (error) {
295
+ if (error instanceof TypeError) return null;
296
+ throw error;
297
+ }
298
+ }
299
+ function toUrl(canonicalId) {
300
+ return parseIri(canonicalId);
301
+ }
302
+ function canonicalizeAll(ids) {
303
+ const result = [];
304
+ for (const id of ids) {
305
+ const canonical = canonicalize(id);
306
+ if (canonical == null) return null;
307
+ result.push(canonical);
308
+ }
309
+ return result;
310
+ }
311
+ function getExpandedIds(node, property) {
312
+ const values = node[property];
313
+ if (values == null) return [];
314
+ if (!Array.isArray(values)) return null;
315
+ const ids = [];
316
+ for (const value of values) {
317
+ if (value == null || typeof value !== "object" || Array.isArray(value) || typeof value["@id"] !== "string") return null;
318
+ ids.push(value["@id"]);
319
+ }
320
+ return ids;
321
+ }
322
+ function parseAll(ids) {
323
+ const result = [];
324
+ for (const id of ids) try {
325
+ result.push(parseIri(id));
326
+ } catch (error) {
327
+ if (error instanceof TypeError) return null;
328
+ throw error;
329
+ }
330
+ return result;
331
+ }
332
+ function describeRoot(root) {
333
+ const rawId = root["@id"];
334
+ if (typeof rawId !== "string") return null;
335
+ const id = canonicalize(rawId);
336
+ if (id == null) return null;
337
+ const partOf = getExpandedIds(root, AS_PART_OF);
338
+ const attributedTo = getExpandedIds(root, AS_ATTRIBUTED_TO);
339
+ return {
340
+ id,
341
+ url: toUrl(id),
342
+ origin: getFe34Origin(id),
343
+ partOf: partOf == null ? null : canonicalizeAll(partOf),
344
+ attributedTo: attributedTo == null ? null : canonicalizeAll(attributedTo),
345
+ attributedToUrls: attributedTo == null ? null : parseAll(attributedTo)
346
+ };
347
+ }
348
+ function describeObject(object) {
349
+ if (!(object instanceof Object$1) || object.id == null) return null;
350
+ const id = canonicalize(object.id);
351
+ if (id == null) return null;
352
+ const partOfId = object instanceof CollectionPage ? object.partOfId : null;
353
+ return {
354
+ id,
355
+ url: toUrl(id),
356
+ origin: getFe34Origin(id),
357
+ partOf: canonicalizeAll(partOfId == null ? [] : [partOfId]),
358
+ attributedTo: canonicalizeAll(object.attributionIds),
359
+ attributedToUrls: object.attributionIds
360
+ };
361
+ }
362
+ function fail(reason) {
363
+ return {
364
+ verified: false,
365
+ reason
366
+ };
367
+ }
368
+ /**
369
+ * Walks the referrer chain of a collection or page to find the root
370
+ * collection and its owner candidate, checking every page on the way.
371
+ */
372
+ function resolveChain(node, referrer) {
373
+ const pages = [];
374
+ let top = node;
375
+ let link = referrer;
376
+ let state;
377
+ while (link != null && PAGING_PROPERTIES.has(link.property)) {
378
+ pages.push(top);
379
+ state = getContextState(link.collectionContext);
380
+ if (state != null) break;
381
+ const parent = describeObject(link.object);
382
+ if (parent == null || link.truncated) return fail({ type: "unknownCollectionOwner" });
383
+ top = parent;
384
+ link = link.referrer;
385
+ }
386
+ let rootId;
387
+ let rootOrigin;
388
+ let candidate;
389
+ if (state != null) {
390
+ rootId = state.rootId;
391
+ rootOrigin = state.rootOrigin;
392
+ const ownerCandidate = state.owner == null ? state.ownerCandidate : { id: canonicalize(state.owner.id) };
393
+ if (ownerCandidate == null) return fail({ type: "unknownCollectionOwner" });
394
+ candidate = ownerCandidate;
395
+ } else {
396
+ rootId = top.id;
397
+ rootOrigin = top.origin;
398
+ const attributedTo = top.attributedTo;
399
+ if (attributedTo == null) return fail({ type: "unknownCollectionOwner" });
400
+ if (link != null && ACTOR_COLLECTION_PROPERTIES.has(link.property)) {
401
+ const id = link.id == null ? null : canonicalize(link.id);
402
+ if (id == null) return fail({ type: "unknownCollectionOwner" });
403
+ candidate = {
404
+ id,
405
+ object: link.object,
406
+ acceptance: link.acceptance
407
+ };
408
+ } else if (attributedTo.length === 1) candidate = {
409
+ id: attributedTo[0],
410
+ url: top.attributedToUrls?.[0]
411
+ };
412
+ else if (attributedTo.length > 1) return fail({
413
+ type: "conflictingCollectionOwners",
414
+ candidates: attributedTo.map(toUrl)
415
+ });
416
+ else return fail({ type: "unknownCollectionOwner" });
417
+ const conflict = attributedTo.find((id) => id !== candidate.id);
418
+ if (conflict != null) return fail({
419
+ type: "conflictingCollectionOwners",
420
+ candidates: [toUrl(candidate.id), toUrl(conflict)]
421
+ });
422
+ }
423
+ if (getFe34Origin(candidate.id) !== rootOrigin) return fail({ type: "unknownCollectionOwner" });
424
+ for (const page of pages) {
425
+ if (page.origin !== rootOrigin) return fail({
426
+ type: "collectionPageMismatch",
427
+ pageId: page.url,
428
+ collectionId: toUrl(rootId),
429
+ partOf: null
430
+ });
431
+ if (page.partOf == null) return fail({ type: "unknownCollectionOwner" });
432
+ const partOf = page.partOf.find((id) => id !== rootId);
433
+ if (partOf != null) return fail({
434
+ type: "collectionPageMismatch",
435
+ pageId: page.url,
436
+ collectionId: toUrl(rootId),
437
+ partOf: toUrl(partOf)
438
+ });
439
+ if (page.attributedTo == null) return fail({ type: "unknownCollectionOwner" });
440
+ const conflict = page.attributedTo.find((id) => id !== candidate.id);
441
+ if (conflict != null) return fail({
442
+ type: "conflictingCollectionOwners",
443
+ candidates: [toUrl(candidate.id), toUrl(conflict)]
444
+ });
445
+ }
446
+ return {
447
+ rootId,
448
+ rootOrigin,
449
+ owner: state?.owner ?? null,
450
+ candidate
451
+ };
452
+ }
453
+ function getActorCollectionIds(actor) {
454
+ const ids = [];
455
+ for (const id of [
456
+ actor.inboxId,
457
+ actor.outboxId,
458
+ actor.followersId,
459
+ actor.followingId,
460
+ actor.likedId
461
+ ]) {
462
+ if (id == null) continue;
463
+ const canonical = canonicalize(id);
464
+ if (canonical != null) ids.push(canonical);
465
+ }
466
+ return ids;
467
+ }
468
+ async function fetchOwner(candidate, options) {
469
+ const documentLoader = options.documentLoader ?? getDocumentLoader();
470
+ const contextLoader = options.contextLoader ?? getDocumentLoader();
471
+ const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
472
+ const tracer = tracerProvider.getTracer(name, version);
473
+ let inferredGateways;
474
+ try {
475
+ const portable = fromCompatibleEf61Id(candidate);
476
+ if (portable != null) {
477
+ inferredGateways = [new URL(candidate.origin)];
478
+ candidate = portable;
479
+ }
480
+ } catch (error) {
481
+ if (!(error instanceof TypeError)) throw error;
482
+ logger.debug("The owner {owner} of a portable collection is a malformed compatible identifier.", { owner: candidate.href });
483
+ return null;
484
+ }
485
+ const gateways = options.gateways ?? (inferredGateways != null || getPortableGatewayCandidates(candidate).length > 0 ? void 0 : options.gatewayHints);
486
+ if (options.gateways != null) inferredGateways = void 0;
487
+ const span = tracer.startSpan("activitypub.lookup_object");
488
+ try {
489
+ const object = await dereferencePortableIri(candidate, {
490
+ documentLoader,
491
+ contextLoader,
492
+ tracerProvider,
493
+ gateways,
494
+ ...inferredGateways == null ? {} : { inferredGateways },
495
+ verifyPortableObject: (document, verifierOptions) => verifyPortableObjectProof(document, {
496
+ ...options,
497
+ ...verifierOptions
498
+ }),
499
+ suppressError: true,
500
+ span,
501
+ parse: (document, parseOptions) => Object$1.fromJsonLd(document, {
502
+ documentLoader,
503
+ contextLoader: parseOptions.contextLoader,
504
+ tracerProvider,
505
+ baseUrl: parseOptions.baseUrl
506
+ })
507
+ });
508
+ return isActor(object) ? object : null;
509
+ } catch (error) {
510
+ logger.debug("Failed to fetch the owner {owner} of a portable collection: {error}", {
511
+ owner: formatIri(candidate),
512
+ error
513
+ });
514
+ return null;
515
+ } finally {
516
+ span.end();
517
+ }
518
+ }
519
+ async function resolveOwner(chain, options) {
520
+ if (chain.owner != null) return chain.owner;
521
+ const { candidate } = chain;
522
+ const candidateUrl = toUrl(candidate.id);
523
+ let actor = null;
524
+ if (candidate.acceptance === "verified" && isActor(candidate.object) && candidate.object.id != null && canonicalize(candidate.object.id) === candidate.id) actor = candidate.object;
525
+ else actor = await fetchOwner(candidate.url ?? (candidate.object instanceof Object$1 && candidate.object.id != null ? candidate.object.id : candidateUrl), options);
526
+ if (actor == null || actor.id == null) return fail({
527
+ type: "collectionOwnerUnavailable",
528
+ owner: candidateUrl
529
+ });
530
+ const gateways = actor.gateways;
531
+ if (gateways.length < 1) return fail({
532
+ type: "collectionOwnerUnavailable",
533
+ owner: candidateUrl
534
+ });
535
+ if (!getActorCollectionIds(actor).includes(chain.rootId)) return fail({
536
+ type: "collectionNotListedByOwner",
537
+ owner: candidateUrl,
538
+ collectionId: toUrl(chain.rootId)
539
+ });
540
+ return {
541
+ id: candidateUrl,
542
+ gateways
543
+ };
544
+ }
545
+ function getSourceGateway(node, documentUrl) {
546
+ if (documentUrl == null || documentUrl.protocol !== "http:" && documentUrl.protocol !== "https:") return null;
547
+ let portableId;
548
+ try {
549
+ portableId = fromCompatibleEf61Id(documentUrl);
550
+ } catch (error) {
551
+ if (error instanceof TypeError) return null;
552
+ throw error;
553
+ }
554
+ if (portableId == null || canonicalize(portableId) !== node.id) return null;
555
+ return new URL(documentUrl.origin);
556
+ }
557
+ /**
558
+ * Applies the [FEP-ef61] trust policy to a portable object fetched through
559
+ * a gateway.
560
+ *
561
+ * Portable actors, activities, objects, and collections with proofs are
562
+ * verified by {@link verifyPortableObjectProof}. A portable collection or
563
+ * collection page without a proof is accepted only if all of the following
564
+ * hold:
565
+ *
566
+ * - It was retrieved from a gateway: its final URL (`documentUrl`) is
567
+ * a compatible identifier for the same portable collection.
568
+ * - Its owner is determined unambiguously: the actor whose `inbox`,
569
+ * `outbox`, `followers`, `following`, or `liked` property referred to
570
+ * the collection, or the single actor in its `attributedTo`. A page
571
+ * inherits the owner of the collection it was reached from through
572
+ * `first`, `last`, `current`, `next`, or `prev`, and must not name
573
+ * another collection in `partOf`.
574
+ * - The owner's actor document is verified by its proof and lists the
575
+ * collection as its `inbox`, `outbox`, `followers`, `following`, or
576
+ * `liked`.
577
+ * - The gateway that served the collection is in the owner's `gateways`.
578
+ *
579
+ * Where the document came from and which object referred to it are passed
580
+ * by property accessors when this function is used as their
581
+ * `verifyPortableObject` option. Objects embedded in an unsecured
582
+ * collection accepted this way are not trusted: accessors dereference and
583
+ * verify them one by one.
584
+ *
585
+ * Note that acceptance through the gateway policy does not verify anything
586
+ * cryptographically; it only means that the owner trusts the gateway.
587
+ *
588
+ * [FEP-ef61]: https://w3id.org/fep/ef61
589
+ *
590
+ * @param jsonLd The JSON-LD document to verify.
591
+ * @param options Additional options. See also
592
+ * {@link VerifyPortableObjectOptions}.
593
+ * @returns The detailed result.
594
+ * @throws {TypeError} If the input is not a single JSON-LD object or has a
595
+ * malformed portable ID.
596
+ * @since 2.4.0
597
+ */
598
+ async function verifyPortableObject(jsonLd, options = {}) {
599
+ const { result, root, objectType } = await verifyPortableObjectProofWithRoot(jsonLd, options);
600
+ if (result.verified) {
601
+ const node = objectType === "collection" && root != null ? describeRoot(root) : null;
602
+ const chain = node == null ? null : resolveChain(node, options.referrer);
603
+ if (chain == null || !("rootId" in chain)) return {
604
+ verified: true,
605
+ method: "proof",
606
+ keys: result.keys
607
+ };
608
+ return {
609
+ verified: true,
610
+ method: "proof",
611
+ keys: result.keys,
612
+ collectionContext: createContext({
613
+ rootId: chain.rootId,
614
+ rootOrigin: chain.rootOrigin,
615
+ owner: chain.owner,
616
+ ownerCandidate: chain.candidate
617
+ })
618
+ };
619
+ }
620
+ if (result.reason.type !== "unsecuredCollection") return {
621
+ verified: false,
622
+ reason: result.reason
623
+ };
624
+ const node = root == null ? null : describeRoot(root);
625
+ if (node == null) return fail({ type: "unknownCollectionOwner" });
626
+ const gateway = getSourceGateway(node, options.documentUrl);
627
+ if (gateway == null) return fail({
628
+ type: "unknownCollectionSource",
629
+ documentUrl: options.documentUrl ?? null
630
+ });
631
+ const chain = resolveChain(node, options.referrer);
632
+ if (!("rootId" in chain)) return chain;
633
+ const owner = await resolveOwner(chain, options);
634
+ if (!("gateways" in owner)) return owner;
635
+ if (!owner.gateways.some((g) => g.origin === gateway.origin)) return fail({
636
+ type: "untrustedGateway",
637
+ owner: owner.id,
638
+ gateway,
639
+ gateways: owner.gateways
640
+ });
641
+ return {
642
+ verified: true,
643
+ method: "gateway",
644
+ unsecured: true,
645
+ owner: owner.id,
646
+ gateway,
647
+ collectionContext: createContext({
648
+ rootId: chain.rootId,
649
+ rootOrigin: chain.rootOrigin,
650
+ owner,
651
+ ownerCandidate: null
652
+ })
653
+ };
654
+ }
655
+ //#endregion
656
+ export { doesActorOwnKey as n, getKeyOwner as r, verifyPortableObject as t };