@fedify/vocab-runtime 2.0.35-dev.2470 → 2.0.35-dev.2485
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.
- package/deno.json +5 -2
- package/dist/internal.cjs +6 -0
- package/dist/internal.d.cts +3 -0
- package/dist/internal.d.ts +3 -0
- package/dist/internal.js +3 -0
- package/dist/mod.cjs +105 -253
- package/dist/mod.d.cts +5 -27
- package/dist/mod.d.ts +6 -27
- package/dist/mod.js +98 -245
- package/dist/public-fetch-BC-nWJNM.d.ts +143 -0
- package/dist/public-fetch-CFnW7XMn.cjs +821 -0
- package/dist/public-fetch-DBpt3xxf.d.cts +143 -0
- package/dist/public-fetch-Dfmc_Kfy.js +772 -0
- package/dist/tests/{body-B-tzXBv1.cjs → body-1FbapsC3.cjs} +1 -1
- package/dist/tests/{body-DADIzmaJ.mjs → body-GD9HfwgN.mjs} +1 -1
- package/dist/tests/body.test.cjs +1 -1
- package/dist/tests/body.test.mjs +1 -1
- package/dist/tests/docloader.test.cjs +616 -1306
- package/dist/tests/docloader.test.mjs +562 -1271
- package/dist/tests/esm-4DuocLvD.cjs +1208 -0
- package/dist/tests/esm-CnLt0wAF.mjs +1225 -0
- package/dist/tests/internal/multicodec.test.cjs +1 -1
- package/dist/tests/internal/multicodec.test.mjs +1 -1
- package/dist/tests/key.test.cjs +2 -2
- package/dist/tests/key.test.mjs +2 -2
- package/dist/tests/langstr.test.cjs +1 -1
- package/dist/tests/langstr.test.mjs +1 -1
- package/dist/tests/langtag.test.cjs +1 -1
- package/dist/tests/langtag.test.mjs +1 -1
- package/dist/tests/link.test.cjs +1 -1
- package/dist/tests/link.test.mjs +1 -1
- package/dist/tests/multibase/multibase.test.cjs +1 -1
- package/dist/tests/multibase/multibase.test.mjs +1 -1
- package/dist/tests/node-BTPYk2h-.mjs +84 -0
- package/dist/tests/node-DWD76vPo.cjs +90 -0
- package/dist/tests/pin-grant-BAlKqSph.mjs +53 -0
- package/dist/tests/pin-grant-CU-o367k.cjs +70 -0
- package/dist/tests/pin-grant.test.cjs +88 -0
- package/dist/tests/pin-grant.test.d.cts +1 -0
- package/dist/tests/pin-grant.test.d.mts +1 -0
- package/dist/tests/pin-grant.test.mjs +88 -0
- package/dist/tests/pinners/bun.test.cjs +167 -0
- package/dist/tests/pinners/bun.test.d.cts +1 -0
- package/dist/tests/pinners/bun.test.d.mts +1 -0
- package/dist/tests/pinners/bun.test.mjs +167 -0
- package/dist/tests/pinners/node.test.cjs +269 -0
- package/dist/tests/pinners/node.test.d.cts +1 -0
- package/dist/tests/pinners/node.test.d.mts +1 -0
- package/dist/tests/pinners/node.test.mjs +268 -0
- package/dist/tests/pinners/pinners.test.cjs +197 -0
- package/dist/tests/pinners/pinners.test.d.cts +1 -0
- package/dist/tests/pinners/pinners.test.d.mts +1 -0
- package/dist/tests/pinners/pinners.test.mjs +197 -0
- package/dist/tests/pinners/testdata/node-child.cjs +135 -0
- package/dist/tests/pinners/testdata/node-child.d.cts +1 -0
- package/dist/tests/pinners/testdata/node-child.d.mts +1 -0
- package/dist/tests/pinners/testdata/node-child.mjs +134 -0
- package/dist/tests/pinners-BjE-YJLL.cjs +221 -0
- package/dist/tests/pinners-C0SoXz-S.mjs +203 -0
- package/dist/tests/public-fetch-BUSPlh1C.mjs +170 -0
- package/dist/tests/public-fetch-Ddjfxbwc.cjs +187 -0
- package/dist/tests/public-fetch.test.cjs +1074 -0
- package/dist/tests/public-fetch.test.d.cts +1 -0
- package/dist/tests/public-fetch.test.d.mts +1 -0
- package/dist/tests/public-fetch.test.mjs +1074 -0
- package/dist/tests/{request-D112qkNN.cjs → request-C4q9phZR.cjs} +1 -1
- package/dist/tests/{request-BwExjPn9.mjs → request-Dr5LoMPw.mjs} +1 -1
- package/dist/tests/request.test.cjs +1 -1
- package/dist/tests/request.test.mjs +1 -1
- package/dist/tests/support-EdBgVdNy.cjs +363 -0
- package/dist/tests/support-SnCB9BSR.mjs +272 -0
- package/dist/tests/{url-Qk1svKZU.cjs → url-DLuSj57U.cjs} +88 -12
- package/dist/tests/{url-DzlMS01z.mjs → url-DjsVF44Q.mjs} +65 -13
- package/dist/tests/url.test.cjs +4 -1
- package/dist/tests/url.test.mjs +4 -1
- package/package.json +14 -3
- package/src/docloader.test.ts +690 -31
- package/src/docloader.ts +174 -67
- package/src/internal.ts +13 -0
- package/src/pin-grant.test.ts +118 -0
- package/src/pin-grant.ts +99 -0
- package/src/pinners/bun.test.ts +278 -0
- package/src/pinners/bun.ts +223 -0
- package/src/pinners/mod.ts +59 -0
- package/src/pinners/node.test.ts +415 -0
- package/src/pinners/node.ts +144 -0
- package/src/pinners/pinners.test.ts +316 -0
- package/src/pinners/testdata/node-child.ts +147 -0
- package/src/pinners/testdata/proxy-child.ts +82 -0
- package/src/pinners/testdata/support.ts +343 -0
- package/src/pinners/testdata/tls-cert.pem +12 -0
- package/src/pinners/testdata/tls-child.ts +88 -0
- package/src/pinners/testdata/tls-key.pem +5 -0
- package/src/pinners/types.ts +48 -0
- package/src/public-fetch.test.ts +1286 -0
- package/src/public-fetch.ts +338 -0
- package/src/testdata/public-fetch-deno-worker.ts +74 -0
- package/src/url.test.ts +11 -0
- package/src/url.ts +113 -22
- package/tsdown.config.ts +12 -3
- /package/dist/tests/{langtag-Bm8oKhIO.cjs → langtag-B_fXk5oL.cjs} +0 -0
- /package/dist/tests/{langtag-QZZgy903.mjs → langtag-CwDxJ10m.mjs} +0 -0
- /package/dist/tests/{link-NUUWCdnK.mjs → link-CYszIegt.mjs} +0 -0
- /package/dist/tests/{link-FguCydMA.cjs → link-qDTmjPw_.cjs} +0 -0
- /package/dist/tests/{multibase-CnmModw0.cjs → multibase-BKJat02S.cjs} +0 -0
- /package/dist/tests/{multibase-DLBufb99.mjs → multibase-CNswrMoP.mjs} +0 -0
- /package/dist/tests/{multicodec-CxGVGa91.cjs → multicodec-B-_CSt1M.cjs} +0 -0
- /package/dist/tests/{multicodec-CyFp54fI.mjs → multicodec-CDEzQTyO.mjs} +0 -0
package/src/docloader.ts
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import { getLogger } from "@logtape/logtape";
|
|
2
|
-
import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
2
|
+
import { type Span, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
3
3
|
import metadata from "../deno.json" with { type: "json" };
|
|
4
4
|
import { MAX_BODY_SIZE, readBoundedText } from "./body.ts";
|
|
5
5
|
import preloadedContexts from "./contexts.ts";
|
|
6
6
|
import { HttpHeaderLink } from "./link.ts";
|
|
7
|
+
import {
|
|
8
|
+
openDirectFetch,
|
|
9
|
+
openPublicFetch,
|
|
10
|
+
type PublicFetchSession,
|
|
11
|
+
} from "./public-fetch.ts";
|
|
7
12
|
import {
|
|
8
13
|
createActivityPubRequest,
|
|
9
14
|
FetchError,
|
|
10
15
|
type GetUserAgentOptions,
|
|
11
16
|
logRequest,
|
|
12
17
|
} from "./request.ts";
|
|
13
|
-
import { UrlError
|
|
18
|
+
import { UrlError } from "./url.ts";
|
|
14
19
|
|
|
15
20
|
const logger = getLogger(["fedify", "runtime", "docloader"]);
|
|
16
21
|
const DEFAULT_MAX_REDIRECTION = 20;
|
|
@@ -110,7 +115,9 @@ export type AuthenticatedDocumentLoaderFactory = (
|
|
|
110
115
|
* Gets a {@link RemoteDocument} from the given response.
|
|
111
116
|
* @param url The URL of the document to load.
|
|
112
117
|
* @param response The response to get the document from.
|
|
113
|
-
* @param fetch The function to fetch the document.
|
|
118
|
+
* @param fetch The function to fetch the document. It is called with the URL
|
|
119
|
+
* of an alternate document, if any, after the response body has
|
|
120
|
+
* been either read or its cancellation has been started.
|
|
114
121
|
* @returns The loaded remote document.
|
|
115
122
|
* @throws {FetchError} If the response is not OK.
|
|
116
123
|
* @internal
|
|
@@ -123,7 +130,54 @@ export async function getRemoteDocument(
|
|
|
123
130
|
options?: DocumentLoaderOptions,
|
|
124
131
|
) => Promise<RemoteDocument>,
|
|
125
132
|
): Promise<RemoteDocument> {
|
|
126
|
-
const
|
|
133
|
+
const result = await parseRemoteDocument(url, response);
|
|
134
|
+
if ("alternate" in result) return await fetch(result.alternate);
|
|
135
|
+
return result.document;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Starts cancelling the body of a response without waiting for it to settle.
|
|
140
|
+
* The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
|
|
141
|
+
* settles only after the other branch is cancelled too, per the Streams
|
|
142
|
+
* standard, so awaiting it could block forever. Failures are only logged.
|
|
143
|
+
* @param response The response whose body is cancelled.
|
|
144
|
+
* @param url The URL of the response, for logging.
|
|
145
|
+
*/
|
|
146
|
+
function cancelResponseBody(response: Response, url: string): void {
|
|
147
|
+
response.body?.cancel().catch((error) => {
|
|
148
|
+
logger.debug(
|
|
149
|
+
"Failed to cancel the response body from {url}: {error}",
|
|
150
|
+
{ url, error },
|
|
151
|
+
);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The result of {@link parseRemoteDocument}: either the loaded document, or
|
|
157
|
+
* the URL of an alternate document to load instead.
|
|
158
|
+
*/
|
|
159
|
+
type ParsedRemoteDocument =
|
|
160
|
+
| { readonly document: RemoteDocument }
|
|
161
|
+
| { readonly alternate: string };
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Gets a {@link RemoteDocument} from the given response, or the URL of an
|
|
165
|
+
* alternate document to load instead. When an alternate document is found,
|
|
166
|
+
* the response body has been either read or its cancellation has been started
|
|
167
|
+
* (without waiting for it), so that the alternate document can be loaded after
|
|
168
|
+
* the response's session is closed.
|
|
169
|
+
* @param url The URL of the document to load.
|
|
170
|
+
* @param response The response to get the document from.
|
|
171
|
+
* @returns The loaded remote document, or the alternate document URL.
|
|
172
|
+
* @throws {FetchError} If the response is not OK.
|
|
173
|
+
*/
|
|
174
|
+
async function parseRemoteDocument(
|
|
175
|
+
url: string,
|
|
176
|
+
response: Response,
|
|
177
|
+
): Promise<ParsedRemoteDocument> {
|
|
178
|
+
// Since the response URL is an IP address URL on runtimes that pin
|
|
179
|
+
// connections, the request URL is used instead:
|
|
180
|
+
const documentUrl = url;
|
|
127
181
|
const docUrl = new URL(documentUrl);
|
|
128
182
|
if (!response.ok) {
|
|
129
183
|
logger.error(
|
|
@@ -181,7 +235,8 @@ export async function getRemoteDocument(
|
|
|
181
235
|
"Found alternate document: {alternateUrl} from {url}",
|
|
182
236
|
{ alternateUrl: altUri.href, url: documentUrl },
|
|
183
237
|
);
|
|
184
|
-
|
|
238
|
+
cancelResponseBody(response, documentUrl);
|
|
239
|
+
return { alternate: altUri.href };
|
|
185
240
|
}
|
|
186
241
|
}
|
|
187
242
|
}
|
|
@@ -233,7 +288,7 @@ export async function getRemoteDocument(
|
|
|
233
288
|
"Found alternate document: {alternateUrl} from {url}",
|
|
234
289
|
{ alternateUrl: attribs.href, url: documentUrl },
|
|
235
290
|
);
|
|
236
|
-
return
|
|
291
|
+
return { alternate: new URL(attribs.href, docUrl).href };
|
|
237
292
|
}
|
|
238
293
|
}
|
|
239
294
|
document = JSON.parse(html);
|
|
@@ -250,7 +305,7 @@ export async function getRemoteDocument(
|
|
|
250
305
|
headers: Object.fromEntries(response.headers.entries()),
|
|
251
306
|
},
|
|
252
307
|
);
|
|
253
|
-
return { contextUrl, document, documentUrl };
|
|
308
|
+
return { document: { contextUrl, document, documentUrl } };
|
|
254
309
|
}
|
|
255
310
|
|
|
256
311
|
/**
|
|
@@ -289,12 +344,98 @@ export interface GetDocumentLoaderOptions extends DocumentLoaderFactoryOptions {
|
|
|
289
344
|
* @since 1.3.0
|
|
290
345
|
*/
|
|
291
346
|
export function getDocumentLoader(
|
|
347
|
+
options: GetDocumentLoaderOptions = {},
|
|
348
|
+
): DocumentLoader {
|
|
349
|
+
return createDocumentLoader(options);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The dependencies of {@link createDocumentLoader}.
|
|
354
|
+
*/
|
|
355
|
+
export interface DocumentLoaderDependencies {
|
|
356
|
+
/**
|
|
357
|
+
* Opens the fetch session for a single hop, instead of
|
|
358
|
+
* {@link openPublicFetch} (or {@link openDirectFetch} if private addresses
|
|
359
|
+
* are allowed).
|
|
360
|
+
*/
|
|
361
|
+
readonly openHop?: (url: string) => Promise<PublicFetchSession>;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* The outcome of a single hop of {@link createDocumentLoader}, decided while
|
|
366
|
+
* its fetch session is open.
|
|
367
|
+
*/
|
|
368
|
+
type HopOutcome = ParsedRemoteDocument | { readonly location: string };
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* The implementation of {@link getDocumentLoader}, with injectable
|
|
372
|
+
* dependencies. This is not exported from any entry point.
|
|
373
|
+
* @param options Options for the document loader.
|
|
374
|
+
* @param deps The dependencies.
|
|
375
|
+
* @returns The document loader.
|
|
376
|
+
*/
|
|
377
|
+
export function createDocumentLoader(
|
|
292
378
|
{ allowPrivateAddress, skipPreloadedContexts, userAgent }:
|
|
293
379
|
GetDocumentLoaderOptions = {},
|
|
380
|
+
deps: DocumentLoaderDependencies = {},
|
|
294
381
|
): DocumentLoader {
|
|
295
382
|
const tracerProvider = trace.getTracerProvider();
|
|
296
383
|
const tracer = tracerProvider.getTracer(metadata.name, metadata.version);
|
|
297
384
|
|
|
385
|
+
async function openHop(
|
|
386
|
+
url: string,
|
|
387
|
+
signal?: AbortSignal,
|
|
388
|
+
): Promise<PublicFetchSession> {
|
|
389
|
+
try {
|
|
390
|
+
if (deps.openHop != null) return await deps.openHop(url);
|
|
391
|
+
return allowPrivateAddress
|
|
392
|
+
? await openDirectFetch(url)
|
|
393
|
+
: await openPublicFetch(url, { signal });
|
|
394
|
+
} catch (error) {
|
|
395
|
+
if (error instanceof UrlError) {
|
|
396
|
+
if (error.reason === "dns") {
|
|
397
|
+
logger.debug("DNS lookup failed for {url}", { url, error });
|
|
398
|
+
} else {
|
|
399
|
+
logger.error("Disallowed private URL: {url}", { url, error });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async function fetchHop(
|
|
407
|
+
session: PublicFetchSession,
|
|
408
|
+
url: string,
|
|
409
|
+
span: Span,
|
|
410
|
+
options?: DocumentLoaderOptions,
|
|
411
|
+
): Promise<HopOutcome> {
|
|
412
|
+
try {
|
|
413
|
+
const request = createActivityPubRequest(url, { userAgent });
|
|
414
|
+
logRequest(logger, request);
|
|
415
|
+
const response = await session.fetch(request, {
|
|
416
|
+
// Since Bun has a bug that ignores the `Request.redirect` option,
|
|
417
|
+
// to work around it we specify `redirect: "manual"` here too:
|
|
418
|
+
// https://github.com/oven-sh/bun/issues/10754
|
|
419
|
+
redirect: "manual",
|
|
420
|
+
signal: options?.signal,
|
|
421
|
+
});
|
|
422
|
+
span.setAttribute("http.response.status_code", response.status);
|
|
423
|
+
|
|
424
|
+
// Follow redirects manually to get the final URL:
|
|
425
|
+
if (
|
|
426
|
+
response.status >= 300 && response.status < 400 &&
|
|
427
|
+
response.headers.has("Location")
|
|
428
|
+
) {
|
|
429
|
+
const location = response.headers.get("Location")!;
|
|
430
|
+
cancelResponseBody(response, url);
|
|
431
|
+
return { location };
|
|
432
|
+
}
|
|
433
|
+
return await parseRemoteDocument(url, response);
|
|
434
|
+
} finally {
|
|
435
|
+
await session.close();
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
298
439
|
async function load(
|
|
299
440
|
url: string,
|
|
300
441
|
options?: DocumentLoaderOptions,
|
|
@@ -320,26 +461,9 @@ export function getDocumentLoader(
|
|
|
320
461
|
documentUrl: currentUrl,
|
|
321
462
|
};
|
|
322
463
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
} catch (error) {
|
|
327
|
-
if (error instanceof UrlError) {
|
|
328
|
-
if (error.reason === "dns") {
|
|
329
|
-
logger.debug("DNS lookup failed for {url}", {
|
|
330
|
-
url: currentUrl,
|
|
331
|
-
error,
|
|
332
|
-
});
|
|
333
|
-
} else {
|
|
334
|
-
logger.error("Disallowed private URL: {url}", {
|
|
335
|
-
url: currentUrl,
|
|
336
|
-
error,
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
throw error;
|
|
341
|
-
}
|
|
342
|
-
}
|
|
464
|
+
// Opening the session validates the URL; the session is closed by
|
|
465
|
+
// fetchHop() before the next hop is opened:
|
|
466
|
+
const session = await openHop(currentUrl, options?.signal);
|
|
343
467
|
visited.add(currentUrl);
|
|
344
468
|
|
|
345
469
|
return await tracer.startActiveSpan(
|
|
@@ -352,22 +476,8 @@ export function getDocumentLoader(
|
|
|
352
476
|
},
|
|
353
477
|
async (span) => {
|
|
354
478
|
try {
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
const response = await fetch(request, {
|
|
358
|
-
// Since Bun has a bug that ignores the `Request.redirect` option,
|
|
359
|
-
// to work around it we specify `redirect: "manual"` here too:
|
|
360
|
-
// https://github.com/oven-sh/bun/issues/10754
|
|
361
|
-
redirect: "manual",
|
|
362
|
-
signal: options?.signal,
|
|
363
|
-
});
|
|
364
|
-
span.setAttribute("http.response.status_code", response.status);
|
|
365
|
-
|
|
366
|
-
// Follow redirects manually to get the final URL:
|
|
367
|
-
if (
|
|
368
|
-
response.status >= 300 && response.status < 400 &&
|
|
369
|
-
response.headers.has("Location")
|
|
370
|
-
) {
|
|
479
|
+
const outcome = await fetchHop(session, currentUrl, span, options);
|
|
480
|
+
if ("location" in outcome) {
|
|
371
481
|
if (redirected >= DEFAULT_MAX_REDIRECTION) {
|
|
372
482
|
logger.error(
|
|
373
483
|
"Too many redirections ({redirections}) while fetching document.",
|
|
@@ -378,10 +488,7 @@ export function getDocumentLoader(
|
|
|
378
488
|
`Too many redirections (${redirected + 1})`,
|
|
379
489
|
);
|
|
380
490
|
}
|
|
381
|
-
const redirectUrl = new URL(
|
|
382
|
-
response.headers.get("Location")!,
|
|
383
|
-
response.url === "" ? currentUrl : response.url,
|
|
384
|
-
).href;
|
|
491
|
+
const redirectUrl = new URL(outcome.location, currentUrl).href;
|
|
385
492
|
span.setAttribute("http.redirect.url", redirectUrl);
|
|
386
493
|
if (visited.has(redirectUrl)) {
|
|
387
494
|
logger.error(
|
|
@@ -397,26 +504,26 @@ export function getDocumentLoader(
|
|
|
397
504
|
return await load(redirectUrl, options, redirected + 1, visited);
|
|
398
505
|
}
|
|
399
506
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
507
|
+
let result: RemoteDocument;
|
|
508
|
+
if ("alternate" in outcome) {
|
|
509
|
+
const alternateUrl = outcome.alternate;
|
|
510
|
+
options?.signal?.throwIfAborted();
|
|
511
|
+
if (redirected >= DEFAULT_MAX_REDIRECTION) {
|
|
512
|
+
throw new FetchError(
|
|
513
|
+
currentUrl,
|
|
514
|
+
`Too many redirections (${redirected + 1})`,
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
if (visited.has(alternateUrl)) {
|
|
518
|
+
throw new FetchError(
|
|
519
|
+
currentUrl,
|
|
520
|
+
`Redirect loop detected: ${alternateUrl}`,
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
result = await load(alternateUrl, options, redirected + 1, visited);
|
|
524
|
+
} else {
|
|
525
|
+
result = outcome.document;
|
|
526
|
+
}
|
|
420
527
|
span.setAttribute("docloader.document_url", result.documentUrl);
|
|
421
528
|
if (result.contextUrl != null) {
|
|
422
529
|
span.setAttribute("docloader.context_url", result.contextUrl);
|
package/src/internal.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal APIs shared among Fedify packages. They are not part of the public
|
|
3
|
+
* API and have no semver guarantees; do not use them outside Fedify.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
export {
|
|
8
|
+
openDirectFetch,
|
|
9
|
+
openPublicFetch,
|
|
10
|
+
type PublicFetchOptions,
|
|
11
|
+
type PublicFetchSession,
|
|
12
|
+
withPublicFetch,
|
|
13
|
+
} from "./public-fetch.ts";
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { test } from "@fedify/fixture";
|
|
2
|
+
import { deepStrictEqual, ok, strictEqual, throws } from "node:assert";
|
|
3
|
+
import type { LookupAddress } from "node:dns";
|
|
4
|
+
import {
|
|
5
|
+
issuePinGrant,
|
|
6
|
+
type PinGrant,
|
|
7
|
+
redeemPinGrant,
|
|
8
|
+
revokePinGrant,
|
|
9
|
+
} from "./pin-grant.ts";
|
|
10
|
+
|
|
11
|
+
const addresses: readonly LookupAddress[] = [
|
|
12
|
+
{ address: "8.8.8.8", family: 4 },
|
|
13
|
+
{ address: "2001:4860:4860::8888", family: 6 },
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
test("redeemPinGrant() returns what the grant was issued for", () => {
|
|
17
|
+
const url = new URL("https://pinned-host.invalid:8443/path?query");
|
|
18
|
+
const input = addresses.map((address) => ({ ...address }));
|
|
19
|
+
const grant = issuePinGrant(url, input);
|
|
20
|
+
const record = redeemPinGrant(grant, url);
|
|
21
|
+
deepStrictEqual(record.origin, "https://pinned-host.invalid:8443");
|
|
22
|
+
deepStrictEqual(record.hostname, "pinned-host.invalid");
|
|
23
|
+
deepStrictEqual(record.addresses, addresses);
|
|
24
|
+
|
|
25
|
+
// The record holds a frozen copy of the addresses:
|
|
26
|
+
input[0].address = "127.0.0.1";
|
|
27
|
+
input.push({ address: "10.0.0.1", family: 4 });
|
|
28
|
+
deepStrictEqual(redeemPinGrant(grant, url).addresses, addresses);
|
|
29
|
+
ok(Object.isFrozen(record));
|
|
30
|
+
ok(Object.isFrozen(record.addresses));
|
|
31
|
+
ok(Object.isFrozen(record.addresses[0]));
|
|
32
|
+
|
|
33
|
+
// Other paths and queries of the same origin are accepted:
|
|
34
|
+
strictEqual(
|
|
35
|
+
redeemPinGrant(grant, new URL("https://pinned-host.invalid:8443/other")),
|
|
36
|
+
record,
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("redeemPinGrant() strips brackets from IPv6 hostnames", () => {
|
|
41
|
+
const url = new URL("http://[2001:4860:4860::8888]/");
|
|
42
|
+
const grant = issuePinGrant(url, [addresses[1]]);
|
|
43
|
+
const record = redeemPinGrant(grant, url);
|
|
44
|
+
deepStrictEqual(record.hostname, "2001:4860:4860::8888");
|
|
45
|
+
deepStrictEqual(record.origin, "http://[2001:4860:4860::8888]");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("redeemPinGrant() rejects grants not issued by issuePinGrant()", () => {
|
|
49
|
+
const url = new URL("https://pinned-host.invalid/");
|
|
50
|
+
const issued = issuePinGrant(url, addresses);
|
|
51
|
+
const forgeries: Record<string, unknown> = {
|
|
52
|
+
"object literal": {},
|
|
53
|
+
"null-prototype object": Object.create(null),
|
|
54
|
+
"frozen null-prototype object": Object.freeze(Object.create(null)),
|
|
55
|
+
"copy of a grant": { ...issued },
|
|
56
|
+
"structured clone of a grant": structuredClone(issued),
|
|
57
|
+
"object inheriting from a grant": Object.create(issued),
|
|
58
|
+
"null": null,
|
|
59
|
+
"undefined": undefined,
|
|
60
|
+
"string": "grant",
|
|
61
|
+
};
|
|
62
|
+
for (const [name, forgery] of Object.entries(forgeries)) {
|
|
63
|
+
throws(
|
|
64
|
+
() => redeemPinGrant(forgery as PinGrant, url),
|
|
65
|
+
TypeError,
|
|
66
|
+
name,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
// The issued grant itself still works:
|
|
70
|
+
ok(redeemPinGrant(issued, url));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("redeemPinGrant() rejects URLs of other origins", () => {
|
|
74
|
+
const grant = issuePinGrant(
|
|
75
|
+
new URL("https://pinned-host.invalid/"),
|
|
76
|
+
addresses,
|
|
77
|
+
);
|
|
78
|
+
for (
|
|
79
|
+
const url of [
|
|
80
|
+
"http://pinned-host.invalid/",
|
|
81
|
+
"https://other-host.invalid/",
|
|
82
|
+
"https://sub.pinned-host.invalid/",
|
|
83
|
+
"https://pinned-host.invalid:8443/",
|
|
84
|
+
"https://8.8.8.8/",
|
|
85
|
+
]
|
|
86
|
+
) {
|
|
87
|
+
throws(() => redeemPinGrant(grant, new URL(url)), TypeError, url);
|
|
88
|
+
}
|
|
89
|
+
// The default port is the same origin:
|
|
90
|
+
ok(redeemPinGrant(grant, new URL("https://pinned-host.invalid:443/")));
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("redeemPinGrant() rejects revoked grants", () => {
|
|
94
|
+
const url = new URL("https://pinned-host.invalid/");
|
|
95
|
+
const grant = issuePinGrant(url, addresses);
|
|
96
|
+
const other = issuePinGrant(url, addresses);
|
|
97
|
+
revokePinGrant(grant);
|
|
98
|
+
throws(() => redeemPinGrant(grant, url), TypeError);
|
|
99
|
+
// Revoking is idempotent, and does not affect other grants:
|
|
100
|
+
revokePinGrant(grant);
|
|
101
|
+
throws(() => redeemPinGrant(grant, url), TypeError);
|
|
102
|
+
ok(redeemPinGrant(other, url));
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("revokePinGrant() ignores unknown objects", () => {
|
|
106
|
+
revokePinGrant({} as PinGrant);
|
|
107
|
+
revokePinGrant(Object.create(null) as PinGrant);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("issuePinGrant() returns a distinct frozen object every time", () => {
|
|
111
|
+
const url = new URL("https://pinned-host.invalid/");
|
|
112
|
+
const a = issuePinGrant(url, addresses);
|
|
113
|
+
const b = issuePinGrant(url, addresses);
|
|
114
|
+
ok(a !== b);
|
|
115
|
+
ok(Object.isFrozen(a));
|
|
116
|
+
strictEqual(Object.getPrototypeOf(a), null);
|
|
117
|
+
deepStrictEqual(Reflect.ownKeys(a), []);
|
|
118
|
+
});
|
package/src/pin-grant.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unforgeable capabilities that hand the addresses validated by
|
|
3
|
+
* `openPublicFetch()` over to a connection pinner.
|
|
4
|
+
*
|
|
5
|
+
* This module is not exported from any entry point of the package.
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ResolvedAddress } from "./url.ts";
|
|
10
|
+
|
|
11
|
+
declare const brand: unique symbol;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* An opaque token that stands for a set of validated addresses of an origin.
|
|
15
|
+
* Only objects returned by {@link issuePinGrant} are accepted by
|
|
16
|
+
* {@link redeemPinGrant}; objects of the same shape are not.
|
|
17
|
+
*/
|
|
18
|
+
export type PinGrant = { readonly [brand]: never };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* What a {@link PinGrant} stands for.
|
|
22
|
+
*/
|
|
23
|
+
export interface PinGrantRecord {
|
|
24
|
+
/** The origin (scheme, host, and port) the grant was issued for. */
|
|
25
|
+
readonly origin: string;
|
|
26
|
+
/** The hostname the grant was issued for, without IPv6 brackets. */
|
|
27
|
+
readonly hostname: string;
|
|
28
|
+
/** The validated addresses, in lookup order. */
|
|
29
|
+
readonly addresses: readonly ResolvedAddress[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface GrantState {
|
|
33
|
+
readonly record: PinGrantRecord;
|
|
34
|
+
revoked: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const grants = new WeakMap<PinGrant, GrantState>();
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Issues a grant for the given URL's origin and addresses. This does not
|
|
41
|
+
* validate the addresses; callers validate them before issuing, and pinners
|
|
42
|
+
* validate them again right before connecting.
|
|
43
|
+
* @param url The URL whose origin the grant is bound to.
|
|
44
|
+
* @param addresses The addresses to connect to.
|
|
45
|
+
* @returns A new grant.
|
|
46
|
+
*/
|
|
47
|
+
export function issuePinGrant(
|
|
48
|
+
url: URL,
|
|
49
|
+
addresses: readonly ResolvedAddress[],
|
|
50
|
+
): PinGrant {
|
|
51
|
+
const grant = Object.freeze(Object.create(null)) as PinGrant;
|
|
52
|
+
let hostname = url.hostname;
|
|
53
|
+
if (hostname.startsWith("[") && hostname.endsWith("]")) {
|
|
54
|
+
hostname = hostname.slice(1, -1);
|
|
55
|
+
}
|
|
56
|
+
const record: PinGrantRecord = Object.freeze({
|
|
57
|
+
origin: url.origin,
|
|
58
|
+
hostname,
|
|
59
|
+
addresses: Object.freeze(
|
|
60
|
+
addresses.map(({ address, family }) =>
|
|
61
|
+
Object.freeze({ address, family })
|
|
62
|
+
),
|
|
63
|
+
),
|
|
64
|
+
});
|
|
65
|
+
grants.set(grant, { record, revoked: false });
|
|
66
|
+
return grant;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Checks that the given grant was issued by {@link issuePinGrant}, has not
|
|
71
|
+
* been revoked, and was issued for the origin of the given URL.
|
|
72
|
+
* @param grant The grant to redeem.
|
|
73
|
+
* @param url The URL to connect to.
|
|
74
|
+
* @returns What the grant stands for.
|
|
75
|
+
* @throws {TypeError} If the grant cannot be used for the URL.
|
|
76
|
+
*/
|
|
77
|
+
export function redeemPinGrant(grant: PinGrant, url: URL): PinGrantRecord {
|
|
78
|
+
const state = typeof grant === "object" && grant !== null
|
|
79
|
+
? grants.get(grant)
|
|
80
|
+
: undefined;
|
|
81
|
+
if (state == null) throw new TypeError("Invalid pin grant.");
|
|
82
|
+
if (state.revoked) throw new TypeError("The pin grant has been revoked.");
|
|
83
|
+
if (url.origin !== state.record.origin) {
|
|
84
|
+
throw new TypeError(
|
|
85
|
+
`The pin grant for ${state.record.origin} cannot be used for ` +
|
|
86
|
+
`${url.origin}.`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
return state.record;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Revokes the given grant so that it can no longer be redeemed.
|
|
94
|
+
* @param grant The grant to revoke.
|
|
95
|
+
*/
|
|
96
|
+
export function revokePinGrant(grant: PinGrant): void {
|
|
97
|
+
const state = grants.get(grant);
|
|
98
|
+
if (state != null) state.revoked = true;
|
|
99
|
+
}
|