@dasl/fisl 0.0.0-stage → 0.2.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.
@@ -0,0 +1,389 @@
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
+ const out = [];
19
+ for (const h of u.searchParams.getAll("hint")) {
20
+ if (!h || /[/?#@\s]/.test(h))
21
+ continue;
22
+ try {
23
+ const target = new URL(`https://${h}${RASL_PREFIX}${cid}`);
24
+ if (!target.username && !target.password &&
25
+ target.pathname === `${RASL_PREFIX}${cid}` &&
26
+ !target.search && !target.hash) {
27
+ out.push(target);
28
+ }
29
+ }
30
+ catch { /* skip malformed hint */ }
31
+ }
32
+ return out;
33
+ }
34
+ return [];
35
+ }
36
+ const PRIVATE_V4 = [
37
+ [0x00000000, 8], // 0.0.0.0/8
38
+ [0x0a000000, 8], // 10.0.0.0/8
39
+ [0x64400000, 10], // 100.64.0.0/10
40
+ [0x7f000000, 8], // 127.0.0.0/8
41
+ [0xa9fe0000, 16], // 169.254.0.0/16
42
+ [0xac100000, 12], // 172.16.0.0/12
43
+ [0xc0a80000, 16], // 192.168.0.0/16
44
+ [0xe0000000, 4], // 224.0.0.0/4 (multicast)
45
+ [0xf0000000, 4], // 240.0.0.0/4 (reserved / broadcast)
46
+ ];
47
+ const v4FromWords = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
48
+ export function isPrivateIp(ip) {
49
+ ip = ip.replace(/^\[|\]$/g, "").toLowerCase();
50
+ if (ip.includes(":")) {
51
+ const dotted = ip.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
52
+ if (dotted) {
53
+ const octets = dotted.slice(1).map(Number);
54
+ if (octets.some((n) => n > 255))
55
+ return true;
56
+ ip = ip.slice(0, dotted.index) +
57
+ ((octets[0] << 8) | octets[1]).toString(16) + ":" +
58
+ ((octets[2] << 8) | octets[3]).toString(16);
59
+ }
60
+ const halves = ip.split("::");
61
+ if (halves.length > 2)
62
+ return true;
63
+ const left = halves[0] ? halves[0].split(":") : [];
64
+ const right = halves[1] ? halves[1].split(":") : [];
65
+ const rawWords = halves.length === 2
66
+ ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right]
67
+ : left;
68
+ if (rawWords.length !== 8 ||
69
+ rawWords.some((w) => !/^[0-9a-f]{1,4}$/.test(w))) {
70
+ return true;
71
+ }
72
+ const words = rawWords.map((w) => parseInt(w, 16));
73
+ const zeroPrefix5 = words.slice(0, 5).every((w) => w === 0);
74
+ // IPv4-mapped (::ffff:0:0/96)
75
+ if (zeroPrefix5 && words[5] === 0xffff) {
76
+ return isPrivateIp(v4FromWords(words[6], words[7]));
77
+ }
78
+ // Unspecified (::), loopback (::1), and IPv4-compatible (::/96)
79
+ if (zeroPrefix5 && words[5] === 0) {
80
+ return (words[6] === 0 && words[7] <= 1) ||
81
+ isPrivateIp(v4FromWords(words[6], words[7]));
82
+ }
83
+ // NAT64 well-known prefix (64:ff9b::/96)
84
+ if (words[0] === 0x0064 && words[1] === 0xff9b &&
85
+ words.slice(2, 6).every((w) => w === 0)) {
86
+ return isPrivateIp(v4FromWords(words[6], words[7]));
87
+ }
88
+ // 6to4 (2002::/16)
89
+ if (words[0] === 0x2002 && isPrivateIp(v4FromWords(words[1], words[2]))) {
90
+ return true;
91
+ }
92
+ return (words[0] & 0xfe00) === 0xfc00 || // unique local (fc00::/7)
93
+ (words[0] & 0xffc0) === 0xfe80 || // link-local (fe80::/10)
94
+ (words[0] & 0xff00) === 0xff00; // multicast (ff00::/8)
95
+ }
96
+ const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
97
+ if (!v4)
98
+ return true;
99
+ const octets = v4.slice(1).map(Number);
100
+ if (octets.some((n) => n > 255))
101
+ return true;
102
+ const n = octets.reduce((a, b) => a * 256 + b, 0);
103
+ return PRIVATE_V4.some(([net, bits]) => (n >>> (32 - bits)) === (net >>> (32 - bits)));
104
+ }
105
+ /** Stop waiting for DNS when an attempt is cancelled, even if OS DNS stalls. */
106
+ function abortable(work, signal) {
107
+ if (!signal)
108
+ return work;
109
+ return new Promise((resolve, reject) => {
110
+ const abort = () => reject(signal.reason);
111
+ if (signal.aborted) {
112
+ reject(signal.reason);
113
+ return;
114
+ }
115
+ signal.addEventListener("abort", abort, { once: true });
116
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
117
+ });
118
+ }
119
+ // Node's transport connects to the validated address while retaining the URL
120
+ // hostname for Host, SNI and certificate verification. No second DNS lookup.
121
+ async function pinnedFetch(url, opts) {
122
+ if (opts.allowPrivate) {
123
+ return fetch(url, {
124
+ redirect: "manual",
125
+ credentials: "omit",
126
+ signal: opts.signal,
127
+ });
128
+ }
129
+ const { lookup } = await import("node:dns/promises");
130
+ const { isIP } = await import("node:net");
131
+ const host = url.hostname.replace(/^\[|\]$/g, "");
132
+ const addresses = isIP(host)
133
+ ? [{ address: host, family: isIP(host) }]
134
+ : await abortable(lookup(host, { all: true }), opts.signal);
135
+ opts.signal?.throwIfAborted();
136
+ if (!addresses.length || addresses.some((a) => isPrivateIp(a.address))) {
137
+ throw new FetchError(`${host} is in private address space`);
138
+ }
139
+ const { request } = url.protocol === "https:"
140
+ ? await import("node:https")
141
+ : await import("node:http");
142
+ const { Readable } = await import("node:stream");
143
+ let lastError;
144
+ for (const destination of addresses) {
145
+ opts.signal?.throwIfAborted();
146
+ try {
147
+ return await new Promise((resolve, reject) => {
148
+ const requestOptions = {
149
+ agent: false,
150
+ family: destination.family,
151
+ autoSelectFamily: false,
152
+ signal: opts.signal,
153
+ lookup: (_hostname, _options, callback) => callback(null, destination.address, destination.family),
154
+ };
155
+ const req = request(url, requestOptions, (res) => {
156
+ const headers = new Headers();
157
+ for (let i = 0; i < res.rawHeaders.length; i += 2) {
158
+ headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
159
+ }
160
+ if ([204, 205, 304].includes(res.statusCode))
161
+ res.resume();
162
+ resolve(new Response([204, 205, 304].includes(res.statusCode)
163
+ ? null
164
+ : Readable.toWeb(res), {
165
+ status: res.statusCode,
166
+ statusText: res.statusMessage,
167
+ headers,
168
+ }));
169
+ });
170
+ req.on("error", reject);
171
+ req.end();
172
+ });
173
+ }
174
+ catch (e) {
175
+ if (opts.signal?.aborted)
176
+ throw e;
177
+ lastError = e;
178
+ }
179
+ }
180
+ throw lastError;
181
+ }
182
+ /** GET a URL statelessly, following redirects and checking every hop. */
183
+ async function get(url, opts) {
184
+ for (let hops = 0; hops < 10; hops++) {
185
+ if (url.username || url.password) {
186
+ throw new FetchError("URL credentials are not supported");
187
+ }
188
+ const res = await pinnedFetch(url, opts);
189
+ const location = res.headers.get("location");
190
+ if (res.status >= 300 && res.status < 400 && location) {
191
+ await res.body?.cancel();
192
+ url = new URL(location, url);
193
+ if (url.protocol !== "https:" &&
194
+ !(opts.allowHttp && url.protocol === "http:")) {
195
+ throw new FetchError(`redirect to unsupported URL ${url}`);
196
+ }
197
+ continue;
198
+ }
199
+ return res;
200
+ }
201
+ throw new FetchError(`too many redirects from ${url}`);
202
+ }
203
+ /** Read a response, hashing as it streams. Returns the bytes if they match. */
204
+ async function readVerified(res, cid, maxSize) {
205
+ if (!res.ok || !res.body) {
206
+ await res.body?.cancel();
207
+ throw new FetchError(`${res.status} ${res.statusText}`);
208
+ }
209
+ const hash = cid.hash === HASH_BLAKE3 ? blake3.create() : sha256.create();
210
+ const chunks = [];
211
+ let size = 0;
212
+ for await (const chunk of res.body) {
213
+ size += chunk.length;
214
+ if (size > maxSize) {
215
+ throw new FetchError(`larger than ${maxSize} bytes`);
216
+ }
217
+ hash.update(chunk);
218
+ chunks.push(chunk);
219
+ }
220
+ const digest = hash.digest();
221
+ if (!digest.every((b, i) => b === cid.digest[i])) {
222
+ throw new FetchError("content does not match the CID");
223
+ }
224
+ const out = new Uint8Array(size);
225
+ let offset = 0;
226
+ for (const c of chunks)
227
+ out.set(c, offset), offset += c.length;
228
+ return out;
229
+ }
230
+ const failureKey = (loc, url) => loc.publisher ?? new URL(url).origin;
231
+ /**
232
+ * Fetch and verify the content for a CID. Tries every supported addr of
233
+ * every location, least-failed first, and returns the first verified bytes.
234
+ */
235
+ async function retrieve(cidString, opts, read) {
236
+ const cid = parseCid(cidString);
237
+ if (!cid)
238
+ throw new FetchError(`Not a DASL CID: ${cidString}`);
239
+ const stop = new AbortController();
240
+ const signal = opts.signal
241
+ ? AbortSignal.any([opts.signal, stop.signal])
242
+ : stop.signal;
243
+ const failures = opts.failures ?? new Map();
244
+ const limit = Math.max(1, Math.floor(opts.concurrency ?? 3));
245
+ const active = new Set();
246
+ const queue = [];
247
+ let resolving = true;
248
+ let finished = false;
249
+ return await new Promise((resolveResult, reject) => {
250
+ const pump = () => {
251
+ if (finished)
252
+ return;
253
+ queue.sort((a, b) => (failures.get(a.key) ?? 0) - (failures.get(b.key) ?? 0));
254
+ while (active.size < limit && queue.length) {
255
+ const { key, url } = queue.shift();
256
+ const task = (async () => {
257
+ const attempt = new AbortController();
258
+ try {
259
+ const attemptSignal = AbortSignal.any([
260
+ signal,
261
+ attempt.signal,
262
+ AbortSignal.timeout(opts.downloadTimeoutMs ?? 30_000),
263
+ ]);
264
+ const value = await read(await get(url, { ...opts, signal: attemptSignal }), cid);
265
+ if (!finished) {
266
+ finished = true;
267
+ stop.abort();
268
+ void Promise.allSettled([...active]).then(() => resolveResult(value));
269
+ }
270
+ }
271
+ catch (e) {
272
+ if (!finished) {
273
+ failures.set(key, (failures.get(key) ?? 0) + 1);
274
+ opts.log?.(`failed ${url}: ${e.message}`);
275
+ }
276
+ }
277
+ finally {
278
+ attempt.abort();
279
+ }
280
+ })();
281
+ active.add(task);
282
+ void task.finally(() => {
283
+ active.delete(task);
284
+ pump();
285
+ });
286
+ }
287
+ if (!resolving && !active.size && !queue.length) {
288
+ finished = true;
289
+ stop.abort();
290
+ reject(new FetchError(`Every location failed for ${cidString}`));
291
+ }
292
+ };
293
+ signal.addEventListener("abort", () => {
294
+ if (!finished) {
295
+ finished = true;
296
+ void Promise.allSettled([...active]).then(() => reject(signal.reason));
297
+ }
298
+ }, { once: true });
299
+ if (signal.aborted) {
300
+ finished = true;
301
+ reject(signal.reason);
302
+ return;
303
+ }
304
+ void (async () => {
305
+ try {
306
+ for await (const loc of resolve(cidString, { ...opts, signal })) {
307
+ if (finished)
308
+ break;
309
+ for (const addr of loc.addrs) {
310
+ try {
311
+ for (const url of requestUrls(addr.url, cidString, opts.allowHttp))
312
+ queue.push({ key: failureKey(loc, addr.url), url });
313
+ }
314
+ catch (e) {
315
+ opts.log?.(String(e));
316
+ }
317
+ }
318
+ pump();
319
+ }
320
+ }
321
+ catch (e) {
322
+ opts.log?.(String(e));
323
+ }
324
+ finally {
325
+ resolving = false;
326
+ pump();
327
+ }
328
+ })();
329
+ });
330
+ }
331
+ export function fetchCid(cidString, opts = {}) {
332
+ return retrieve(cidString, opts, (res, cid) => readVerified(res, cid, opts.maxSize ?? 2 ** 30));
333
+ }
334
+ /** Stream a verified download into a temporary file, then atomically rename it.
335
+ * The destination is replaced only after verification. No default size limit.
336
+ */
337
+ export async function downloadCid(cidString, destination, opts = {}) {
338
+ const [{ createHash }, { dirname, join }, { open, rename, rm }] = await Promise.all([
339
+ import("node:crypto"),
340
+ import("node:path"),
341
+ import("node:fs/promises"),
342
+ ]);
343
+ const paths = new Set();
344
+ try {
345
+ const path = await retrieve(cidString, opts, async (res, cid) => {
346
+ if (!res.ok || !res.body) {
347
+ await res.body?.cancel();
348
+ throw new FetchError(`HTTP ${res.status}`);
349
+ }
350
+ const path = join(dirname(destination), `.fisl-${crypto.randomUUID()}`);
351
+ const file = await open(path, "wx");
352
+ paths.add(path);
353
+ const hash = cid.hash === HASH_BLAKE3
354
+ ? blake3.create()
355
+ : createHash("sha256");
356
+ let size = 0;
357
+ try {
358
+ for await (const chunk of res.body) {
359
+ size += chunk.length;
360
+ if (size > (opts.maxSize ?? Infinity)) {
361
+ throw new FetchError("download exceeds size limit");
362
+ }
363
+ hash.update(chunk);
364
+ let offset = 0;
365
+ while (offset < chunk.byteLength) {
366
+ const { bytesWritten } = await file.write(chunk, offset);
367
+ offset += bytesWritten;
368
+ }
369
+ }
370
+ const digest = new Uint8Array(hash.digest());
371
+ if (!digest.every((b, i) => b === cid.digest[i])) {
372
+ throw new FetchError("content does not match the CID");
373
+ }
374
+ await file.sync();
375
+ return path;
376
+ }
377
+ finally {
378
+ await file.close();
379
+ }
380
+ });
381
+ await rename(path, destination);
382
+ paths.delete(path);
383
+ }
384
+ finally {
385
+ // Concurrent attempts may still be cancelling. Each uses an independent file.
386
+ for (const path of paths)
387
+ await rm(path, { force: true }).catch(() => { });
388
+ }
389
+ }
@@ -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>;
@@ -0,0 +1,132 @@
1
+ // Look up locations for a CID, from a FISL indexer or directly from a PDS.
2
+ import { getRecord, resolveIdentity } from "../atproto.js";
3
+ import { liveRecord, toLocation } from "../record.js";
4
+ import { FISL_PREFIX } from "./server.js";
5
+ /** Split a byte stream into lines, without a bound on their number. */
6
+ async function* lines(body) {
7
+ const decoder = new TextDecoder();
8
+ let buf = "";
9
+ for await (const chunk of body) {
10
+ buf += decoder.decode(chunk, { stream: true });
11
+ let i;
12
+ while ((i = buf.indexOf("\n")) >= 0) {
13
+ yield buf.slice(0, i);
14
+ buf = buf.slice(i + 1);
15
+ }
16
+ }
17
+ buf += decoder.decode();
18
+ if (buf)
19
+ yield buf;
20
+ }
21
+ /** Stream locations for a CID from a FISL indexer, using the jsonl format. */
22
+ export async function* resolveFromIndexer(cid, indexer, signal) {
23
+ const url = new URL(`${FISL_PREFIX}${cid}/jsonl`, indexer);
24
+ const res = await fetch(url, { signal });
25
+ if (!res.ok || !res.body) {
26
+ await res.body?.cancel();
27
+ throw new Error(`${url}: ${res.status} ${res.statusText}`);
28
+ }
29
+ for await (const line of lines(res.body)) {
30
+ if (!line.trim())
31
+ continue;
32
+ const loc = liveRecord(JSON.parse(line));
33
+ if (loc)
34
+ yield loc;
35
+ }
36
+ }
37
+ /** Read the location a publisher announced for a CID, straight from its PDS. */
38
+ export async function resolveFromPds(cid, handleOrDid, signal) {
39
+ const id = await resolveIdentity(handleOrDid, signal);
40
+ const record = await getRecord(id, cid, signal);
41
+ const live = record && liveRecord(record);
42
+ return live ? toLocation(live, id.did) : null;
43
+ }
44
+ /** Locations from every indexer and publisher. Failing sources are skipped. */
45
+ export async function* resolve(cid, opts) {
46
+ const stop = new AbortController();
47
+ const signal = opts.signal
48
+ ? AbortSignal.any([opts.signal, stop.signal])
49
+ : stop.signal;
50
+ const sources = [
51
+ ...(opts.publishers ?? []).map((source) => ({ source, publisher: true })),
52
+ ...(opts.indexers ?? []).map((source) => ({ source, publisher: false })),
53
+ ];
54
+ const queue = [];
55
+ let wake = () => { };
56
+ let remaining = sources.length;
57
+ const worker = async () => {
58
+ while (sources.length && !signal.aborted) {
59
+ const { source, publisher } = sources.shift();
60
+ const timeout = AbortSignal.any([
61
+ signal,
62
+ AbortSignal.timeout(opts.resolutionTimeoutMs ?? 10_000),
63
+ ]);
64
+ const work = (async () => {
65
+ if (publisher) {
66
+ const loc = await resolveFromPds(cid, source, timeout);
67
+ if (loc && !timeout.aborted) {
68
+ queue.push(loc);
69
+ wake();
70
+ }
71
+ }
72
+ else {
73
+ for await (const loc of resolveFromIndexer(cid, source, timeout)) {
74
+ if (timeout.aborted)
75
+ break;
76
+ queue.push(loc);
77
+ wake();
78
+ }
79
+ }
80
+ })();
81
+ try {
82
+ await Promise.race([
83
+ work,
84
+ new Promise((_, reject) => {
85
+ if (timeout.aborted)
86
+ reject(timeout.reason);
87
+ else {
88
+ timeout.addEventListener("abort", () => reject(timeout.reason), { once: true });
89
+ }
90
+ }),
91
+ ]);
92
+ }
93
+ catch (e) {
94
+ if (!signal.aborted)
95
+ opts.onError?.(source, e);
96
+ }
97
+ finally {
98
+ remaining--;
99
+ wake();
100
+ }
101
+ }
102
+ };
103
+ const workers = Array.from({
104
+ length: Math.min(sources.length, Math.max(1, opts.resolutionConcurrency ?? 4)),
105
+ }, worker);
106
+ try {
107
+ while (remaining && !signal.aborted || queue.length) {
108
+ if (queue.length)
109
+ yield queue.shift();
110
+ else {
111
+ await new Promise((resolve) => {
112
+ if (signal.aborted) {
113
+ resolve();
114
+ return;
115
+ }
116
+ const done = () => {
117
+ signal.removeEventListener("abort", done);
118
+ resolve();
119
+ };
120
+ wake = done;
121
+ signal.addEventListener("abort", done, { once: true });
122
+ });
123
+ }
124
+ }
125
+ if (opts.signal?.aborted)
126
+ throw opts.signal.reason;
127
+ }
128
+ finally {
129
+ stop.abort();
130
+ await Promise.allSettled(workers);
131
+ }
132
+ }
@@ -0,0 +1,19 @@
1
+ import type { Store } from "../index/store.ts";
2
+ import { type Location } from "../record.ts";
3
+ export declare const FISL_PREFIX = "/routing/locations/";
4
+ export interface FislOptions {
5
+ /** max-age in seconds when no record states an expiry. */
6
+ ttl?: number;
7
+ /** max-age in seconds for an empty result. */
8
+ emptyTtl?: number;
9
+ }
10
+ /** Find the live locations for a CID. */
11
+ export declare function lookup(store: Store, cid: string, now?: number): Promise<{
12
+ locations: Location[];
13
+ expires: number | null;
14
+ }>;
15
+ /**
16
+ * A handler for FISL requests. Returns null for paths outside
17
+ * /routing/locations/, so it can be combined with other handlers.
18
+ */
19
+ export declare function fislHandler(store: Store, { ttl, emptyTtl }?: FislOptions): (req: Request) => Promise<Response | null>;
@@ -0,0 +1,69 @@
1
+ // The FISL HTTP endpoint: GET /routing/locations/{cid}/{format}
2
+ // See specs/fisl.md.
3
+ import { parseCid } from "../cid.js";
4
+ import { earliestExpiry, liveRecord, toLocation, } from "../record.js";
5
+ export const FISL_PREFIX = "/routing/locations/";
6
+ const CORS = {
7
+ "access-control-allow-origin": "*",
8
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
9
+ };
10
+ /** Find the live locations for a CID. */
11
+ export async function lookup(store, cid, now = Date.now()) {
12
+ const locations = [];
13
+ let expires = null;
14
+ for (const row of await store.get(cid)) {
15
+ const rec = liveRecord(row.record, now);
16
+ if (!rec)
17
+ continue;
18
+ locations.push(toLocation(rec, row.did));
19
+ const exp = earliestExpiry(rec);
20
+ if (exp !== null)
21
+ expires = Math.min(expires ?? exp, exp);
22
+ }
23
+ return { locations, expires };
24
+ }
25
+ /**
26
+ * A handler for FISL requests. Returns null for paths outside
27
+ * /routing/locations/, so it can be combined with other handlers.
28
+ */
29
+ export function fislHandler(store, { ttl = 60, emptyTtl = 5 } = {}) {
30
+ return async (req) => {
31
+ const { pathname } = new URL(req.url);
32
+ if (!pathname.startsWith(FISL_PREFIX))
33
+ return null;
34
+ if (req.method === "OPTIONS") {
35
+ return new Response(null, { status: 204, headers: CORS });
36
+ }
37
+ if (req.method !== "GET" && req.method !== "HEAD") {
38
+ return new Response("Method not allowed", { status: 405, headers: CORS });
39
+ }
40
+ const [cid, format, ...extra] = pathname.slice(FISL_PREFIX.length).split("/");
41
+ if (!parseCid(cid)) {
42
+ return new Response("Not a DASL or BDASL CID", {
43
+ status: 400,
44
+ headers: CORS,
45
+ });
46
+ }
47
+ if ((format !== "json" && format !== "jsonl") || extra.length) {
48
+ return new Response("Unsupported format", { status: 404, headers: CORS });
49
+ }
50
+ const now = Date.now();
51
+ const { locations, expires } = await lookup(store, cid, now);
52
+ // max-age must not outlive the earliest expiry in the response.
53
+ let maxAge = locations.length ? ttl : emptyTtl;
54
+ if (expires !== null) {
55
+ maxAge = Math.min(maxAge, Math.floor((expires - now) / 1000));
56
+ }
57
+ const headers = {
58
+ ...CORS,
59
+ "cache-control": `public, max-age=${Math.max(0, maxAge)}`,
60
+ "content-type": format === "json"
61
+ ? "application/json"
62
+ : "application/jsonl",
63
+ };
64
+ const body = format === "json"
65
+ ? JSON.stringify({ locations })
66
+ : locations.map((l) => JSON.stringify(l) + "\n").join("");
67
+ return new Response(req.method === "HEAD" ? null : body, { headers });
68
+ };
69
+ }
@@ -0,0 +1,14 @@
1
+ import type { Store } from "./store.ts";
2
+ import type { Verified, Verifier } from "./verify.ts";
3
+ export type IngestResult = "stored" | "deleted" | "discarded" | "stale";
4
+ /**
5
+ * Index the current state of (did, cid). The event only says that something
6
+ * changed: the record itself comes from a verified proof from the PDS.
7
+ */
8
+ export declare function ingest(store: Store, verifier: Verifier, did: string, cid: string): Promise<IngestResult>;
9
+ /**
10
+ * Index a record that the caller already has, for example from a Jetstream
11
+ * event. Nothing is verified, so the caller must trust the record's source.
12
+ * A null record deletes (did, cid).
13
+ */
14
+ export declare function ingestUnverified(store: Store, did: string, cid: string, { record, rev }: Verified): Promise<IngestResult>;
@@ -0,0 +1,31 @@
1
+ // Apply ATFISL indexing steps 2 to 6 to one record event.
2
+ import { parseCid } from "../cid.js";
3
+ import { liveRecord } from "../record.js";
4
+ /**
5
+ * Index the current state of (did, cid). The event only says that something
6
+ * changed: the record itself comes from a verified proof from the PDS.
7
+ */
8
+ export async function ingest(store, verifier, did, cid) {
9
+ if (!parseCid(cid))
10
+ return "discarded";
11
+ return ingestUnverified(store, did, cid, await verifier.verify(did, cid));
12
+ }
13
+ /**
14
+ * Index a record that the caller already has, for example from a Jetstream
15
+ * event. Nothing is verified, so the caller must trust the record's source.
16
+ * A null record deletes (did, cid).
17
+ */
18
+ export async function ingestUnverified(store, did, cid, { record, rev }) {
19
+ if (!parseCid(cid))
20
+ return "discarded";
21
+ const live = record && liveRecord(record);
22
+ if (!live) {
23
+ // Absent, expired or without usable addrs: remove any older row.
24
+ await store.delete(cid, did, rev);
25
+ return record ? "discarded" : "deleted";
26
+ }
27
+ if (!rev)
28
+ return "discarded";
29
+ const stored = await store.put({ cid, did, rev, record: live });
30
+ return stored ? "stored" : "stale";
31
+ }