@dasl/fisl 0.0.0-stage → 0.1.0

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 (41) hide show
  1. package/CLI.md +111 -0
  2. package/README.md +108 -2
  3. package/dist/cli.d.ts +13 -0
  4. package/dist/cli.js +315 -0
  5. package/dist/mod.d.ts +21 -0
  6. package/dist/mod.js +21 -0
  7. package/dist/src/atproto.d.ts +67 -0
  8. package/dist/src/atproto.js +163 -0
  9. package/dist/src/cid-core.d.ts +9 -0
  10. package/dist/src/cid-core.js +39 -0
  11. package/dist/src/cid.d.ts +18 -0
  12. package/dist/src/cid.js +40 -0
  13. package/dist/src/fetch.d.ts +27 -0
  14. package/dist/src/fetch.js +328 -0
  15. package/dist/src/fisl/client.d.ts +17 -0
  16. package/dist/src/fisl/client.js +124 -0
  17. package/dist/src/fisl/server.d.ts +19 -0
  18. package/dist/src/fisl/server.js +69 -0
  19. package/dist/src/index/ingest.d.ts +8 -0
  20. package/dist/src/index/ingest.js +22 -0
  21. package/dist/src/index/jetstream.d.ts +13 -0
  22. package/dist/src/index/jetstream.js +88 -0
  23. package/dist/src/index/pds.d.ts +14 -0
  24. package/dist/src/index/pds.js +42 -0
  25. package/dist/src/index/sqlite.d.ts +16 -0
  26. package/dist/src/index/sqlite.js +105 -0
  27. package/dist/src/index/store.d.ts +37 -0
  28. package/dist/src/index/store.js +59 -0
  29. package/dist/src/index/verify.d.ts +19 -0
  30. package/dist/src/index/verify.js +61 -0
  31. package/dist/src/publish.d.ts +11 -0
  32. package/dist/src/publish.js +24 -0
  33. package/dist/src/rasl/server.d.ts +24 -0
  34. package/dist/src/rasl/server.js +110 -0
  35. package/dist/src/record-core.d.ts +8 -0
  36. package/dist/src/record-core.js +58 -0
  37. package/dist/src/record.d.ts +35 -0
  38. package/dist/src/record.js +47 -0
  39. package/dist/src/serve.d.ts +12 -0
  40. package/dist/src/serve.js +69 -0
  41. package/package.json +50 -4
