@fedify/fedify 2.3.15-dev.2482 → 2.3.16-dev.2809

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 (87) hide show
  1. package/dist/{builder-CocMrVkL.mjs → builder-DzN834kN.mjs} +2 -2
  2. package/dist/{client-CAM_bQXx.d.cts → client-BIBzqEIp.d.cts} +0 -1
  3. package/dist/{client-1He2YuBF.mjs → client-DpUNYKla.mjs} +113 -64
  4. package/dist/{client-CSddvgWN.d.ts → client-jE7oGvRh.d.ts} +0 -1
  5. package/dist/compat/mod.d.cts +1 -1
  6. package/dist/compat/mod.d.ts +1 -1
  7. package/dist/compat/transformers.test.mjs +1 -1
  8. package/dist/{context-MOrCC7yl.d.cts → context-CE_Tj_Oc.d.cts} +28 -2
  9. package/dist/{context-BWbdE_MZ.d.ts → context-H_5tZXg-.d.ts} +28 -2
  10. package/dist/{deno-po8iekMB.mjs → deno-D6uT0AM-.mjs} +1 -1
  11. package/dist/docloader-CNjN6Sbc.mjs +125 -0
  12. package/dist/federation/builder.test.mjs +1 -1
  13. package/dist/federation/handler.test.mjs +5 -5
  14. package/dist/federation/idempotency.test.mjs +2 -2
  15. package/dist/federation/inbox.test.mjs +1 -1
  16. package/dist/federation/metrics.test.mjs +1 -1
  17. package/dist/federation/middleware.test.mjs +390 -29
  18. package/dist/federation/mod.cjs +1 -1
  19. package/dist/federation/mod.d.cts +2 -2
  20. package/dist/federation/mod.d.ts +2 -2
  21. package/dist/federation/mod.js +1 -1
  22. package/dist/federation/send.test.mjs +498 -88
  23. package/dist/federation/temporal.test.mjs +1 -1
  24. package/dist/federation/webfinger.test.mjs +1 -1
  25. package/dist/{http-Cdu8BGtv.js → http-Bp6mEroC.js} +172 -103
  26. package/dist/{http-WcSdFbt1.cjs → http-CSvwZqZm.cjs} +173 -104
  27. package/dist/{http-DQmNpfym.d.ts → http-CZPYFK3b.d.cts} +1 -2
  28. package/dist/{http-DiWQB8Mr.d.cts → http-DmP0sr2l.d.ts} +1 -2
  29. package/dist/{http-BNCLeQJ-.mjs → http-aRNJfio8.mjs} +196 -98
  30. package/dist/{inbox-g1sd_Vjn.mjs → inbox-DnLMxWg5.mjs} +2 -2
  31. package/dist/{key-BR2TRTXR.mjs → key-TRkqUVd-.mjs} +2 -2
  32. package/dist/{kv-cache-8SigUtvX.mjs → kv-cache-8QrDCLgQ.mjs} +1 -1
  33. package/dist/{kv-cache-C0AqpjoS.js → kv-cache-CnNEdAgf.js} +60 -18
  34. package/dist/{kv-cache-Bw_gduSm.cjs → kv-cache-D529z_1E.cjs} +59 -17
  35. package/dist/{ld-CSNsWdYE.mjs → ld-CAC31Yos.mjs} +3 -3
  36. package/dist/{metrics-BS7YzLVA.mjs → metrics-DuUzHGxP.mjs} +1 -1
  37. package/dist/{middleware-Dlo7NnZl.mjs → middleware-B4jacDbf.mjs} +1 -1
  38. package/dist/{middleware-B1RRLN7m.mjs → middleware-BMqQ54Bi.mjs} +80 -40
  39. package/dist/{middleware-D-SL8Bkj.cjs → middleware-CSbf6RbJ.cjs} +236 -98
  40. package/dist/{middleware-WL-JfDiK.js → middleware-DDhmxHiw.js} +237 -99
  41. package/dist/{mod-LmD03uRA.d.ts → mod-CDFFESfL.d.ts} +1 -1
  42. package/dist/{mod-Bid79LFU.d.cts → mod-C_gFmeNq.d.cts} +1 -1
  43. package/dist/{mod-Co1M3Ux0.d.cts → mod-DDVkmZ_h.d.cts} +2 -8
  44. package/dist/{mod-B6PwkUMU.d.cts → mod-DDjtbkZO.d.cts} +1 -1
  45. package/dist/{mod-Br8yJNcE.d.ts → mod-DMjhnFbg.d.ts} +2 -8
  46. package/dist/{mod-TLEvgT1i.d.ts → mod-HQXFvOHs.d.ts} +1 -1
  47. package/dist/mod.cjs +5 -5
  48. package/dist/mod.d.cts +6 -6
  49. package/dist/mod.d.ts +6 -6
  50. package/dist/mod.js +5 -5
  51. package/dist/nodeinfo/client.test.mjs +337 -19
  52. package/dist/nodeinfo/handler.test.mjs +1 -1
  53. package/dist/nodeinfo/mod.cjs +1 -1
  54. package/dist/nodeinfo/mod.d.cts +1 -1
  55. package/dist/nodeinfo/mod.d.ts +1 -1
  56. package/dist/nodeinfo/mod.js +1 -1
  57. package/dist/otel/exporter.test.mjs +292 -30
  58. package/dist/otel/mod.cjs +36 -30
  59. package/dist/otel/mod.d.cts +13 -0
  60. package/dist/otel/mod.d.ts +13 -0
  61. package/dist/otel/mod.js +36 -30
  62. package/dist/{owner-DeggvxcG.mjs → owner-DJVOcWgi.mjs} +2 -2
  63. package/dist/{proof-teNNYmFh.cjs → proof-BxwMhZ0U.cjs} +1 -1
  64. package/dist/{proof-DMcUrrp8.mjs → proof-CIOOp9BJ.mjs} +3 -3
  65. package/dist/{proof-v-IzWx7x.js → proof-CXY7WUci.js} +1 -1
  66. package/dist/{send-BsthcvPG.mjs → send-BPXYrcMp.mjs} +171 -73
  67. package/dist/sig/http.test.mjs +528 -2
  68. package/dist/sig/key.test.mjs +2 -2
  69. package/dist/sig/ld.test.mjs +2 -2
  70. package/dist/sig/mod.cjs +2 -2
  71. package/dist/sig/mod.d.cts +2 -2
  72. package/dist/sig/mod.d.ts +2 -2
  73. package/dist/sig/mod.js +2 -2
  74. package/dist/sig/owner.test.mjs +1 -1
  75. package/dist/sig/proof.test.mjs +1 -1
  76. package/dist/{temporal-Cji8Y8eQ.mjs → temporal-DpZ0fYjM.mjs} +1 -1
  77. package/dist/testing/mod.d.mts +26 -0
  78. package/dist/{types-miAYfiGO.js → types-B1_pRFE_.js} +112 -63
  79. package/dist/{types-DRPjmHVV.cjs → types-DOvyymM4.cjs} +111 -62
  80. package/dist/utils/docloader.test.mjs +318 -34
  81. package/dist/utils/kv-cache.test.mjs +1 -1
  82. package/dist/utils/mod.cjs +1 -1
  83. package/dist/utils/mod.d.cts +1 -1
  84. package/dist/utils/mod.d.ts +1 -1
  85. package/dist/utils/mod.js +1 -1
  86. package/package.json +7 -7
  87. package/dist/docloader-BVj35vgR.mjs +0 -83
