@fedify/fedify 2.1.30 → 2.1.32

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 (104) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-CTpfuuVp.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-CAM_bQXx.d.cts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CSddvgWN.d.ts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-CjDMsn4a.mjs → client-cpPaW7Ww.mjs} +189 -65
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +254 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/transformers.test.mjs +1 -1
  12. package/dist/{context-DLLaDau8.d.ts → context-DE2YrQwM.d.ts} +56 -13
  13. package/dist/{context-BNwv9Q1v.d.cts → context-y6ZUQCMf.d.cts} +56 -13
  14. package/dist/{deno-BATJ1hq6.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/docloader-DUXr9k_O.mjs +124 -0
  16. package/dist/federation/attachment-responses.test.d.mts +2 -0
  17. package/dist/federation/attachment-responses.test.mjs +182 -0
  18. package/dist/federation/builder.test.mjs +1 -1
  19. package/dist/federation/collection.test.mjs +1 -1
  20. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  21. package/dist/federation/delivery-attachments.test.mjs +280 -0
  22. package/dist/federation/handler.test.mjs +208 -16
  23. package/dist/federation/idempotency.test.mjs +2 -2
  24. package/dist/federation/inbox.test.mjs +1 -1
  25. package/dist/federation/middleware.test.mjs +1559 -26
  26. package/dist/federation/mod.cjs +1 -1
  27. package/dist/federation/mod.d.cts +2 -2
  28. package/dist/federation/mod.d.ts +2 -2
  29. package/dist/federation/mod.js +1 -1
  30. package/dist/federation/negotiation.test.mjs +1 -1
  31. package/dist/federation/retry.test.mjs +1 -1
  32. package/dist/federation/send.test.mjs +723 -68
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-CK3efjgM.js → http-BtbMAgTA.js} +176 -105
  36. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  37. package/dist/{http-BoR1M3W7.cjs → http-D5woFKA_.cjs} +177 -106
  38. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  39. package/dist/{http-Bjd6I92u.mjs → http-HX6wVyJh.mjs} +198 -98
  40. package/dist/{inbox-9MlBGgs9.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-ClQh9Qqh.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-BxSx_Iyp.cjs → kv-cache-B0V_e231.cjs} +59 -17
  43. package/dist/{kv-cache-ImApO425.js → kv-cache-BsDg-cT8.js} +60 -18
  44. package/dist/{ld-Crg0Xmwr.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-jL9p9V9G.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-CmD3lpy4.cjs → middleware-CrfRuKCf.cjs} +728 -143
  48. package/dist/{middleware-CE0b69gj.mjs → middleware-DiquMgtt.mjs} +444 -115
  49. package/dist/{middleware-C2AJFk8W.js → middleware-DunNtbo9.js} +727 -143
  50. package/dist/{middleware-Bi5D6DBT.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-DiuFTYUt.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CWJNbyju.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-BLDHhuW0.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-DNEgTI8M.d.ts → mod-REfljt0T.d.ts} +4 -9
  55. package/dist/{mod-Cn9GJ5ex.d.cts → mod-UvIGUHqW.d.cts} +4 -9
  56. package/dist/{mod-BmlfRBmU.d.cts → mod-sTa1Zzxk.d.cts} +1 -1
  57. package/dist/mod.cjs +5 -5
  58. package/dist/mod.d.cts +8 -8
  59. package/dist/mod.d.ts +8 -8
  60. package/dist/mod.js +5 -5
  61. package/dist/nodeinfo/client.test.mjs +764 -19
  62. package/dist/nodeinfo/handler.test.mjs +1 -1
  63. package/dist/nodeinfo/mod.cjs +1 -1
  64. package/dist/nodeinfo/mod.d.cts +1 -1
  65. package/dist/nodeinfo/mod.d.ts +1 -1
  66. package/dist/nodeinfo/mod.js +1 -1
  67. package/dist/nodeinfo/types.test.mjs +1 -1
  68. package/dist/otel/exporter.test.mjs +292 -30
  69. package/dist/otel/mod.cjs +36 -30
  70. package/dist/otel/mod.d.cts +13 -0
  71. package/dist/otel/mod.d.ts +13 -0
  72. package/dist/otel/mod.js +36 -30
  73. package/dist/{owner-BRoKojK1.mjs → owner-DwyDorZI.mjs} +2 -2
  74. package/dist/{proof-CHXVlsH_.cjs → proof-Be-4K4jn.cjs} +193 -46
  75. package/dist/{proof-DMIAezxz.mjs → proof-DYjmyrHh.mjs} +38 -13
  76. package/dist/{proof-7R4s10TJ.js → proof-Du4-5SHY.js} +187 -46
  77. package/dist/send-BGSfQkIK.mjs +416 -0
  78. package/dist/sig/http.test.mjs +506 -2
  79. package/dist/sig/key-types.test.d.mts +218 -0
  80. package/dist/sig/key-types.test.mjs +8 -0
  81. package/dist/sig/key.test.mjs +2 -2
  82. package/dist/sig/ld.test.mjs +573 -8
  83. package/dist/sig/mod.cjs +2 -2
  84. package/dist/sig/mod.d.cts +3 -3
  85. package/dist/sig/mod.d.ts +3 -3
  86. package/dist/sig/mod.js +2 -2
  87. package/dist/sig/owner.test.mjs +1 -1
  88. package/dist/sig/proof.test.mjs +95 -3
  89. package/dist/{temporal-DR0JahMu.mjs → temporal-CNCchWly.mjs} +3 -5
  90. package/dist/testing/mod.d.mts +1 -2177
  91. package/dist/{types-DRPjmHVV.cjs → types-B5wRhemi.cjs} +187 -63
  92. package/dist/{types-miAYfiGO.js → types-CXy2lRVU.js} +188 -64
  93. package/dist/utils/docloader.test.mjs +316 -32
  94. package/dist/utils/mod.cjs +1 -1
  95. package/dist/utils/mod.d.cts +1 -1
  96. package/dist/utils/mod.d.ts +1 -1
  97. package/dist/utils/mod.js +1 -1
  98. package/package.json +7 -7
  99. package/dist/docloader-OLWc7P2D.mjs +0 -82
  100. package/dist/send-BHIt_8ia.mjs +0 -260
  101. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  102. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  103. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  104. /package/dist/{types-DCP0WLdt.mjs → types-s4mCTGkT.mjs} +0 -0