@@ -0,0 +1,163 @@
1
+ // A small AT Protocol client: identity resolution, app-password sessions
2
+ // and the repo calls that dev.fisl.at needs. Uses plain fetch.
3
+ import { NSID } from "./record.js";
4
+ export const PLC_DIRECTORY = "https://plc.directory";
5
+ export const APPVIEW = "https://public.api.bsky.app";
6
+ export class XrpcError extends Error {
7
+ status;
8
+ error;
9
+ constructor(status, error, message) {
10
+ super(message);
11
+ this.status = status;
12
+ this.error = error;
13
+ }
14
+ }
15
+ /** Call an XRPC method. Queries use GET with params; procedures POST a JSON body. */
16
+ export async function xrpc(service, method, opts = {}) {
17
+ const url = new URL(`/xrpc/${method}`, service);
18
+ for (const [k, v] of Object.entries(opts.params ?? {})) {
19
+ if (v !== undefined)
20
+ url.searchParams.set(k, String(v));
21
+ }
22
+ const headers = {};
23
+ if (opts.token)
24
+ headers.authorization = `Bearer ${opts.token}`;
25
+ if (opts.body !== undefined)
26
+ headers["content-type"] = "application/json";
27
+ const res = await fetch(url, {
28
+ signal: opts.signal,
29
+ method: opts.body === undefined ? "GET" : "POST",
30
+ headers,
31
+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
32
+ });
33
+ const type = res.headers.get("content-type") ?? "";
34
+ if (!res.ok) {
35
+ const err = type.includes("json") ? await res.json() : {};
36
+ throw new XrpcError(res.status, err.error, `${method}: ${err.message ?? err.error ?? res.statusText}`);
37
+ }
38
+ if (type.includes("json"))
39
+ return await res.json();
40
+ return new Uint8Array(await res.arrayBuffer());
41
+ }
42
+ /** Resolve a handle to a DID: DNS, then .well-known, then the Bluesky AppView. */
43
+ export async function resolveHandle(handle, signal) {
44
+ handle = handle.replace(/^@/, "").toLowerCase();
45
+ try {
46
+ const { resolveTxt } = await import("node:dns/promises");
47
+ const txt = await resolveTxt(`_atproto.${handle}`);
48
+ // A TXT record can be split into chunks.
49
+ const did = txt.map((t) => t.join(""))
50
+ .find((t) => t.startsWith("did="))?.slice(4);
51
+ if (did)
52
+ return did;
53
+ }
54
+ catch { /* fall through */ }
55
+ try {
56
+ const res = await fetch(`https://${handle}/.well-known/atproto-did`, {
57
+ signal,
58
+ });
59
+ const did = (await res.text()).trim();
60
+ if (res.ok && did.startsWith("did:"))
61
+ return did;
62
+ }
63
+ catch { /* fall through */ }
64
+ const { did } = await xrpc(APPVIEW, "com.atproto.identity.resolveHandle", { params: { handle }, signal });
65
+ return did;
66
+ }
67
+ export async function resolveDid(did, signal) {
68
+ let url;
69
+ if (did.startsWith("did:plc:"))
70
+ url = `${PLC_DIRECTORY}/${did}`;
71
+ else if (did.startsWith("did:web:")) {
72
+ url = `https://${decodeURIComponent(did.slice(8))}/.well-known/did.json`;
73
+ }
74
+ else
75
+ throw new Error(`Unsupported DID method: ${did}`);
76
+ const res = await fetch(url, { signal });
77
+ if (!res.ok)
78
+ throw new Error(`Could not resolve ${did}: ${res.status}`);
79
+ return await res.json();
80
+ }
81
+ /** Resolve a handle or DID to its DID, PDS and signing key. */
82
+ export async function resolveIdentity(handleOrDid, signal) {
83
+ const did = handleOrDid.startsWith("did:")
84
+ ? handleOrDid
85
+ : await resolveHandle(handleOrDid, signal);
86
+ const doc = await resolveDid(did, signal);
87
+ const pds = doc.service?.find((s) => s.id.endsWith("#atproto_pds") && s.type === "AtprotoPersonalDataServer")?.serviceEndpoint;
88
+ if (!pds)
89
+ throw new Error(`${did} has no PDS`);
90
+ const key = doc.verificationMethod?.find((v) => v.id.endsWith("#atproto"))
91
+ ?.publicKeyMultibase;
92
+ return { did, pds, signingKey: key ? `did:key:${key}` : undefined };
93
+ }
94
+ /** Log in with a handle (or DID) and an app password. */
95
+ export async function login(identifier, password) {
96
+ const id = await resolveIdentity(identifier);
97
+ const res = await xrpc(id.pds, "com.atproto.server.createSession", { body: { identifier: id.did, password } });
98
+ return { ...id, accessJwt: res.accessJwt };
99
+ }
100
+ /** Create or replace the record for a CID. */
101
+ export function putRecord(s, cid, record) {
102
+ return xrpc(s.pds, "com.atproto.repo.putRecord", {
103
+ token: s.accessJwt,
104
+ // The PDS cannot resolve the dev.fisl.at Lexicon, so it cannot validate.
105
+ body: {
106
+ repo: s.did,
107
+ collection: NSID,
108
+ rkey: cid,
109
+ record: { $type: NSID, ...record },
110
+ validate: false,
111
+ },
112
+ });
113
+ }
114
+ export function deleteRecord(s, cid) {
115
+ return xrpc(s.pds, "com.atproto.repo.deleteRecord", {
116
+ token: s.accessJwt,
117
+ body: { repo: s.did, collection: NSID, rkey: cid },
118
+ });
119
+ }
120
+ /**
121
+ * Create or replace many records in one commit. At most 200 per call.
122
+ * applyWrites has no upsert, so pass the CIDs that already have a record.
123
+ */
124
+ export function putRecords(s, records, existing = new Set()) {
125
+ return xrpc(s.pds, "com.atproto.repo.applyWrites", {
126
+ token: s.accessJwt,
127
+ body: {
128
+ repo: s.did,
129
+ validate: false,
130
+ writes: records.map(({ cid, record }) => ({
131
+ $type: `com.atproto.repo.applyWrites#${existing.has(cid) ? "update" : "create"}`,
132
+ collection: NSID,
133
+ rkey: cid,
134
+ value: { $type: NSID, ...record },
135
+ })),
136
+ },
137
+ });
138
+ }
139
+ /** Read one record from a repo. Returns null if there is none. */
140
+ export async function getRecord(id, cid, signal) {
141
+ try {
142
+ const res = await xrpc(id.pds, "com.atproto.repo.getRecord", { params: { repo: id.did, collection: NSID, rkey: cid }, signal });
143
+ return res.value;
144
+ }
145
+ catch (e) {
146
+ if (e instanceof XrpcError && e.error === "RecordNotFound")
147
+ return null;
148
+ throw e;
149
+ }
150
+ }
151
+ /** List every dev.fisl.at record in a repo. */
152
+ export async function* listRecords(id) {
153
+ let cursor;
154
+ do {
155
+ const res = await xrpc(id.pds, "com.atproto.repo.listRecords", {
156
+ params: { repo: id.did, collection: NSID, limit: 100, cursor },
157
+ });
158
+ for (const r of res.records) {
159
+ yield { cid: r.uri.split("/").pop(), record: r.value };
160
+ }
161
+ cursor = res.records.length ? res.cursor : undefined;
162
+ } while (cursor);
163
+ }
@@ -0,0 +1,9 @@
1
+ import type { Cid } from "./cid.ts";
2
+
3
+ export function base32Encode(bytes: Uint8Array): string;
4
+ export function base32Decode(s: string): Uint8Array | null;
5
+ export function parseCid(
6
+ s: unknown,
7
+ options?: { bdasl?: boolean },
8
+ ): Cid | null;
9
+ export function isCid(s: unknown): boolean;
@@ -0,0 +1,39 @@
1
+ import { base32 } from "multiformats/bases/base32";
2
+ import { CID } from "multiformats/cid";
3
+
4
+ const CODEC_RAW = 0x55,
5
+ CODEC_DRISL = 0x71,
6
+ HASH_SHA256 = 0x12,
7
+ HASH_BLAKE3 = 0x1e;
8
+
9
+ export function base32Encode(bytes) {
10
+ return base32.encode(bytes).slice(1);
11
+ }
12
+
13
+ export function base32Decode(s) {
14
+ try {
15
+ const bytes = base32.decode("b" + s);
16
+ return base32Encode(bytes) === s ? bytes : null;
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
22
+ /** Parse a string CID. Returns null if it is not a DASL (or, with `bdasl`, BDASL) CID. */
23
+ export function parseCid(s, { bdasl = true } = {}) {
24
+ if (typeof s !== "string" || s.length !== 59 || s[0] !== "b") return null;
25
+ try {
26
+ const cid = CID.parse(s, base32);
27
+ const { code: hash, digest, size } = cid.multihash;
28
+ if (cid.version !== 1 || size !== 32) return null;
29
+ if (cid.code !== CODEC_RAW && cid.code !== CODEC_DRISL) return null;
30
+ if (hash !== HASH_SHA256 && !(bdasl && hash === HASH_BLAKE3)) return null;
31
+ return { codec: cid.code, hash, digest, string: s };
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ export function isCid(s) {
38
+ return parseCid(s) !== null;
39
+ }
@@ -0,0 +1,18 @@
1
+ export declare const CODEC_RAW = 85;
2
+ export declare const CODEC_DRISL = 113;
3
+ export declare const HASH_SHA256 = 18;
4
+ export declare const HASH_BLAKE3 = 30;
5
+ export interface Cid {
6
+ codec: number;
7
+ hash: number;
8
+ digest: Uint8Array;
9
+ string: string;
10
+ }
11
+ export { base32Decode, base32Encode, isCid, parseCid } from "./cid-core.js";
12
+ export declare function cidFromDigest(digest: Uint8Array, codec?: number, hash?: number): string;
13
+ /** The DASL CID of raw bytes, hashed with SHA-256. */
14
+ export declare function cidForBytes(bytes: Uint8Array): Promise<string>;
15
+ /** The DASL CID of a file. Streams the file, so large files are fine. */
16
+ export declare function cidForFile(path: string): Promise<string>;
17
+ /** Check that bytes match a CID, using the CID's hash function. */
18
+ export declare function verifyBytes(cid: Cid, bytes: Uint8Array): Promise<boolean>;
@@ -0,0 +1,40 @@
1
+ // DASL and BDASL CIDs: https://dasl.ing/cid.html, https://dasl.ing/bdasl.html
2
+ //
3
+ // A CID is 36 bytes: version 0x01, codec, hash type, hash length 0x20 and a
4
+ // 32-byte digest. Its only string form is "b" + lowercase base32, no padding.
5
+ import { blake3 } from "@noble/hashes/blake3.js";
6
+ import { sha256 } from "@noble/hashes/sha2.js";
7
+ export const CODEC_RAW = 0x55;
8
+ export const CODEC_DRISL = 0x71;
9
+ export const HASH_SHA256 = 0x12;
10
+ export const HASH_BLAKE3 = 0x1e;
11
+ // @ts-types="./cid-core.d.ts"
12
+ export { base32Decode, base32Encode, isCid, parseCid } from "./cid-core.js";
13
+ // @ts-types="./cid-core.d.ts"
14
+ import { base32Encode } from "./cid-core.js";
15
+ export function cidFromDigest(digest, codec = CODEC_RAW, hash = HASH_SHA256) {
16
+ const bytes = new Uint8Array(36);
17
+ bytes.set([0x01, codec, hash, 0x20]);
18
+ bytes.set(digest, 4);
19
+ return "b" + base32Encode(bytes);
20
+ }
21
+ /** The DASL CID of raw bytes, hashed with SHA-256. */
22
+ export async function cidForBytes(bytes) {
23
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
24
+ return cidFromDigest(digest);
25
+ }
26
+ /** The DASL CID of a file. Streams the file, so large files are fine. */
27
+ export async function cidForFile(path) {
28
+ const h = sha256.create();
29
+ const { createReadStream } = await import("node:fs");
30
+ for await (const chunk of createReadStream(path))
31
+ h.update(chunk);
32
+ return cidFromDigest(h.digest());
33
+ }
34
+ /** Check that bytes match a CID, using the CID's hash function. */
35
+ export async function verifyBytes(cid, bytes) {
36
+ const digest = cid.hash === HASH_BLAKE3 ? blake3(bytes) : new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
37
+ if (digest.length !== cid.digest.length)
38
+ return false;
39
+ return digest.every((b, i) => b === cid.digest[i]);
40
+ }
@@ -0,0 +1,27 @@
1
+ import { type ResolveOptions } from "./fisl/client.ts";
2
+ export interface FetchOptions extends ResolveOptions {
3
+ /** Allow plain http URLs. Off by default. */
4
+ allowHttp?: boolean;
5
+ signal?: AbortSignal;
6
+ /** Deadline per download, including DNS and response body. Default 30 seconds. */
7
+ downloadTimeoutMs?: number;
8
+ /** Maximum simultaneous mirror downloads. Default 3. */
9
+ concurrency?: number;
10
+ /** Allow hosts in private or loopback address space. Off by default. */
11
+ allowPrivate?: boolean;
12
+ /** Maximum bytes per addr. Default 1 GiB in memory, unlimited for files. */
13
+ maxSize?: number;
14
+ /** Failure counts by publisher or origin. Pass the same map across calls. */
15
+ failures?: Map<string, number>;
16
+ log?: (msg: string) => void;
17
+ }
18
+ export declare class FetchError extends Error {
19
+ }
20
+ /** Turn an addr URL into the https/http URLs to request. Empty if unsupported. */
21
+ export declare function requestUrls(url: string, cid: string, allowHttp?: boolean): URL[];
22
+ export declare function isPrivateIp(ip: string): boolean;
23
+ export declare function fetchCid(cidString: string, opts?: FetchOptions): Promise<Uint8Array>;
24
+ /** Stream a verified download into a temporary file, then atomically rename it.
25
+ * The destination is replaced only after verification. No default size limit.
26
+ */
27
+ export declare function downloadCid(cidString: string, destination: string, opts?: FetchOptions): Promise<void>;
@@ -0,0 +1,328 @@
1
+ // Fetch content by CID: resolve locations with FISL, try each addr, verify.
2
+ // See "Retrieval" and "Security Considerations" in specs/fisl.md.
3
+ import { blake3 } from "@noble/hashes/blake3.js";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { HASH_BLAKE3, parseCid } from "./cid.js";
6
+ import { resolve } from "./fisl/client.js";
7
+ import { RASL_PREFIX } from "./rasl/server.js";
8
+ export class FetchError extends Error {
9
+ }
10
+ /** Turn an addr URL into the https/http URLs to request. Empty if unsupported. */
11
+ export function requestUrls(url, cid, allowHttp = false) {
12
+ const u = new URL(url);
13
+ if (u.protocol === "https:" || (allowHttp && u.protocol === "http:")) {
14
+ return [u];
15
+ }
16
+ // rasl://<cid>/?hint=<host>
17
+ if (u.protocol === "rasl:" && u.hostname === cid) {
18
+ return u.searchParams.getAll("hint").map((h) => new URL(`https://${h}${RASL_PREFIX}${cid}`));
19
+ }
20
+ return [];
21
+ }
22
+ const PRIVATE_V4 = [
23
+ [0x00000000, 8], // 0.0.0.0/8
24
+ [0x0a000000, 8], // 10.0.0.0/8
25
+ [0x64400000, 10], // 100.64.0.0/10
26
+ [0x7f000000, 8], // 127.0.0.0/8
27
+ [0xa9fe0000, 16], // 169.254.0.0/16
28
+ [0xac100000, 12], // 172.16.0.0/12
29
+ [0xc0a80000, 16], // 192.168.0.0/16
30
+ ];
31
+ export function isPrivateIp(ip) {
32
+ ip = ip.replace(/^\[|\]$/g, "").toLowerCase();
33
+ if (ip.includes(":")) {
34
+ const dotted = ip.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
35
+ if (dotted) {
36
+ const octets = dotted.slice(1).map(Number);
37
+ ip = ip.slice(0, dotted.index) +
38
+ ((octets[0] << 8) | octets[1]).toString(16) + ":" +
39
+ ((octets[2] << 8) | octets[3]).toString(16);
40
+ }
41
+ const halves = ip.split("::");
42
+ const left = halves[0] ? halves[0].split(":") : [];
43
+ const right = halves[1] ? halves[1].split(":") : [];
44
+ const words = (halves.length === 2
45
+ ? [...left, ...Array(8 - left.length - right.length).fill("0"), ...right]
46
+ : left).map((w) => parseInt(w, 16));
47
+ if (words.length !== 8 || words.some(Number.isNaN)) {
48
+ return true;
49
+ }
50
+ if (words.slice(0, 5).every((w) => w === 0) && words[5] === 0xffff) {
51
+ return isPrivateIp(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
52
+ }
53
+ return words.every((w) => w === 0) || (words.slice(0, 7).every((w) => w === 0) && words[7] === 1) ||
54
+ (words[0] & 0xfe00) === 0xfc00 ||
55
+ (words[0] & 0xffc0) === 0xfe80;
56
+ }
57
+ const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
58
+ if (!v4)
59
+ return true;
60
+ const octets = v4.slice(1).map(Number);
61
+ if (octets.some((n) => n > 255))
62
+ return true;
63
+ const n = octets.reduce((a, b) => a * 256 + b, 0);
64
+ return PRIVATE_V4.some(([net, bits]) => (n >>> (32 - bits)) === (net >>> (32 - bits)));
65
+ }
66
+ /** Stop waiting for DNS when an attempt is cancelled, even if OS DNS stalls. */
67
+ function abortable(work, signal) {
68
+ if (!signal)
69
+ return work;
70
+ return new Promise((resolve, reject) => {
71
+ const abort = () => reject(signal.reason);
72
+ if (signal.aborted) {
73
+ reject(signal.reason);
74
+ return;
75
+ }
76
+ signal.addEventListener("abort", abort, { once: true });
77
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
78
+ });
79
+ }
80
+ // Node's transport connects to the validated address while retaining the URL
81
+ // hostname for Host, SNI and certificate verification. No second DNS lookup.
82
+ async function pinnedFetch(url, opts) {
83
+ if (opts.allowPrivate) {
84
+ return fetch(url, {
85
+ redirect: "manual",
86
+ credentials: "omit",
87
+ signal: opts.signal,
88
+ });
89
+ }
90
+ const { lookup } = await import("node:dns/promises");
91
+ const { isIP } = await import("node:net");
92
+ const host = url.hostname.replace(/^\[|\]$/g, "");
93
+ const addresses = isIP(host)
94
+ ? [{ address: host, family: isIP(host) }]
95
+ : await abortable(lookup(host, { all: true }), opts.signal);
96
+ opts.signal?.throwIfAborted();
97
+ if (!addresses.length || addresses.some((a) => isPrivateIp(a.address))) {
98
+ throw new FetchError(`${host} is in private address space`);
99
+ }
100
+ const { request } = url.protocol === "https:"
101
+ ? await import("node:https")
102
+ : await import("node:http");
103
+ const { Readable } = await import("node:stream");
104
+ const destination = addresses[0];
105
+ return new Promise((resolve, reject) => {
106
+ const requestOptions = {
107
+ agent: false,
108
+ family: destination.family,
109
+ autoSelectFamily: false,
110
+ signal: opts.signal,
111
+ lookup: (_hostname, _options, callback) => callback(null, destination.address, destination.family),
112
+ };
113
+ const req = request(url, requestOptions, (res) => {
114
+ const headers = new Headers();
115
+ for (let i = 0; i < res.rawHeaders.length; i += 2) {
116
+ headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
117
+ }
118
+ if ([204, 205, 304].includes(res.statusCode))
119
+ res.resume();
120
+ resolve(new Response([204, 205, 304].includes(res.statusCode)
121
+ ? null
122
+ : Readable.toWeb(res), {
123
+ status: res.statusCode,
124
+ headers,
125
+ }));
126
+ });
127
+ req.on("error", reject);
128
+ req.end();
129
+ });
130
+ }
131
+ /** GET a URL statelessly, following redirects and checking every hop. */
132
+ async function get(url, opts) {
133
+ for (let hops = 0; hops < 10; hops++) {
134
+ if (url.username || url.password) {
135
+ throw new FetchError("URL credentials are not supported");
136
+ }
137
+ const res = await pinnedFetch(url, opts);
138
+ const location = res.headers.get("location");
139
+ if (res.status >= 300 && res.status < 400 && location) {
140
+ await res.body?.cancel();
141
+ url = new URL(location, url);
142
+ if (url.protocol !== "https:" &&
143
+ !(opts.allowHttp && url.protocol === "http:")) {
144
+ throw new FetchError(`redirect to unsupported URL ${url}`);
145
+ }
146
+ continue;
147
+ }
148
+ return res;
149
+ }
150
+ throw new FetchError(`too many redirects from ${url}`);
151
+ }
152
+ /** Read a response, hashing as it streams. Returns the bytes if they match. */
153
+ async function readVerified(res, cid, maxSize) {
154
+ if (!res.ok || !res.body) {
155
+ await res.body?.cancel();
156
+ throw new FetchError(`${res.status} ${res.statusText}`);
157
+ }
158
+ const hash = cid.hash === HASH_BLAKE3 ? blake3.create() : sha256.create();
159
+ const chunks = [];
160
+ let size = 0;
161
+ for await (const chunk of res.body) {
162
+ size += chunk.length;
163
+ if (size > maxSize) {
164
+ throw new FetchError(`larger than ${maxSize} bytes`);
165
+ }
166
+ hash.update(chunk);
167
+ chunks.push(chunk);
168
+ }
169
+ const digest = hash.digest();
170
+ if (!digest.every((b, i) => b === cid.digest[i])) {
171
+ throw new FetchError("content does not match the CID");
172
+ }
173
+ const out = new Uint8Array(size);
174
+ let offset = 0;
175
+ for (const c of chunks)
176
+ out.set(c, offset), offset += c.length;
177
+ return out;
178
+ }
179
+ const failureKey = (loc, url) => loc.publisher ?? new URL(url).origin;
180
+ /**
181
+ * Fetch and verify the content for a CID. Tries every supported addr of
182
+ * every location, least-failed first, and returns the first verified bytes.
183
+ */
184
+ async function retrieve(cidString, opts, read) {
185
+ const cid = parseCid(cidString);
186
+ if (!cid)
187
+ throw new FetchError(`Not a DASL CID: ${cidString}`);
188
+ const stop = new AbortController();
189
+ const signal = opts.signal
190
+ ? AbortSignal.any([opts.signal, stop.signal])
191
+ : stop.signal;
192
+ const failures = opts.failures ?? new Map();
193
+ const limit = Math.max(1, Math.floor(opts.concurrency ?? 3));
194
+ const active = new Set();
195
+ const queue = [];
196
+ let resolving = true;
197
+ let finished = false;
198
+ return await new Promise((resolveResult, reject) => {
199
+ const pump = () => {
200
+ if (finished)
201
+ return;
202
+ queue.sort((a, b) => (failures.get(a.key) ?? 0) - (failures.get(b.key) ?? 0));
203
+ while (active.size < limit && queue.length) {
204
+ const { key, url } = queue.shift();
205
+ const task = (async () => {
206
+ const attempt = new AbortController();
207
+ try {
208
+ const attemptSignal = AbortSignal.any([
209
+ signal,
210
+ attempt.signal,
211
+ AbortSignal.timeout(opts.downloadTimeoutMs ?? 30_000),
212
+ ]);
213
+ const value = await read(await get(url, { ...opts, signal: attemptSignal }), cid);
214
+ if (!finished) {
215
+ finished = true;
216
+ stop.abort();
217
+ void Promise.allSettled([...active]).then(() => resolveResult(value));
218
+ }
219
+ }
220
+ catch (e) {
221
+ if (!finished) {
222
+ failures.set(key, (failures.get(key) ?? 0) + 1);
223
+ opts.log?.(`failed ${url}: ${e.message}`);
224
+ }
225
+ }
226
+ finally {
227
+ attempt.abort();
228
+ }
229
+ })();
230
+ active.add(task);
231
+ void task.finally(() => {
232
+ active.delete(task);
233
+ pump();
234
+ });
235
+ }
236
+ if (!resolving && !active.size && !queue.length) {
237
+ finished = true;
238
+ stop.abort();
239
+ reject(new FetchError(`Every location failed for ${cidString}`));
240
+ }
241
+ };
242
+ signal.addEventListener("abort", () => {
243
+ if (!finished) {
244
+ finished = true;
245
+ void Promise.allSettled([...active]).then(() => reject(signal.reason));
246
+ }
247
+ }, { once: true });
248
+ if (signal.aborted) {
249
+ finished = true;
250
+ reject(signal.reason);
251
+ return;
252
+ }
253
+ void (async () => {
254
+ try {
255
+ for await (const loc of resolve(cidString, { ...opts, signal })) {
256
+ if (finished)
257
+ break;
258
+ for (const addr of loc.addrs) {
259
+ try {
260
+ for (const url of requestUrls(addr.url, cidString, opts.allowHttp))
261
+ queue.push({ key: failureKey(loc, addr.url), url });
262
+ }
263
+ catch (e) {
264
+ opts.log?.(String(e));
265
+ }
266
+ }
267
+ pump();
268
+ }
269
+ }
270
+ catch (e) {
271
+ opts.log?.(String(e));
272
+ }
273
+ finally {
274
+ resolving = false;
275
+ pump();
276
+ }
277
+ })();
278
+ });
279
+ }
280
+ export function fetchCid(cidString, opts = {}) {
281
+ return retrieve(cidString, opts, (res, cid) => readVerified(res, cid, opts.maxSize ?? 2 ** 30));
282
+ }
283
+ /** Stream a verified download into a temporary file, then atomically rename it.
284
+ * The destination is replaced only after verification. No default size limit.
285
+ */
286
+ export async function downloadCid(cidString, destination, opts = {}) {
287
+ const { dirname, join } = await import("node:path");
288
+ const { open, rename, rm } = await import("node:fs/promises");
289
+ const paths = new Set();
290
+ try {
291
+ const path = await retrieve(cidString, opts, async (res, cid) => {
292
+ if (!res.ok || !res.body) {
293
+ await res.body?.cancel();
294
+ throw new FetchError(`HTTP ${res.status}`);
295
+ }
296
+ const path = join(dirname(destination), `.fisl-${crypto.randomUUID()}`);
297
+ const file = await open(path, "wx");
298
+ paths.add(path);
299
+ const hash = cid.hash === HASH_BLAKE3 ? blake3.create() : sha256.create();
300
+ let size = 0;
301
+ try {
302
+ for await (const chunk of res.body) {
303
+ size += chunk.length;
304
+ if (size > (opts.maxSize ?? Infinity)) {
305
+ throw new FetchError("download exceeds size limit");
306
+ }
307
+ hash.update(chunk);
308
+ await file.write(chunk); // writes the whole chunk
309
+ }
310
+ if (!hash.digest().every((b, i) => b === cid.digest[i])) {
311
+ throw new FetchError("content does not match the CID");
312
+ }
313
+ await file.sync();
314
+ return path;
315
+ }
316
+ finally {
317
+ await file.close();
318
+ }
319
+ });
320
+ await rename(path, destination);
321
+ paths.delete(path);
322
+ }
323
+ finally {
324
+ // Concurrent attempts may still be cancelling. Each uses an independent file.
325
+ for (const path of paths)
326
+ await rm(path, { force: true }).catch(() => { });
327
+ }
328
+ }
@@ -0,0 +1,17 @@
1
+ import { type Location } from "../record.ts";
2
+ /** Stream locations for a CID from a FISL indexer, using the jsonl format. */
3
+ export declare function resolveFromIndexer(cid: string, indexer: string, signal?: AbortSignal): AsyncGenerator<Location>;
4
+ /** Read the location a publisher announced for a CID, straight from its PDS. */
5
+ export declare function resolveFromPds(cid: string, handleOrDid: string, signal?: AbortSignal): Promise<Location | null>;
6
+ export interface ResolveOptions {
7
+ /** FISL indexer base URLs. */
8
+ indexers?: string[];
9
+ signal?: AbortSignal;
10
+ resolutionTimeoutMs?: number;
11
+ resolutionConcurrency?: number;
12
+ /** Publishers to ask directly. */
13
+ publishers?: string[];
14
+ onError?: (source: string, e: Error) => void;
15
+ }
16
+ /** Locations from every indexer and publisher. Failing sources are skipped. */
17
+ export declare function resolve(cid: string, opts: ResolveOptions): AsyncGenerator<Location>;