@@ -1,10 +1,10 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-po8iekMB.mjs";
5
- import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-BS7YzLVA.mjs";
4
+ import { n as version, t as name } from "./deno-D6uT0AM-.mjs";
5
+ import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-DuUzHGxP.mjs";
6
6
  import { i as validateAcceptSignature, n as fulfillAcceptSignature, r as parseAcceptSignature } from "./accept-Dd__NiUL.mjs";
7
- import { i as fetchKeyDetailed, s as validateCryptoKey } from "./key-BR2TRTXR.mjs";
7
+ import { i as fetchKeyDetailed, s as validateCryptoKey } from "./key-TRkqUVd-.mjs";
8
8
  import { getLogger } from "@logtape/logtape";
9
9
  import { CryptographicKey } from "@fedify/vocab";
10
10
  import { SpanStatusCode, trace } from "@opentelemetry/api";
@@ -900,10 +900,10 @@ async function createRedirectRequest(request, location, body, validateRedirect)
900
900
  cache: request.cache
901
901
  });
902
902
  }
903
- async function fetchDoubleKnockRequest(request, signedRequest, signal) {
903
+ async function fetchDoubleKnockRequest(session, request, signedRequest, signal) {
904
904
  const maxAttempts = request.method === "GET" || request.method === "HEAD" ? 2 : 1;
905
905
  for (let attempt = 1;; attempt++) try {
906
- return await fetch(signedRequest, {
906
+ return await session.fetch(signedRequest, {
907
907
  redirect: "manual",
908
908
  signal
909
909
  });
@@ -964,108 +964,206 @@ function getAbortReason(signal) {
964
964
  * @since 1.6.0
965
965
  */
966
966
  async function doubleKnock(request, identity, options = {}) {
967
- return await doubleKnockInternal(request, identity, options);
967
+ const { response } = await doubleKnockCore(request, identity, options, openGlobalFetchHop);
968
+ return response;
968
969
  }
969
- async function doubleKnockInternal(request, identity, options, redirected = 0, visited = /* @__PURE__ */ new Set()) {
970
- const { specDeterminer, log, tracerProvider, signal } = options;
971
- const maximumRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
972
- visited.add(request.url);
973
- const origin = new URL(request.url).origin;
974
- const firstTrySpec = specDeterminer == null ? "rfc9421" : await specDeterminer.determineSpec(origin);
975
- const body = options.body !== void 0 ? options.body : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
976
- let signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
977
- spec: firstTrySpec,
978
- tracerProvider,
979
- body
970
+ /**
971
+ * Performs a double-knock request like {@link doubleKnock}, opening a session
972
+ * for every hop with the given function, and passes the final response to
973
+ * the given function. The final session is closed after `consume` settles,
974
+ * so `consume` must read or cancel the response body before it returns.
975
+ * This is not exported from any entry point.
976
+ * @param request The request to send.
977
+ * @param identity The identity to use for signing the request.
978
+ * @param options The options for double-knock requests.
979
+ * @param openHop The function to open a session for each hop. The session of
980
+ * a hop is closed before the next hop is opened.
981
+ * @param consume The function to consume the final response.
982
+ * @returns The value returned by `consume`.
983
+ */
984
+ async function doubleKnockScoped(request, identity, options, openHop, consume) {
985
+ const { response, session } = await doubleKnockCore(request, identity, options, openHop);
986
+ try {
987
+ return await consume(response);
988
+ } catch (error) {
989
+ getLogger([
990
+ "fedify",
991
+ "sig",
992
+ "http"
993
+ ]).debug("Failed to consume the response from {url}; closing the session: {error}", {
994
+ url: request.url,
995
+ error
996
+ });
997
+ throw error;
998
+ } finally {
999
+ await session.close();
1000
+ }
1001
+ }
1002
+ /**
1003
+ * A hop session for {@link doubleKnock}: it uses the global `fetch()` without
1004
+ * validating or pinning addresses, and its `close()` does nothing, so that
1005
+ * the final response can be returned to the caller.
1006
+ */
1007
+ function openGlobalFetchHop(url) {
1008
+ const sessionUrl = new URL(url);
1009
+ return Promise.resolve({
1010
+ get url() {
1011
+ return new URL(sessionUrl);
1012
+ },
1013
+ fetch: (input, init) => fetch(input, init),
1014
+ close: () => Promise.resolve()
980
1015
  });
981
- log?.(signedRequest);
982
- let response = await fetchDoubleKnockRequest(request, signedRequest, signal);
983
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
984
- if (redirected >= maximumRedirection) throw new FetchError(request.url, `Too many redirections (${redirected + 1})`);
985
- const redirectRequest = await createRedirectRequest(request, response.headers.get("Location"), body, options.validateRedirect);
986
- if (visited.has(redirectRequest.url)) throw new FetchError(request.url, `Redirect loop detected: ${redirectRequest.url}`);
987
- return doubleKnockInternal(redirectRequest, identity, {
988
- ...options,
989
- body
990
- }, redirected + 1, visited);
991
- } else if (response.status === 400 || response.status === 401 || response.status > 401) {
992
- const logger = getLogger([
1016
+ }
1017
+ function isRedirectResponse(response) {
1018
+ return response.status >= 300 && response.status < 400 && response.headers.has("Location");
1019
+ }
1020
+ /**
1021
+ * Starts cancelling the body of a response that is not passed to the caller,
1022
+ * without waiting for it to settle. The cancellation of a branch of a tee
1023
+ * (e.g., a body cloned by a fetch mock) settles only after the other branch
1024
+ * is cancelled too, per the Streams standard, so awaiting it could block
1025
+ * forever. Failures are only logged.
1026
+ */
1027
+ function cancelResponseBody(response, url) {
1028
+ response.body?.cancel().catch((error) => {
1029
+ getLogger([
993
1030
  "fedify",
994
1031
  "sig",
995
1032
  "http"
996
- ]);
997
- const acceptSigHeader = response.headers.get("Accept-Signature");
998
- if (acceptSigHeader != null) {
999
- const entries = validateAcceptSignature(parseAcceptSignature(acceptSigHeader));
1000
- const localKeyId = identity.keyId.href;
1001
- const localAlg = "rsa-v1_5-sha256";
1002
- let fulfilled = false;
1003
- let challengeRequest;
1004
- for (const entry of entries) {
1005
- const rfc9421 = fulfillAcceptSignature(entry, localKeyId, localAlg);
1006
- if (rfc9421 == null) continue;
1007
- logger.debug("Received Accept-Signature challenge; accumulating label {label} and components {components}.", {
1008
- label: rfc9421.label,
1009
- components: rfc9421.components
1010
- });
1011
- try {
1012
- challengeRequest = await signRequest(challengeRequest ?? request, identity.privateKey, identity.keyId, {
1013
- spec: "rfc9421",
1014
- tracerProvider,
1015
- body,
1016
- rfc9421
1033
+ ]).debug("Failed to cancel the response body from {url}: {error}", {
1034
+ url,
1035
+ error
1036
+ });
1037
+ });
1038
+ }
1039
+ async function doubleKnockCore(request, identity, options, openHop) {
1040
+ const { specDeterminer, log, tracerProvider, signal } = options;
1041
+ const maximumRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
1042
+ const visited = /* @__PURE__ */ new Set();
1043
+ const body = options.body !== void 0 ? options.body : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
1044
+ let session = await openHop(request.url);
1045
+ try {
1046
+ for (let redirected = 0;; redirected++) {
1047
+ visited.add(request.url);
1048
+ const origin = new URL(request.url).origin;
1049
+ const firstTrySpec = specDeterminer == null ? "rfc9421" : await specDeterminer.determineSpec(origin);
1050
+ let signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
1051
+ spec: firstTrySpec,
1052
+ tracerProvider,
1053
+ body
1054
+ });
1055
+ log?.(signedRequest);
1056
+ let response = await fetchDoubleKnockRequest(session, request, signedRequest, signal);
1057
+ const firstRedirected = isRedirectResponse(response);
1058
+ if (!firstRedirected && (response.status === 400 || response.status === 401 || response.status > 401)) {
1059
+ const logger = getLogger([
1060
+ "fedify",
1061
+ "sig",
1062
+ "http"
1063
+ ]);
1064
+ const acceptSigHeader = response.headers.get("Accept-Signature");
1065
+ if (acceptSigHeader != null) {
1066
+ const entries = validateAcceptSignature(parseAcceptSignature(acceptSigHeader));
1067
+ const localKeyId = identity.keyId.href;
1068
+ const localAlg = "rsa-v1_5-sha256";
1069
+ let fulfilled = false;
1070
+ let challengeRequest;
1071
+ for (const entry of entries) {
1072
+ const rfc9421 = fulfillAcceptSignature(entry, localKeyId, localAlg);
1073
+ if (rfc9421 == null) continue;
1074
+ logger.debug("Received Accept-Signature challenge; accumulating label {label} and components {components}.", {
1075
+ label: rfc9421.label,
1076
+ components: rfc9421.components
1077
+ });
1078
+ try {
1079
+ challengeRequest = await signRequest(challengeRequest ?? request, identity.privateKey, identity.keyId, {
1080
+ spec: "rfc9421",
1081
+ tracerProvider,
1082
+ body,
1083
+ rfc9421
1084
+ });
1085
+ fulfilled = true;
1086
+ } catch (error) {
1087
+ logger.debug("Failed to fulfill Accept-Signature challenge entry {label}: {error}", {
1088
+ label: entry.label,
1089
+ error
1090
+ });
1091
+ }
1092
+ }
1093
+ if (fulfilled && challengeRequest != null) {
1094
+ cancelResponseBody(response, request.url);
1095
+ signedRequest = challengeRequest;
1096
+ log?.(signedRequest);
1097
+ response = await session.fetch(signedRequest, {
1098
+ redirect: "manual",
1099
+ signal
1100
+ });
1101
+ }
1102
+ if (fulfilled && !isRedirectResponse(response)) {
1103
+ if (response.status < 300) {
1104
+ await specDeterminer?.rememberSpec(origin, "rfc9421");
1105
+ return {
1106
+ response,
1107
+ session
1108
+ };
1109
+ }
1110
+ if (response.status !== 400 && response.status !== 401) return {
1111
+ response,
1112
+ session
1113
+ };
1114
+ }
1115
+ }
1116
+ if (!isRedirectResponse(response)) {
1117
+ const spec = firstTrySpec === "draft-cavage-http-signatures-12" ? "rfc9421" : "draft-cavage-http-signatures-12";
1118
+ getLogger([
1119
+ "fedify",
1120
+ "sig",
1121
+ "http"
1122
+ ]).debug("Failed to verify with the spec {spec} ({status} {statusText}); retrying with spec {secondSpec}... (double-knocking)", {
1123
+ spec: firstTrySpec,
1124
+ secondSpec: spec,
1125
+ status: response.status,
1126
+ statusText: response.statusText
1017
1127
  });
1018
- fulfilled = true;
1019
- } catch (error) {
1020
- logger.debug("Failed to fulfill Accept-Signature challenge entry {label}: {error}", {
1021
- label: entry.label,
1022
- error
1128
+ cancelResponseBody(response, request.url);
1129
+ signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
1130
+ spec,
1131
+ tracerProvider,
1132
+ body
1023
1133
  });
1134
+ log?.(signedRequest);
1135
+ response = await fetchDoubleKnockRequest(session, request, signedRequest, signal);
1136
+ if (!isRedirectResponse(response) && response.status !== 400 && response.status !== 401) await specDeterminer?.rememberSpec(origin, spec);
1024
1137
  }
1025
- }
1026
- if (fulfilled && challengeRequest != null) {
1027
- signedRequest = challengeRequest;
1028
- log?.(signedRequest);
1029
- response = await fetch(signedRequest, {
1030
- redirect: "manual",
1031
- signal
1032
- });
1033
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) return doubleKnock(await createRedirectRequest(request, response.headers.get("Location"), body, options.validateRedirect), identity, {
1034
- ...options,
1035
- body
1036
- });
1037
- }
1038
- if (fulfilled && response.status < 300) {
1039
- await specDeterminer?.rememberSpec(origin, "rfc9421");
1040
- return response;
1041
- }
1042
- if (fulfilled && response.status !== 400 && response.status !== 401) return response;
1043
- }
1044
- const spec = firstTrySpec === "draft-cavage-http-signatures-12" ? "rfc9421" : "draft-cavage-http-signatures-12";
1045
- logger.debug("Failed to verify with the spec {spec} ({status} {statusText}); retrying with spec {secondSpec}... (double-knocking)", {
1046
- spec: firstTrySpec,
1047
- secondSpec: spec,
1048
- status: response.status,
1049
- statusText: response.statusText
1050
- });
1051
- signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
1052
- spec,
1053
- tracerProvider,
1054
- body
1055
- });
1056
- log?.(signedRequest);
1057
- response = await fetchDoubleKnockRequest(request, signedRequest, signal);
1058
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
1138
+ } else if (!firstRedirected) await specDeterminer?.rememberSpec(origin, firstTrySpec);
1139
+ if (!isRedirectResponse(response)) return {
1140
+ response,
1141
+ session
1142
+ };
1143
+ cancelResponseBody(response, request.url);
1144
+ await session.close();
1059
1145
  if (redirected >= maximumRedirection) throw new FetchError(request.url, `Too many redirections (${redirected + 1})`);
1060
- const redirectRequest = await createRedirectRequest(request, response.headers.get("Location"), body, options.validateRedirect);
1146
+ const location = response.headers.get("Location");
1147
+ const redirectRequest = await createRedirectRequest(request, location, body, options.validateRedirect);
1061
1148
  if (visited.has(redirectRequest.url)) throw new FetchError(request.url, `Redirect loop detected: ${redirectRequest.url}`);
1062
- return doubleKnockInternal(redirectRequest, identity, {
1063
- ...options,
1064
- body
1065
- }, redirected + 1, visited);
1066
- } else if (response.status !== 400 && response.status !== 401) await specDeterminer?.rememberSpec(origin, spec);
1067
- } else await specDeterminer?.rememberSpec(origin, firstTrySpec);
1068
- return response;
1149
+ request = redirectRequest;
1150
+ session = await openHop(request.url);
1151
+ }
1152
+ } catch (error) {
1153
+ try {
1154
+ await session.close();
1155
+ } catch (closeError) {
1156
+ getLogger([
1157
+ "fedify",
1158
+ "sig",
1159
+ "http"
1160
+ ]).debug("Failed to close the session for {url}: {error}", {
1161
+ url: request.url,
1162
+ error: closeError
1163
+ });
1164
+ }
1165
+ throw error;
1166
+ }
1069
1167
  }
1070
1168
  /**
1071
1169
  * Performs a timing-safe equality comparison between two `Uint8Array` values.
@@ -1095,4 +1193,4 @@ function timingSafeEqual(a, b) {
1095
1193
  return result === 0;
1096
1194
  }
1097
1195
  //#endregion
1098
- export { parseRfc9421Signature as a, timingSafeEqual as c, formatRfc9421SignatureParameters as i, verifyRequest as l, doubleKnock as n, parseRfc9421SignatureInput as o, formatRfc9421Signature as r, signRequest as s, createRfc9421SignatureBase as t, verifyRequestDetailed as u };
1196
+ export { formatRfc9421SignatureParameters as a, signRequest as c, verifyRequestDetailed as d, formatRfc9421Signature as i, timingSafeEqual as l, doubleKnock as n, parseRfc9421Signature as o, doubleKnockScoped as r, parseRfc9421SignatureInput as s, createRfc9421SignatureBase as t, verifyRequest as u };
@@ -1,8 +1,8 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-po8iekMB.mjs";
5
- import { g as recordInboxActivity, n as getDurationMs, r as getFederationMetrics } from "./metrics-BS7YzLVA.mjs";
4
+ import { n as version, t as name } from "./deno-D6uT0AM-.mjs";
5
+ import { g as recordInboxActivity, n as getDurationMs, r as getFederationMetrics } from "./metrics-DuUzHGxP.mjs";
6
6
  import { getLogger } from "@logtape/logtape";
7
7
  import { getTypeId } from "@fedify/vocab";
8
8
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
@@ -1,8 +1,8 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-po8iekMB.mjs";
5
- import { _ as recordKeyLookup, n as getDurationMs, t as classifyFetchError } from "./metrics-BS7YzLVA.mjs";
4
+ import { n as version, t as name } from "./deno-D6uT0AM-.mjs";
5
+ import { _ as recordKeyLookup, n as getDurationMs, t as classifyFetchError } from "./metrics-DuUzHGxP.mjs";
6
6
  import { getLogger } from "@logtape/logtape";
7
7
  import { CryptographicKey, Object as Object$1, isActor } from "@fedify/vocab";
8
8
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
@@ -1,7 +1,7 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { p as recordDocumentCache } from "./metrics-BS7YzLVA.mjs";
4
+ import { p as recordDocumentCache } from "./metrics-DuUzHGxP.mjs";
5
5
  import { getLogger } from "@logtape/logtape";
6
6
  import { preloadedContexts } from "@fedify/vocab-runtime";
7
7
  //#region src/utils/kv-cache.ts
@@ -1,9 +1,10 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { T as recordDocumentCache, f as validateCryptoKey, t as doubleKnock } from "./http-Cdu8BGtv.js";
3
+ import { T as recordDocumentCache, f as validateCryptoKey, t as doubleKnockScoped } from "./http-Bp6mEroC.js";
4
4
  import { getLogger } from "@logtape/logtape";
5
- import { FetchError, UrlError, createActivityPubRequest, getRemoteDocument, logRequest, preloadedContexts, validatePublicUrl } from "@fedify/vocab-runtime";
5
+ import { FetchError, UrlError, createActivityPubRequest, getRemoteDocument, logRequest, preloadedContexts } from "@fedify/vocab-runtime";
6
6
  import { curry } from "es-toolkit";
7
+ import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
7
8
  //#region src/utils/docloader.ts
8
9
  const logger$1 = getLogger([
9
10
  "fedify",
@@ -24,12 +25,34 @@ const DEFAULT_MAX_REDIRECTION = 20;
24
25
  * @throws {TypeError} If the key is invalid or unsupported.
25
26
  * @since 0.4.0
26
27
  */
27
- function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedirection, userAgent, specDeterminer, tracerProvider } = {}) {
28
+ function getAuthenticatedDocumentLoader(identity, options = {}) {
29
+ return createAuthenticatedDocumentLoader(identity, options);
30
+ }
31
+ /**
32
+ * The placeholder that the alternate document callback of
33
+ * `getRemoteDocument()` returns, so that the alternate document is loaded
34
+ * after the current hop is closed.
35
+ */
36
+ const ALTERNATE_PLACEHOLDER = Object.freeze({
37
+ contextUrl: null,
38
+ document: null,
39
+ documentUrl: "about:blank"
40
+ });
41
+ /**
42
+ * The implementation of {@link getAuthenticatedDocumentLoader}. This is not
43
+ * exported from any entry point.
44
+ * @param identity The identity to get the document loader for.
45
+ * @param options The options for the document loader.
46
+ * @param deps The dependencies, for tests.
47
+ * @returns The authenticated document loader.
48
+ * @throws {TypeError} If the key is invalid or unsupported.
49
+ */
50
+ function createAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedirection, userAgent, specDeterminer, tracerProvider } = {}, deps = {}) {
28
51
  validateCryptoKey(identity.privateKey);
29
52
  async function load(url, options, redirected = 0, visited = /* @__PURE__ */ new Set()) {
30
53
  options?.signal?.throwIfAborted();
31
54
  let currentUrl = new URL(url).href;
32
- await validateUrl(currentUrl);
55
+ validateUrl(currentUrl);
33
56
  visited.add(currentUrl);
34
57
  const originalRequest = createActivityPubRequest(currentUrl, { userAgent });
35
58
  function follow(nextUrl) {
@@ -38,31 +61,44 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedi
38
61
  if (visited.has(nextUrl)) throw new FetchError(currentUrl, `Redirect loop detected: ${nextUrl}`);
39
62
  redirected++;
40
63
  }
41
- const response = await doubleKnock(originalRequest, identity, {
64
+ const result = await doubleKnockScoped(originalRequest, identity, {
42
65
  maxRedirection,
43
66
  specDeterminer,
44
67
  log: curry(logRequest)(logger$1),
45
68
  tracerProvider,
46
69
  signal: options?.signal,
47
- validateRedirect: async (nextUrl) => {
70
+ validateRedirect: (nextUrl) => {
48
71
  follow(nextUrl);
49
- await validateUrl(nextUrl);
72
+ validateUrl(nextUrl);
50
73
  visited.add(nextUrl);
51
74
  currentUrl = nextUrl;
52
75
  }
76
+ }, (hopUrl) => openHop(hopUrl, options?.signal), async (response) => {
77
+ let alternateUrl;
78
+ const document = await getRemoteDocument(currentUrl, response, (url) => {
79
+ alternateUrl = url;
80
+ return Promise.resolve(ALTERNATE_PLACEHOLDER);
81
+ });
82
+ if (alternateUrl == null) return { document };
83
+ if (!response.bodyUsed && response.body?.locked !== true) response.body?.cancel().catch((error) => {
84
+ logger$1.debug("Failed to cancel the response body from {url}: {error}", {
85
+ url: currentUrl,
86
+ error
87
+ });
88
+ });
89
+ return { alternateUrl };
53
90
  });
54
- return getRemoteDocument(currentUrl, response, (alternateUrl) => {
55
- follow(alternateUrl);
56
- return load(alternateUrl, options, redirected, visited);
57
- });
91
+ if ("document" in result) return result.document;
92
+ follow(result.alternateUrl);
93
+ return load(result.alternateUrl, options, redirected, visited);
58
94
  }
59
- async function validateUrl(url) {
60
- const parsedUrl = new URL(url);
61
- const protocol = parsedUrl.protocol;
62
- if (protocol !== "http:" && protocol !== "https:") throw new UrlError(`Unsupported protocol: ${protocol}`);
63
- if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new UrlError("URLs with credentials are not allowed");
64
- if (!allowPrivateAddress) try {
65
- await validatePublicUrl(url);
95
+ function openUnvalidatedHop(url, signal) {
96
+ if (deps.openHop != null) return deps.openHop(url);
97
+ return allowPrivateAddress ? openDirectFetch(url) : openPublicFetch(url, { signal });
98
+ }
99
+ async function openHop(url, signal) {
100
+ try {
101
+ return await openUnvalidatedHop(url, signal);
66
102
  } catch (error) {
67
103
  if (error instanceof UrlError) if (error.reason === "dns") logger$1.debug("DNS lookup failed for {url}", {
68
104
  url,
@@ -75,6 +111,12 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedi
75
111
  throw error;
76
112
  }
77
113
  }
114
+ function validateUrl(url) {
115
+ const parsedUrl = new URL(url);
116
+ const protocol = parsedUrl.protocol;
117
+ if (protocol !== "http:" && protocol !== "https:") throw new UrlError(`Unsupported protocol: ${protocol}`);
118
+ if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new UrlError("URLs with credentials are not allowed");
119
+ }
78
120
  return (url, options) => load(url, options);
79
121
  }
80
122
  //#endregion
@@ -1,10 +1,11 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  require("./chunk-DDcVe30Y.cjs");
4
- const require_http = require("./http-WcSdFbt1.cjs");
4
+ const require_http = require("./http-CSvwZqZm.cjs");
5
5
  let _logtape_logtape = require("@logtape/logtape");
6
6
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
7
7
  let es_toolkit = require("es-toolkit");
8
+ let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
8
9
  //#region src/utils/docloader.ts
9
10
  const logger$1 = (0, _logtape_logtape.getLogger)([
10
11
  "fedify",
@@ -25,12 +26,34 @@ const DEFAULT_MAX_REDIRECTION = 20;
25
26
  * @throws {TypeError} If the key is invalid or unsupported.
26
27
  * @since 0.4.0
27
28
  */
28
- function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedirection, userAgent, specDeterminer, tracerProvider } = {}) {
29
+ function getAuthenticatedDocumentLoader(identity, options = {}) {
30
+ return createAuthenticatedDocumentLoader(identity, options);
31
+ }
32
+ /**
33
+ * The placeholder that the alternate document callback of
34
+ * `getRemoteDocument()` returns, so that the alternate document is loaded
35
+ * after the current hop is closed.
36
+ */
37
+ const ALTERNATE_PLACEHOLDER = Object.freeze({
38
+ contextUrl: null,
39
+ document: null,
40
+ documentUrl: "about:blank"
41
+ });
42
+ /**
43
+ * The implementation of {@link getAuthenticatedDocumentLoader}. This is not
44
+ * exported from any entry point.
45
+ * @param identity The identity to get the document loader for.
46
+ * @param options The options for the document loader.
47
+ * @param deps The dependencies, for tests.
48
+ * @returns The authenticated document loader.
49
+ * @throws {TypeError} If the key is invalid or unsupported.
50
+ */
51
+ function createAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedirection, userAgent, specDeterminer, tracerProvider } = {}, deps = {}) {
29
52
  require_http.validateCryptoKey(identity.privateKey);
30
53
  async function load(url, options, redirected = 0, visited = /* @__PURE__ */ new Set()) {
31
54
  options?.signal?.throwIfAborted();
32
55
  let currentUrl = new URL(url).href;
33
- await validateUrl(currentUrl);
56
+ validateUrl(currentUrl);
34
57
  visited.add(currentUrl);
35
58
  const originalRequest = (0, _fedify_vocab_runtime.createActivityPubRequest)(currentUrl, { userAgent });
36
59
  function follow(nextUrl) {
@@ -39,31 +62,44 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedi
39
62
  if (visited.has(nextUrl)) throw new _fedify_vocab_runtime.FetchError(currentUrl, `Redirect loop detected: ${nextUrl}`);
40
63
  redirected++;
41
64
  }
42
- const response = await require_http.doubleKnock(originalRequest, identity, {
65
+ const result = await require_http.doubleKnockScoped(originalRequest, identity, {
43
66
  maxRedirection,
44
67
  specDeterminer,
45
68
  log: (0, es_toolkit.curry)(_fedify_vocab_runtime.logRequest)(logger$1),
46
69
  tracerProvider,
47
70
  signal: options?.signal,
48
- validateRedirect: async (nextUrl) => {
71
+ validateRedirect: (nextUrl) => {
49
72
  follow(nextUrl);
50
- await validateUrl(nextUrl);
73
+ validateUrl(nextUrl);
51
74
  visited.add(nextUrl);
52
75
  currentUrl = nextUrl;
53
76
  }
77
+ }, (hopUrl) => openHop(hopUrl, options?.signal), async (response) => {
78
+ let alternateUrl;
79
+ const document = await (0, _fedify_vocab_runtime.getRemoteDocument)(currentUrl, response, (url) => {
80
+ alternateUrl = url;
81
+ return Promise.resolve(ALTERNATE_PLACEHOLDER);
82
+ });
83
+ if (alternateUrl == null) return { document };
84
+ if (!response.bodyUsed && response.body?.locked !== true) response.body?.cancel().catch((error) => {
85
+ logger$1.debug("Failed to cancel the response body from {url}: {error}", {
86
+ url: currentUrl,
87
+ error
88
+ });
89
+ });
90
+ return { alternateUrl };
54
91
  });
55
- return (0, _fedify_vocab_runtime.getRemoteDocument)(currentUrl, response, (alternateUrl) => {
56
- follow(alternateUrl);
57
- return load(alternateUrl, options, redirected, visited);
58
- });
92
+ if ("document" in result) return result.document;
93
+ follow(result.alternateUrl);
94
+ return load(result.alternateUrl, options, redirected, visited);
59
95
  }
60
- async function validateUrl(url) {
61
- const parsedUrl = new URL(url);
62
- const protocol = parsedUrl.protocol;
63
- if (protocol !== "http:" && protocol !== "https:") throw new _fedify_vocab_runtime.UrlError(`Unsupported protocol: ${protocol}`);
64
- if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new _fedify_vocab_runtime.UrlError("URLs with credentials are not allowed");
65
- if (!allowPrivateAddress) try {
66
- await (0, _fedify_vocab_runtime.validatePublicUrl)(url);
96
+ function openUnvalidatedHop(url, signal) {
97
+ if (deps.openHop != null) return deps.openHop(url);
98
+ return allowPrivateAddress ? (0, _fedify_vocab_runtime_internal.openDirectFetch)(url) : (0, _fedify_vocab_runtime_internal.openPublicFetch)(url, { signal });
99
+ }
100
+ async function openHop(url, signal) {
101
+ try {
102
+ return await openUnvalidatedHop(url, signal);
67
103
  } catch (error) {
68
104
  if (error instanceof _fedify_vocab_runtime.UrlError) if (error.reason === "dns") logger$1.debug("DNS lookup failed for {url}", {
69
105
  url,
@@ -76,6 +112,12 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, maxRedi
76
112
  throw error;
77
113
  }
78
114
  }
115
+ function validateUrl(url) {
116
+ const parsedUrl = new URL(url);
117
+ const protocol = parsedUrl.protocol;
118
+ if (protocol !== "http:" && protocol !== "https:") throw new _fedify_vocab_runtime.UrlError(`Unsupported protocol: ${protocol}`);
119
+ if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new _fedify_vocab_runtime.UrlError("URLs with credentials are not allowed");
120
+ }
79
121
  return (url, options) => load(url, options);
80
122
  }
81
123
  //#endregion
@@ -1,9 +1,9 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-po8iekMB.mjs";
5
- import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-BS7YzLVA.mjs";
6
- import { r as fetchKey, s as validateCryptoKey } from "./key-BR2TRTXR.mjs";
4
+ import { n as version, t as name } from "./deno-D6uT0AM-.mjs";
5
+ import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-DuUzHGxP.mjs";
6
+ import { r as fetchKey, s as validateCryptoKey } from "./key-TRkqUVd-.mjs";
7
7
  import { getLogger } from "@logtape/logtape";
8
8
  import { Activity, CryptographicKey, Object as Object$1, getTypeId } from "@fedify/vocab";
9
9
  import { SpanStatusCode, trace } from "@opentelemetry/api";
@@ -1,7 +1,7 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-po8iekMB.mjs";
4
+ import { n as version, t as name } from "./deno-D6uT0AM-.mjs";
5
5
  import { metrics } from "@opentelemetry/api";
6
6
  import { FetchError } from "@fedify/vocab-runtime";
7
7
  //#region src/federation/metrics.ts
@@ -1,5 +1,5 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as FederationImpl } from "./middleware-B1RRLN7m.mjs";
4
+ import { n as FederationImpl } from "./middleware-BMqQ54Bi.mjs";
5
5
  export { FederationImpl };