@@ -1,12 +1,13 @@
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-BATJ1hq6.mjs";
4
+ import { n as version, t as name } from "./deno-L23b3Hba.mjs";
5
5
  import { i as validateAcceptSignature, n as fulfillAcceptSignature, r as parseAcceptSignature } from "./accept-BavzedPB.mjs";
6
- import { i as fetchKeyDetailed, s as validateCryptoKey } from "./key-ClQh9Qqh.mjs";
6
+ import { i as fetchKeyDetailed, s as validateCryptoKey } from "./key-Dai3f5yI.mjs";
7
7
  import { CryptographicKey } from "@fedify/vocab";
8
8
  import { SpanStatusCode, trace } from "@opentelemetry/api";
9
9
  import { FetchError } from "@fedify/vocab-runtime";
10
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
10
11
  import { getLogger } from "@logtape/logtape";
11
12
  import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
12
13
  import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
@@ -26,12 +27,13 @@ const DOUBLE_KNOCK_TRANSPORT_RETRY_DELAY_MS = 100;
26
27
  */
27
28
  async function signRequest(request, privateKey, keyId, options = {}) {
28
29
  validateCryptoKey(privateKey, "private");
30
+ const signingKey = asCryptoKey(privateKey);
29
31
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("http_signatures.sign", async (span) => {
30
32
  try {
31
33
  const spec = options.spec ?? "draft-cavage-http-signatures-12";
32
34
  let signed;
33
- if (spec === "rfc9421") signed = await signRequestRfc9421(request, privateKey, keyId, span, options.currentTime, options.body, options.rfc9421);
34
- else signed = await signRequestDraft(request, privateKey, keyId, span, options.currentTime, options.body);
35
+ if (spec === "rfc9421") signed = await signRequestRfc9421(request, signingKey, keyId, span, options.currentTime, options.body, options.rfc9421);
36
+ else signed = await signRequestDraft(request, signingKey, keyId, span, options.currentTime, options.body);
35
37
  if (span.isRecording()) {
36
38
  span.setAttribute(ATTR_HTTP_REQUEST_METHOD, signed.method);
37
39
  span.setAttribute(ATTR_URL_FULL, signed.url);
@@ -849,10 +851,10 @@ async function createRedirectRequest(request, location, body, validateRedirect)
849
851
  cache: request.cache
850
852
  });
851
853
  }
852
- async function fetchDoubleKnockRequest(request, signedRequest, signal) {
854
+ async function fetchDoubleKnockRequest(session, request, signedRequest, signal) {
853
855
  const maxAttempts = request.method === "GET" || request.method === "HEAD" ? 2 : 1;
854
856
  for (let attempt = 1;; attempt++) try {
855
- return await fetch(signedRequest, {
857
+ return await session.fetch(signedRequest, {
856
858
  redirect: "manual",
857
859
  signal
858
860
  });
@@ -913,107 +915,205 @@ function getAbortReason(signal) {
913
915
  * @since 1.6.0
914
916
  */
915
917
  async function doubleKnock(request, identity, options = {}) {
916
- return await doubleKnockInternal(request, identity, options);
918
+ const { response } = await doubleKnockCore(request, identity, options, openGlobalFetchHop);
919
+ return response;
917
920
  }
918
- async function doubleKnockInternal(request, identity, options, redirected = 0, visited = /* @__PURE__ */ new Set()) {
919
- const { specDeterminer, log, tracerProvider, signal } = options;
920
- visited.add(request.url);
921
- const origin = new URL(request.url).origin;
922
- const firstTrySpec = specDeterminer == null ? "rfc9421" : await specDeterminer.determineSpec(origin);
923
- const body = options.body !== void 0 ? options.body : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
924
- let signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
925
- spec: firstTrySpec,
926
- tracerProvider,
927
- body
921
+ /**
922
+ * Performs a double-knock request like {@link doubleKnock}, opening a session
923
+ * for every hop with the given function, and passes the final response to
924
+ * the given function. The final session is closed after `consume` settles,
925
+ * so `consume` must read or cancel the response body before it returns.
926
+ * This is not exported from any entry point.
927
+ * @param request The request to send.
928
+ * @param identity The identity to use for signing the request.
929
+ * @param options The options for double-knock requests.
930
+ * @param openHop The function to open a session for each hop. The session of
931
+ * a hop is closed before the next hop is opened.
932
+ * @param consume The function to consume the final response.
933
+ * @returns The value returned by `consume`.
934
+ */
935
+ async function doubleKnockScoped(request, identity, options, openHop, consume) {
936
+ const { response, session } = await doubleKnockCore(request, identity, options, openHop);
937
+ try {
938
+ return await consume(response);
939
+ } catch (error) {
940
+ getLogger([
941
+ "fedify",
942
+ "sig",
943
+ "http"
944
+ ]).debug("Failed to consume the response from {url}; closing the session: {error}", {
945
+ url: request.url,
946
+ error
947
+ });
948
+ throw error;
949
+ } finally {
950
+ await session.close();
951
+ }
952
+ }
953
+ /**
954
+ * A hop session for {@link doubleKnock}: it uses the global `fetch()` without
955
+ * validating or pinning addresses, and its `close()` does nothing, so that
956
+ * the final response can be returned to the caller.
957
+ */
958
+ function openGlobalFetchHop(url) {
959
+ const sessionUrl = new URL(url);
960
+ return Promise.resolve({
961
+ get url() {
962
+ return new URL(sessionUrl);
963
+ },
964
+ fetch: (input, init) => fetch(input, init),
965
+ close: () => Promise.resolve()
928
966
  });
929
- log?.(signedRequest);
930
- let response = await fetchDoubleKnockRequest(request, signedRequest, signal);
931
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
932
- if (redirected >= DEFAULT_MAX_REDIRECTION) throw new FetchError(request.url, `Too many redirections (${redirected + 1})`);
933
- const redirectRequest = await createRedirectRequest(request, response.headers.get("Location"), body, options.validateRedirect);
934
- if (visited.has(redirectRequest.url)) throw new FetchError(request.url, `Redirect loop detected: ${redirectRequest.url}`);
935
- return doubleKnockInternal(redirectRequest, identity, {
936
- ...options,
937
- body
938
- }, redirected + 1, visited);
939
- } else if (response.status === 400 || response.status === 401 || response.status > 401) {
940
- const logger = getLogger([
967
+ }
968
+ function isRedirectResponse(response) {
969
+ return response.status >= 300 && response.status < 400 && response.headers.has("Location");
970
+ }
971
+ /**
972
+ * Starts cancelling the body of a response that is not passed to the caller,
973
+ * without waiting for it to settle. The cancellation of a branch of a tee
974
+ * (e.g., a body cloned by a fetch mock) settles only after the other branch
975
+ * is cancelled too, per the Streams standard, so awaiting it could block
976
+ * forever. Failures are only logged.
977
+ */
978
+ function cancelResponseBody(response, url) {
979
+ response.body?.cancel().catch((error) => {
980
+ getLogger([
941
981
  "fedify",
942
982
  "sig",
943
983
  "http"
944
- ]);
945
- const acceptSigHeader = response.headers.get("Accept-Signature");
946
- if (acceptSigHeader != null) {
947
- const entries = validateAcceptSignature(parseAcceptSignature(acceptSigHeader));
948
- const localKeyId = identity.keyId.href;
949
- const localAlg = "rsa-v1_5-sha256";
950
- let fulfilled = false;
951
- let challengeRequest;
952
- for (const entry of entries) {
953
- const rfc9421 = fulfillAcceptSignature(entry, localKeyId, localAlg);
954
- if (rfc9421 == null) continue;
955
- logger.debug("Received Accept-Signature challenge; accumulating label {label} and components {components}.", {
956
- label: rfc9421.label,
957
- components: rfc9421.components
958
- });
959
- try {
960
- challengeRequest = await signRequest(challengeRequest ?? request, identity.privateKey, identity.keyId, {
961
- spec: "rfc9421",
962
- tracerProvider,
963
- body,
964
- rfc9421
984
+ ]).debug("Failed to cancel the response body from {url}: {error}", {
985
+ url,
986
+ error
987
+ });
988
+ });
989
+ }
990
+ async function doubleKnockCore(request, identity, options, openHop) {
991
+ const { specDeterminer, log, tracerProvider, signal } = options;
992
+ const visited = /* @__PURE__ */ new Set();
993
+ const body = options.body !== void 0 ? options.body : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
994
+ let session = await openHop(request.url);
995
+ try {
996
+ for (let redirected = 0;; redirected++) {
997
+ visited.add(request.url);
998
+ const origin = new URL(request.url).origin;
999
+ const firstTrySpec = specDeterminer == null ? "rfc9421" : await specDeterminer.determineSpec(origin);
1000
+ let signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
1001
+ spec: firstTrySpec,
1002
+ tracerProvider,
1003
+ body
1004
+ });
1005
+ log?.(signedRequest);
1006
+ let response = await fetchDoubleKnockRequest(session, request, signedRequest, signal);
1007
+ const firstRedirected = isRedirectResponse(response);
1008
+ if (!firstRedirected && (response.status === 400 || response.status === 401 || response.status > 401)) {
1009
+ const logger = getLogger([
1010
+ "fedify",
1011
+ "sig",
1012
+ "http"
1013
+ ]);
1014
+ const acceptSigHeader = response.headers.get("Accept-Signature");
1015
+ if (acceptSigHeader != null) {
1016
+ const entries = validateAcceptSignature(parseAcceptSignature(acceptSigHeader));
1017
+ const localKeyId = identity.keyId.href;
1018
+ const localAlg = "rsa-v1_5-sha256";
1019
+ let fulfilled = false;
1020
+ let challengeRequest;
1021
+ for (const entry of entries) {
1022
+ const rfc9421 = fulfillAcceptSignature(entry, localKeyId, localAlg);
1023
+ if (rfc9421 == null) continue;
1024
+ logger.debug("Received Accept-Signature challenge; accumulating label {label} and components {components}.", {
1025
+ label: rfc9421.label,
1026
+ components: rfc9421.components
1027
+ });
1028
+ try {
1029
+ challengeRequest = await signRequest(challengeRequest ?? request, identity.privateKey, identity.keyId, {
1030
+ spec: "rfc9421",
1031
+ tracerProvider,
1032
+ body,
1033
+ rfc9421
1034
+ });
1035
+ fulfilled = true;
1036
+ } catch (error) {
1037
+ logger.debug("Failed to fulfill Accept-Signature challenge entry {label}: {error}", {
1038
+ label: entry.label,
1039
+ error
1040
+ });
1041
+ }
1042
+ }
1043
+ if (fulfilled && challengeRequest != null) {
1044
+ cancelResponseBody(response, request.url);
1045
+ signedRequest = challengeRequest;
1046
+ log?.(signedRequest);
1047
+ response = await session.fetch(signedRequest, {
1048
+ redirect: "manual",
1049
+ signal
1050
+ });
1051
+ }
1052
+ if (fulfilled && !isRedirectResponse(response)) {
1053
+ if (response.status < 300) {
1054
+ await specDeterminer?.rememberSpec(origin, "rfc9421");
1055
+ return {
1056
+ response,
1057
+ session
1058
+ };
1059
+ }
1060
+ if (response.status !== 400 && response.status !== 401) return {
1061
+ response,
1062
+ session
1063
+ };
1064
+ }
1065
+ }
1066
+ if (!isRedirectResponse(response)) {
1067
+ const spec = firstTrySpec === "draft-cavage-http-signatures-12" ? "rfc9421" : "draft-cavage-http-signatures-12";
1068
+ getLogger([
1069
+ "fedify",
1070
+ "sig",
1071
+ "http"
1072
+ ]).debug("Failed to verify with the spec {spec} ({status} {statusText}); retrying with spec {secondSpec}... (double-knocking)", {
1073
+ spec: firstTrySpec,
1074
+ secondSpec: spec,
1075
+ status: response.status,
1076
+ statusText: response.statusText
965
1077
  });
966
- fulfilled = true;
967
- } catch (error) {
968
- logger.debug("Failed to fulfill Accept-Signature challenge entry {label}: {error}", {
969
- label: entry.label,
970
- error
1078
+ cancelResponseBody(response, request.url);
1079
+ signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
1080
+ spec,
1081
+ tracerProvider,
1082
+ body
971
1083
  });
1084
+ log?.(signedRequest);
1085
+ response = await fetchDoubleKnockRequest(session, request, signedRequest, signal);
1086
+ if (!isRedirectResponse(response) && response.status !== 400 && response.status !== 401) await specDeterminer?.rememberSpec(origin, spec);
972
1087
  }
973
- }
974
- if (fulfilled && challengeRequest != null) {
975
- signedRequest = challengeRequest;
976
- log?.(signedRequest);
977
- response = await fetch(signedRequest, {
978
- redirect: "manual",
979
- signal
980
- });
981
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) return doubleKnock(await createRedirectRequest(request, response.headers.get("Location"), body, options.validateRedirect), identity, {
982
- ...options,
983
- body
984
- });
985
- }
986
- if (fulfilled && response.status < 300) {
987
- await specDeterminer?.rememberSpec(origin, "rfc9421");
988
- return response;
989
- }
990
- if (fulfilled && response.status !== 400 && response.status !== 401) return response;
991
- }
992
- const spec = firstTrySpec === "draft-cavage-http-signatures-12" ? "rfc9421" : "draft-cavage-http-signatures-12";
993
- logger.debug("Failed to verify with the spec {spec} ({status} {statusText}); retrying with spec {secondSpec}... (double-knocking)", {
994
- spec: firstTrySpec,
995
- secondSpec: spec,
996
- status: response.status,
997
- statusText: response.statusText
998
- });
999
- signedRequest = await signRequest(request, identity.privateKey, identity.keyId, {
1000
- spec,
1001
- tracerProvider,
1002
- body
1003
- });
1004
- log?.(signedRequest);
1005
- response = await fetchDoubleKnockRequest(request, signedRequest, signal);
1006
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
1088
+ } else if (!firstRedirected) await specDeterminer?.rememberSpec(origin, firstTrySpec);
1089
+ if (!isRedirectResponse(response)) return {
1090
+ response,
1091
+ session
1092
+ };
1093
+ cancelResponseBody(response, request.url);
1094
+ await session.close();
1007
1095
  if (redirected >= DEFAULT_MAX_REDIRECTION) throw new FetchError(request.url, `Too many redirections (${redirected + 1})`);
1008
- const redirectRequest = await createRedirectRequest(request, response.headers.get("Location"), body, options.validateRedirect);
1096
+ const location = response.headers.get("Location");
1097
+ const redirectRequest = await createRedirectRequest(request, location, body, options.validateRedirect);
1009
1098
  if (visited.has(redirectRequest.url)) throw new FetchError(request.url, `Redirect loop detected: ${redirectRequest.url}`);
1010
- return doubleKnockInternal(redirectRequest, identity, {
1011
- ...options,
1012
- body
1013
- }, redirected + 1, visited);
1014
- } else if (response.status !== 400 && response.status !== 401) await specDeterminer?.rememberSpec(origin, spec);
1015
- } else await specDeterminer?.rememberSpec(origin, firstTrySpec);
1016
- return response;
1099
+ request = redirectRequest;
1100
+ session = await openHop(request.url);
1101
+ }
1102
+ } catch (error) {
1103
+ try {
1104
+ await session.close();
1105
+ } catch (closeError) {
1106
+ getLogger([
1107
+ "fedify",
1108
+ "sig",
1109
+ "http"
1110
+ ]).debug("Failed to close the session for {url}: {error}", {
1111
+ url: request.url,
1112
+ error: closeError
1113
+ });
1114
+ }
1115
+ throw error;
1116
+ }
1017
1117
  }
1018
1118
  /**
1019
1119
  * Performs a timing-safe equality comparison between two `Uint8Array` values.
@@ -1043,4 +1143,4 @@ function timingSafeEqual(a, b) {
1043
1143
  return result === 0;
1044
1144
  }
1045
1145
  //#endregion
1046
- 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 };
1146
+ 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,7 +1,7 @@
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-BATJ1hq6.mjs";
4
+ import { n as version, t as name } from "./deno-L23b3Hba.mjs";
5
5
  import { Activity, getTypeId } from "@fedify/vocab";
6
6
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
7
7
  import { getLogger } from "@logtape/logtape";
@@ -1,10 +1,11 @@
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-BATJ1hq6.mjs";
4
+ import { n as version, t as name } from "./deno-L23b3Hba.mjs";
5
5
  import { CryptographicKey, Object as Object$1, isActor } from "@fedify/vocab";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
7
  import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";
8
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
8
9
  import { getLogger } from "@logtape/logtape";
9
10
  //#region src/sig/key.ts
10
11
  /** Classifies decoding failures without hiding unexpected loader errors. */
@@ -116,7 +117,7 @@ function generateCryptoKeyPair(algorithm) {
116
117
  */
117
118
  async function exportJwk(key) {
118
119
  validateCryptoKey(key);
119
- const jwk = await crypto.subtle.exportKey("jwk", key);
120
+ const jwk = await crypto.subtle.exportKey("jwk", asCryptoKey(key));
120
121
  if (jwk.crv === "Ed25519") jwk.alg = "Ed25519";
121
122
  return jwk;
122
123
  }
@@ -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-BoR1M3W7.cjs");
4
+ const require_http = require("./http-D5woFKA_.cjs");
5
5
  let _logtape_logtape = require("@logtape/logtape");
6
6
  let es_toolkit = require("es-toolkit");
7
7
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
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, 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, 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,30 +62,43 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, userAge
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
  specDeterminer,
44
67
  log: (0, es_toolkit.curry)(_fedify_vocab_runtime.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 (0, _fedify_vocab_runtime.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 (0, _fedify_vocab_runtime.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 _fedify_vocab_runtime.UrlError(`Unsupported protocol: ${protocol}`);
63
- if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new _fedify_vocab_runtime.UrlError("URLs with credentials are not allowed");
64
- if (!allowPrivateAddress) try {
65
- await (0, _fedify_vocab_runtime.validatePublicUrl)(url);
95
+ function openUnvalidatedHop(url, signal) {
96
+ if (deps.openHop != null) return deps.openHop(url);
97
+ return allowPrivateAddress ? (0, _fedify_vocab_runtime_internal.openDirectFetch)(url) : (0, _fedify_vocab_runtime_internal.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 _fedify_vocab_runtime.UrlError) if (error.reason === "dns") logger$1.debug("DNS lookup failed for {url}", {
68
104
  url,
@@ -75,6 +111,12 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, userAge
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 _fedify_vocab_runtime.UrlError(`Unsupported protocol: ${protocol}`);
118
+ if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new _fedify_vocab_runtime.UrlError("URLs with credentials are not allowed");
119
+ }
78
120
  return (url, options) => load(url, options);
79
121
  }
80
122
  //#endregion
@@ -1,9 +1,10 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { f as validateCryptoKey, t as doubleKnock } from "./http-CK3efjgM.js";
3
+ import { f as validateCryptoKey, t as doubleKnockScoped } from "./http-BtbMAgTA.js";
4
4
  import { getLogger } from "@logtape/logtape";
5
5
  import { curry } from "es-toolkit";
6
- import { FetchError, UrlError, createActivityPubRequest, getRemoteDocument, logRequest, preloadedContexts, validatePublicUrl } from "@fedify/vocab-runtime";
6
+ import { FetchError, UrlError, createActivityPubRequest, getRemoteDocument, logRequest, preloadedContexts } from "@fedify/vocab-runtime";
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, 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, 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,30 +61,43 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, userAge
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
  specDeterminer,
43
66
  log: curry(logRequest)(logger$1),
44
67
  tracerProvider,
45
68
  signal: options?.signal,
46
- validateRedirect: async (nextUrl) => {
69
+ validateRedirect: (nextUrl) => {
47
70
  follow(nextUrl);
48
- await validateUrl(nextUrl);
71
+ validateUrl(nextUrl);
49
72
  visited.add(nextUrl);
50
73
  currentUrl = nextUrl;
51
74
  }
75
+ }, (hopUrl) => openHop(hopUrl, options?.signal), async (response) => {
76
+ let alternateUrl;
77
+ const document = await getRemoteDocument(currentUrl, response, (url) => {
78
+ alternateUrl = url;
79
+ return Promise.resolve(ALTERNATE_PLACEHOLDER);
80
+ });
81
+ if (alternateUrl == null) return { document };
82
+ if (!response.bodyUsed && response.body?.locked !== true) response.body?.cancel().catch((error) => {
83
+ logger$1.debug("Failed to cancel the response body from {url}: {error}", {
84
+ url: currentUrl,
85
+ error
86
+ });
87
+ });
88
+ return { alternateUrl };
52
89
  });
53
- return getRemoteDocument(currentUrl, response, (alternateUrl) => {
54
- follow(alternateUrl);
55
- return load(alternateUrl, options, redirected, visited);
56
- });
90
+ if ("document" in result) return result.document;
91
+ follow(result.alternateUrl);
92
+ return load(result.alternateUrl, options, redirected, visited);
57
93
  }
58
- async function validateUrl(url) {
59
- const parsedUrl = new URL(url);
60
- const protocol = parsedUrl.protocol;
61
- if (protocol !== "http:" && protocol !== "https:") throw new UrlError(`Unsupported protocol: ${protocol}`);
62
- if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new UrlError("URLs with credentials are not allowed");
63
- if (!allowPrivateAddress) try {
64
- await validatePublicUrl(url);
94
+ function openUnvalidatedHop(url, signal) {
95
+ if (deps.openHop != null) return deps.openHop(url);
96
+ return allowPrivateAddress ? openDirectFetch(url) : openPublicFetch(url, { signal });
97
+ }
98
+ async function openHop(url, signal) {
99
+ try {
100
+ return await openUnvalidatedHop(url, signal);
65
101
  } catch (error) {
66
102
  if (error instanceof UrlError) if (error.reason === "dns") logger$1.debug("DNS lookup failed for {url}", {
67
103
  url,
@@ -74,6 +110,12 @@ function getAuthenticatedDocumentLoader(identity, { allowPrivateAddress, userAge
74
110
  throw error;
75
111
  }
76
112
  }
113
+ function validateUrl(url) {
114
+ const parsedUrl = new URL(url);
115
+ const protocol = parsedUrl.protocol;
116
+ if (protocol !== "http:" && protocol !== "https:") throw new UrlError(`Unsupported protocol: ${protocol}`);
117
+ if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new UrlError("URLs with credentials are not allowed");
118
+ }
77
119
  return (url, options) => load(url, options);
78
120
  }
79
121
  //#endregion