@dasl/fisl 0.1.0 → 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.
package/README.md CHANGED
@@ -1,79 +1,274 @@
1
1
  # @dasl/fisl
2
2
 
3
- A Node.js library for [FISL](https://dasl.ing/fisl.html) and [ATFISL](https://dasl.ing/atfisl.html). It does four things:
3
+ Publish content-addressed files to AT Protocol, discover mirrors by [DASL CID](https://dasl.ing/cid.html), and download verified bytes from any host.
4
4
 
5
- - Publish `dev.fisl.at` records to your AT Protocol repo (Bluesky-hosted or self-hosted PDS).
6
- - Run a FISL indexer. It follows Jetstream or polls a PDS, verifies each record against a signed commit, and serves `GET /routing/locations/{cid}/{json,jsonl}`.
7
- - Serve a local directory over [RASL](https://dasl.ing/rasl.html), and optionally publish a record for each file.
8
- - Fetch content by CID. It resolves locations with FISL, tries each URL, and verifies the hash.
5
+ `@dasl/fisl` implements [FISL](https://dasl.ing/fisl.html), [ATFISL](https://dasl.ing/atfisl.html), and [RASL](https://dasl.ing/rasl.html) as both a TypeScript/JavaScript library and the `fisl` CLI.
9
6
 
10
- Requires Node.js 22.13 or later. Repository development and tests use Node 24 or later. The package also includes the [`fisl` command line tool](CLI.md).
7
+ Requires Node.js 22.13 or later.
11
8
 
12
9
  ## Install
13
10
 
14
- Install the package in your project:
11
+ Use it as a library:
15
12
 
16
13
  ```sh
17
14
  npm install @dasl/fisl
18
15
  ```
19
16
 
20
- Import the library from `@dasl/fisl`:
17
+ Or use the `fisl` CLI directly:
18
+
19
+ ```sh
20
+ npm install -g @dasl/fisl
21
+ # or run without installing globally:
22
+ npx @dasl/fisl help
23
+ ```
24
+
25
+ ## What you can do
26
+
27
+ ### With the CLI
28
+
29
+ Compute CIDs, announce file URLs to your AT Protocol repo, serve a local directory, and fetch verified files from the command line:
30
+
31
+ ```sh
32
+ # Hash a file to its DASL CID
33
+ fisl cid photo.jpg
34
+
35
+ # Announce that a file is available at a URL (uses an AT Protocol app password)
36
+ export FISL_HANDLE=alice.bsky.social FISL_APP_PASSWORD=xxxx-xxxx-xxxx-xxxx
37
+ fisl publish photo.jpg --url https://example.com/photo.jpg --expires 2026-12-31T00:00:00Z
38
+
39
+ # Publish many records, one {"cid", ...record} object per line
40
+ fisl publish --jsonl records.jsonl
41
+
42
+ # List and remove records
43
+ fisl list alice.bsky.social
44
+ fisl unpublish bafkrei...
45
+
46
+ # Serve a directory over RASL and announce every file
47
+ fisl serve ./public --port 8080 --public-url https://files.example.com --publish
48
+
49
+ # Resolve mirrors and download a verified file
50
+ export FISL_INDEXER=http://localhost:8000
51
+ fisl resolve bafkrei...
52
+ fisl get bafkrei... -o photo.jpg
53
+ # Or fetch directly from a publisher without an indexer
54
+ fisl get bafkrei... --did alice.bsky.social -o photo.jpg
55
+ ```
56
+
57
+ `fisl get` uses `https` and `rasl://` URLs and skips unknown schemes such as `radiroh://`. Add `--allow-http` for plain HTTP and `--allow-private` for loopback or private network hosts.
58
+
59
+ #### Running an indexer
60
+
61
+ `fisl indexer` runs a local FISL HTTP server (`GET /routing/locations/{cid}/{json,jsonl}`) backed by SQLite (default `fisl-index.sqlite`) or memory (`--db :memory:`). By default it connects to Bluesky's public Jetstream and indexes every ATFISL record in real time.
62
+
63
+ ```sh
64
+ # Index every ATFISL record on Jetstream (defaults: port 8000, fisl-index.sqlite)
65
+ fisl indexer
66
+
67
+ # Backfill specific publishers at startup, then follow their live commits on Jetstream
68
+ fisl indexer --did alice.bsky.social --did did:plc:abc123... --port 8000 --db fisl-index.sqlite
69
+
70
+ # Index every ATFISL record on Jetstream, and backfill one publisher at startup
71
+ fisl indexer --backfill alice.bsky.social
72
+
73
+ # Use a custom Jetstream endpoint and an in-memory store for quick local testing
74
+ fisl indexer --jetstream wss://jetstream1.us-west.bsky.network/subscribe --db :memory:
75
+
76
+ # Poll specific publishers directly from their PDS every 30 seconds (no Jetstream)
77
+ fisl indexer --source pds --did alice.bsky.social --did bob.bsky.social --interval 30
78
+ ```
79
+
80
+ The `--did` flag (which accepts handles or DIDs and can be repeated) controls which publishers are indexed:
81
+
82
+ - **Omit `--did`** (with default `--source jetstream`): follows live commits from every publisher on Jetstream, with no historical backfill.
83
+ - **Pass one or more `--did` flags**: indexes only those publishers. With `--source jetstream`, the indexer backfills their existing records at startup and then filters Jetstream to them. With `--source pds`, `--did` is required and the indexer polls only those repos.
84
+ - **Pass one or more `--backfill` flags** (`--source jetstream` only): backfills those publishers at startup, but does not filter Jetstream to them. Without `--did`, the indexer then follows every publisher. The flag accepts handles or DIDs and can be repeated.
85
+
86
+ #### CLI configuration
87
+
88
+ The CLI reads these environment variables. A command-line flag overrides the variable.
89
+
90
+ | Variable | Used by | Flag |
91
+ | --- | --- | --- |
92
+ | `FISL_HANDLE` | `publish`, `list`, `unpublish`, `serve` | `--handle` |
93
+ | `FISL_APP_PASSWORD` | `publish`, `unpublish`, `serve` | `--password` |
94
+ | `FISL_INDEXER` | `resolve`, `get` | `--indexer` |
95
+
96
+ The CLI does not read a `.env` file by itself. Use Node.js's `--env-file` flag to load one (add `.env` to `.gitignore` because it holds a secret):
97
+
98
+ ```sh
99
+ # Example .env:
100
+ # FISL_HANDLE=alice.bsky.social
101
+ # FISL_APP_PASSWORD=xxxx-xxxx-xxxx-xxxx
102
+ # FISL_INDEXER=http://localhost:8000
103
+
104
+ NODE_OPTIONS="--env-file=$HOME/.config/fisl/.env" fisl publish photo.jpg --url https://example.com/photo.jpg
105
+ ```
106
+
107
+ Variables already set in your shell take priority over the file.
108
+
109
+ ### With the library
110
+
111
+ #### 1. Publish and manage records
112
+
113
+ Hash a file, sign in to your PDS (Bluesky-hosted or self-hosted), and publish a `dev.fisl.at` record. Records can list multiple mirror URLs and optional expiry timestamps.
21
114
 
22
115
  ```ts
23
- import { cidForFile, fetchCid, login, publish } from "@dasl/fisl";
116
+ import { cidForFile, deleteRecord, listRecords, login, publish } from "@dasl/fisl";
24
117
 
25
118
  const cid = await cidForFile("photo.jpg");
26
119
  const session = await login("alice.bsky.social", process.env.APP_PASSWORD!);
120
+
27
121
  await publish(session, [{
28
122
  cid,
29
- record: { addrs: [{ url: "https://example.com/photo.jpg" }] },
123
+ record: {
124
+ addrs: [
125
+ { url: "https://example.com/photo.jpg" },
126
+ { url: "https://mirror.example.org/photo.jpg", expires: "2026-12-31T00:00:00Z" },
127
+ ],
128
+ },
30
129
  }]);
31
130
 
32
- const bytes = await fetchCid(cid, { indexers: ["https://indexer.example"] });
131
+ // List or remove published records
132
+ for await (const { cid: publishedCid } of listRecords(session)) {
133
+ console.log(publishedCid);
134
+ }
135
+ await deleteRecord(session, cid);
33
136
  ```
34
137
 
35
- The handlers return `null` for paths they do not own, so you can combine them in one server:
138
+ #### 2. Resolve and fetch verified content
139
+
140
+ Look up mirrors from one or more FISL indexers, or directly from a publisher's handle or DID. Every download is hashed and verified against the CID before it is returned.
141
+
142
+ ```ts
143
+ import { downloadCid, fetchCid, resolve } from "@dasl/fisl";
144
+
145
+ // Inspect live locations without downloading
146
+ for await (const loc of resolve(cid, {
147
+ indexers: ["https://indexer.example"],
148
+ publishers: ["alice.bsky.social"],
149
+ })) {
150
+ console.log(loc.addrs);
151
+ }
152
+
153
+ // Fetch into memory (verified against the CID)
154
+ const bytes = await fetchCid(cid, {
155
+ indexers: ["https://indexer.example"],
156
+ });
157
+
158
+ // Stream large files to disk atomically (verified before replacing destination)
159
+ await downloadCid(cid, "./photo.jpg", {
160
+ publishers: ["alice.bsky.social"],
161
+ });
162
+ ```
163
+
164
+ By default, `fetchCid` and `downloadCid` allow only `https://` and `rasl://` URLs on public IP addresses. For local development against `localhost` or plain `http://`, opt in explicitly:
165
+
166
+ ```ts
167
+ const bytes = await fetchCid(cid, {
168
+ indexers: ["http://localhost:8000"],
169
+ allowHttp: true,
170
+ allowPrivate: true,
171
+ });
172
+ ```
173
+
174
+ #### 3. Serve a local directory over RASL
175
+
176
+ Index a directory and serve its files at `/.well-known/rasl/{cid}`:
177
+
178
+ ```ts
179
+ import { indexDir, raslHandler } from "@dasl/fisl";
180
+ import { serve } from "@dasl/fisl/serve";
181
+
182
+ const files = await indexDir("./public");
183
+ const rasl = raslHandler(files);
184
+ const server = await serve(
185
+ async (req) => (await rasl(req)) ?? new Response(null, { status: 404 }),
186
+ { port: 8080 },
187
+ );
188
+
189
+ // On shutdown, stop the server and clean up temporary snapshots
190
+ await server.shutdown();
191
+ await files.dispose();
192
+ ```
193
+
194
+ #### 4. Run a FISL indexer
195
+
196
+ Follow Jetstream for all `dev.fisl.at` commits (or poll specific repos with `pollRepos`), verify each record against its signed commit, store it in SQLite, and serve `GET /routing/locations/{cid}/{json,jsonl}`:
197
+
198
+ ```ts
199
+ import { fislHandler, followJetstream, Verifier } from "@dasl/fisl";
200
+ import { serve } from "@dasl/fisl/serve";
201
+ import { SqliteStore } from "@dasl/fisl/sqlite";
202
+
203
+ const store = await SqliteStore.open("fisl-index.sqlite");
204
+ const verifier = new Verifier();
205
+ const stop = new AbortController();
206
+
207
+ // Start following Jetstream in the background
208
+ const follower = followJetstream(store, verifier, { signal: stop.signal });
209
+
210
+ const fisl = fislHandler(store);
211
+ const server = await serve(
212
+ async (req) => (await fisl(req)) ?? new Response(null, { status: 404 }),
213
+ { port: 8000 },
214
+ );
215
+ ```
216
+
217
+ #### 5. Combine handlers in any fetch-style server
218
+
219
+ `fislHandler` and `raslHandler` take a standard `Request` and return `Response | null`. Returning `null` for paths they do not own lets you compose them in Cloudflare Workers, Deno, Bun, or Node.js:
36
220
 
37
221
  ```ts
38
222
  import { fislHandler, indexDir, MemoryStore, raslHandler } from "@dasl/fisl";
39
223
 
40
224
  const fisl = fislHandler(new MemoryStore());
41
225
  const rasl = raslHandler(await indexDir("./public"));
226
+
42
227
  export default {
43
228
  fetch: async (req: Request) =>
44
229
  (await fisl(req)) ?? (await rasl(req)) ?? new Response(null, { status: 404 }),
45
230
  };
46
231
  ```
47
232
 
48
- The handlers take a `Request` and return a `Response`, so they work in Cloudflare Workers and other fetch-style servers. For a Node.js HTTP server, import `serve` from `@dasl/fisl/serve`. The `fisl` CLI uses this server adapter.
233
+ See `examples/kiwix.ts` in the repository for an end-to-end publishing example.
49
234
 
50
- For a persistent index, import `SqliteStore` from `@dasl/fisl/sqlite`. It uses `node:sqlite`:
235
+ ## Package entry points
51
236
 
52
- ```ts
53
- import { SqliteStore } from "@dasl/fisl/sqlite";
237
+ The package splits Node-specific adapters into subpaths so the core library stays portable across runtimes:
54
238
 
55
- const store = await SqliteStore.open("fisl-index.sqlite");
56
- ```
239
+ | Entry point | Purpose |
240
+ | --- | --- |
241
+ | `@dasl/fisl` | Core library: CIDs, records, AT Protocol publishing, resolution, verified fetching, `fislHandler`, `raslHandler`, `MemoryStore`, `Verifier`, `ingest`, `ingestUnverified`, `followJetstream`, `pollRepos`, `backfill`. |
242
+ | `@dasl/fisl/serve` | Node.js `node:http` adapter (`serve`) for fetch-style handlers. |
243
+ | `@dasl/fisl/sqlite` | Persistent `SqliteStore` backed by `node:sqlite`. |
244
+
245
+ ## Cloudflare Workers
246
+
247
+ The library and its dependencies use Node.js built-in modules. Workers with a compatibility date of `2026-08-04` or later include them by default. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config.
57
248
 
58
- ### Cloudflare Workers
249
+ Workers have no local file system, so do not use `cidForFile`, `downloadCid`, `indexDir`, `@dasl/fisl/serve`, or `@dasl/fisl/sqlite` in a Worker. Portable exports such as `cidFromDigest`, `cidForBytes`, `login`, `putRecords`, `resolveIdentity`, `fislHandler`, `ingest`, and custom `Store` implementations (for example, on D1) work in Workers. Reference Workers live in the monorepo under `indexer-worker/`, `kiwix-worker/`, and `nasa-worker/`.
59
250
 
60
- The library uses Node.js built-in modules, and so do its dependencies. Workers with a compatibility date of 2026-08-04 or later have them by default. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config.
251
+ ## Defaults, limits, and safety
61
252
 
62
- Workers have no local file system. Do not use `cidForFile`, `downloadCid`, `indexDir` or `SqliteStore` in a Worker. The Workers in this repository use `cidFromDigest`, `login`, `putRecords`, `resolveIdentity`, `fislHandler`, `ingest` and their own `Store` on D1. See the Workers at the repository root: `indexer-worker/`, `kiwix-worker/`, and `nasa-worker/`.
253
+ - **Streaming and atomic downloads**: `downloadCid(cid, destination, options)` and `fisl get CID --output PATH` stream into a temporary file beside the destination and replace the destination only after the bytes match the CID.
254
+ - **Size limits**: `fetchCid` defaults to a 1 GiB limit in memory. `downloadCid` has no default size limit; set `maxSize` to enforce one.
255
+ - **Concurrency and timeouts**: Retrieval resolves up to 4 sources and downloads from up to 3 mirrors at once. Default deadlines are 10 seconds per source and 30 seconds per mirror. Override with `resolutionTimeoutMs`, `downloadTimeoutMs`, `resolutionConcurrency`, or `concurrency`. Pass an `AbortSignal` as `signal` to cancel.
256
+ - **SSRF protection**: Private and loopback IP addresses are blocked by default unless `allowPrivate: true` is set. Each connection is pinned to the IP address that passed the check.
257
+ - **RASL snapshots**: `indexDir` copies files into temporary snapshots before hashing them, so edits to the source directory cannot change the bytes behind an existing CID. Snapshots use disk space equal to the indexed files. Call `await files.dispose()` after stopping the server to remove them.
63
258
 
64
259
  ## How indexing works
65
260
 
66
- Jetstream events have no commit proof. For each `dev.fisl.at` event, the indexer fetches `com.atproto.sync.getRecord` from the publisher's PDS. That call returns the signed commit and the path to the record. The indexer then:
261
+ Jetstream events do not carry a commit proof. For each `dev.fisl.at` event, the indexer fetches `com.atproto.sync.getRecord` from the publisher's PDS, which returns the signed commit and MST proof for the record. The indexer then:
67
262
 
68
- 1. checks the commit signature against the DID's signing key;
69
- 2. applies the ATFISL expiry rules;
70
- 3. stores one row per CID and DID, and keeps the newest repo revision.
263
+ 1. Verifies the commit signature against the DID's signing key.
264
+ 2. Applies the ATFISL expiry rules.
265
+ 3. Stores one row per `(cid, did)` and keeps the newest repo revision.
71
266
 
72
- The Jetstream cursor is saved, so a restart continues from where it stopped.
267
+ Stores retain deletion and expiry revisions after hiding records so an older update cannot restore a deleted record. The Jetstream cursor is persisted so restarts continue where they left off. If proof verification fails, the CLI follower reconnects from its saved cursor, and the monorepo Worker saves failed proofs before advancing progress so later runs can retry them.
73
268
 
74
- ## Test
269
+ ## Development
75
270
 
76
- From the repository root:
271
+ Repository development and tests require Node.js 24 or later. From the repository root:
77
272
 
78
273
  ```sh
79
274
  npm install
@@ -81,29 +276,18 @@ npm run build
81
276
  npm test -w @dasl/fisl
82
277
  ```
83
278
 
84
- To test the CLI and library from the package tarball and build the Workers, run this at the repository root:
279
+ To run the CLI from a checkout without installing globally:
85
280
 
86
281
  ```sh
87
- npm run test:pack
282
+ npm run fisl -w @dasl/fisl -- help
283
+ # Or with a local .env file from packages/fisl/:
284
+ node --env-file=.env cli.ts publish photo.jpg --url https://example.com/photo.jpg
88
285
  ```
89
286
 
90
- For large files, use `downloadCid(cid, destination, options)` or `fisl get CID --output PATH`.
91
- The download streams into a temporary file beside the destination.
92
- It replaces the destination only after the bytes match the CID.
93
- File downloads have no default size limit. Set `maxSize` to impose one.
94
-
95
- Retrieval resolves up to four sources and downloads from up to three mirrors at once.
96
- The default deadlines are 10 seconds per source and 30 seconds per mirror.
97
- Set `resolutionTimeoutMs`, `downloadTimeoutMs`, `resolutionConcurrency`, or `concurrency` to change these limits.
98
- Pass an `AbortSignal` as `signal` to cancel retrieval.
99
- Private address filtering pins each connection to the address that it checks.
100
-
101
- `indexDir` copies files into temporary snapshots before it hashes them.
102
- RASL serves these snapshots, so edits to the source directory cannot change bytes behind an existing CID.
103
- Snapshots require additional disk space equal to the indexed files.
104
- After stopping the server, call `await files.dispose()` on the result of `indexDir` to remove the snapshots.
105
-
106
- Stores retain deletion revisions and expiry revisions after they hide records.
107
- This prevents an older update from restoring a deleted record.
108
- The Worker saves failed proofs before it advances stream or backfill progress, then retries them on later runs.
109
- The CLI follower reconnects from its saved position after a failed proof.
287
+ To link the built workspace command globally, run `npm link` inside `packages/fisl/`.
288
+
289
+ To test the packed tarball (CLI and library exports) and build the Workers:
290
+
291
+ ```sh
292
+ npm run test:pack
293
+ ```
package/dist/cli.js CHANGED
@@ -27,7 +27,8 @@ Usage:
27
27
  fisl serve <dir> [--port 8080] [--hostname 0.0.0.0]
28
28
  [--public-url https://host] [--publish] [--expires <datetime>]
29
29
  fisl indexer [--port 8000] [--db <path>|:memory:] [--source jetstream|pds]
30
- [--did <handle|did>]... [--interval <seconds>] [--jetstream <url>]
30
+ [--did <handle|did>]... [--backfill <handle|did>]...
31
+ [--interval <seconds>] [--jetstream <url>]
31
32
  fisl resolve <cid> [--indexer <url>]... [--did <handle|did>]...
32
33
  fisl get <cid> [--indexer <url>]... [--did <handle|did>]... [-o <file>]
33
34
  [--allow-http] [--allow-private]
@@ -104,6 +105,14 @@ function checkExpires(expires) {
104
105
  fail(`--expires must be a datetime like 2026-12-31T00:00:00Z`);
105
106
  }
106
107
  }
108
+ function parseNumberFlag(name, value, { min = 0, max = Infinity, integer = true } = {}) {
109
+ const n = Number(value);
110
+ if (!Number.isFinite(n) || (integer && !Number.isInteger(n)) ||
111
+ n < min || n > max) {
112
+ fail(`--${name} must be a valid number`);
113
+ }
114
+ return n;
115
+ }
107
116
  const commands = {
108
117
  async cid(args) {
109
118
  const { _: files } = parse(args, {});
@@ -184,6 +193,7 @@ const commands = {
184
193
  db: { type: "string", default: "fisl-index.sqlite" },
185
194
  source: { type: "string", default: "jetstream" },
186
195
  did: { type: "string", multiple: true, default: [] },
196
+ backfill: { type: "string", multiple: true, default: [] },
187
197
  interval: { type: "string", default: "60" },
188
198
  jetstream: { type: "string", default: JETSTREAM },
189
199
  });
@@ -193,33 +203,75 @@ const commands = {
193
203
  if (flags.source === "pds" && !flags.did.length) {
194
204
  fail("--source pds needs at least one --did");
195
205
  }
206
+ if (flags.source === "pds" && flags.backfill.length) {
207
+ fail("--backfill needs --source jetstream");
208
+ }
209
+ const port = parseNumberFlag("port", flags.port, { min: 0, max: 65535 });
210
+ const interval = parseNumberFlag("interval", flags.interval, {
211
+ min: 1,
212
+ integer: false,
213
+ });
196
214
  const store = flags.db === ":memory:"
197
215
  ? new MemoryStore()
198
216
  : await SqliteStore.open(flags.db);
199
217
  const verifier = new Verifier();
200
218
  const log = (msg) => console.error(msg);
201
219
  const dids = await Promise.all(flags.did.map(resolveHandleOrFail));
220
+ // Backfilled too, but Jetstream is not limited to them.
221
+ const backfillDids = [
222
+ ...new Set([
223
+ ...dids,
224
+ ...await Promise.all(flags.backfill.map(resolveHandleOrFail)),
225
+ ]),
226
+ ];
202
227
  const fisl = fislHandler(store);
203
- await serve(async (req) => (await fisl(req)) ?? new Response("Not found", { status: 404 }), { port: Number(flags.port), hostname: flags.hostname });
204
- setInterval(async () => {
205
- const n = await store.sweep();
206
- if (n)
207
- log(`swept ${n} expired records`);
228
+ const server = await serve(async (req) => (await fisl(req)) ?? new Response("Not found", { status: 404 }), { port, hostname: flags.hostname });
229
+ const abort = new AbortController();
230
+ const stop = () => {
231
+ abort.abort();
232
+ void server.shutdown();
233
+ };
234
+ process.once("SIGINT", stop);
235
+ process.once("SIGTERM", stop);
236
+ const sweeper = setInterval(async () => {
237
+ try {
238
+ const n = await store.sweep();
239
+ if (n)
240
+ log(`swept ${n} expired records`);
241
+ }
242
+ catch (e) {
243
+ log(`sweep error: ${e.message}`);
244
+ }
208
245
  }, 60_000);
209
- if (flags.source === "pds") {
210
- await pollRepos(store, verifier, dids, {
211
- interval: Number(flags.interval) * 1000,
212
- log,
213
- });
246
+ try {
247
+ if (flags.source === "pds") {
248
+ await pollRepos(store, verifier, dids, {
249
+ interval: interval * 1000,
250
+ log,
251
+ signal: abort.signal,
252
+ });
253
+ }
254
+ else {
255
+ for (const did of backfillDids) {
256
+ if (abort.signal.aborted)
257
+ break;
258
+ await backfill(store, verifier, did, { log, signal: abort.signal });
259
+ }
260
+ await followJetstream(store, verifier, {
261
+ url: flags.jetstream,
262
+ dids,
263
+ log,
264
+ signal: abort.signal,
265
+ });
266
+ }
214
267
  }
215
- else {
216
- for (const did of dids)
217
- await backfill(store, verifier, did, { log });
218
- await followJetstream(store, verifier, {
219
- url: flags.jetstream,
220
- dids,
221
- log,
222
- });
268
+ finally {
269
+ clearInterval(sweeper);
270
+ process.off("SIGINT", stop);
271
+ process.off("SIGTERM", stop);
272
+ await server.shutdown();
273
+ if (store instanceof SqliteStore)
274
+ store.close();
223
275
  }
224
276
  },
225
277
  async resolve(args) {
@@ -258,6 +310,7 @@ const commands = {
258
310
  const dir = flags._[0];
259
311
  if (!dir)
260
312
  fail("serve needs a directory");
313
+ const port = parseNumberFlag("port", flags.port, { min: 0, max: 65535 });
261
314
  const publicUrl = flags["public-url"]?.replace(/\/$/, "");
262
315
  if (flags.publish && !publicUrl)
263
316
  fail("--publish needs --public-url");
@@ -271,7 +324,7 @@ const commands = {
271
324
  });
272
325
  console.error(`Indexed ${files.size} files`);
273
326
  const rasl = raslHandler(files);
274
- const server = await serve(async (req) => (await rasl(req)) ?? new Response("Not found", { status: 404 }), { port: Number(flags.port), hostname: flags.hostname });
327
+ const server = await serve(async (req) => (await rasl(req)) ?? new Response("Not found", { status: 404 }), { port, hostname: flags.hostname });
275
328
  const stop = () => {
276
329
  void server.shutdown();
277
330
  };
@@ -60,7 +60,7 @@ export declare function putRecords(s: Session, records: {
60
60
  /** Read one record from a repo. Returns null if there is none. */
61
61
  export declare function getRecord(id: Identity, cid: string, signal?: AbortSignal): Promise<AtfislRecord | null>;
62
62
  /** List every dev.fisl.at record in a repo. */
63
- export declare function listRecords(id: Identity): AsyncGenerator<{
63
+ export declare function listRecords(id: Identity, signal?: AbortSignal): AsyncGenerator<{
64
64
  cid: string;
65
65
  record: AtfislRecord;
66
66
  }>;
@@ -3,6 +3,11 @@
3
3
  import { NSID } from "./record.js";
4
4
  export const PLC_DIRECTORY = "https://plc.directory";
5
5
  export const APPVIEW = "https://public.api.bsky.app";
6
+ const DEFAULT_TIMEOUT_MS = 30_000;
7
+ function withTimeout(signal) {
8
+ const timeout = AbortSignal.timeout(DEFAULT_TIMEOUT_MS);
9
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
10
+ }
6
11
  export class XrpcError extends Error {
7
12
  status;
8
13
  error;
@@ -25,7 +30,7 @@ export async function xrpc(service, method, opts = {}) {
25
30
  if (opts.body !== undefined)
26
31
  headers["content-type"] = "application/json";
27
32
  const res = await fetch(url, {
28
- signal: opts.signal,
33
+ signal: withTimeout(opts.signal),
29
34
  method: opts.body === undefined ? "GET" : "POST",
30
35
  headers,
31
36
  body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
@@ -54,7 +59,7 @@ export async function resolveHandle(handle, signal) {
54
59
  catch { /* fall through */ }
55
60
  try {
56
61
  const res = await fetch(`https://${handle}/.well-known/atproto-did`, {
57
- signal,
62
+ signal: withTimeout(signal),
58
63
  });
59
64
  const did = (await res.text()).trim();
60
65
  if (res.ok && did.startsWith("did:"))
@@ -69,11 +74,21 @@ export async function resolveDid(did, signal) {
69
74
  if (did.startsWith("did:plc:"))
70
75
  url = `${PLC_DIRECTORY}/${did}`;
71
76
  else if (did.startsWith("did:web:")) {
72
- url = `https://${decodeURIComponent(did.slice(8))}/.well-known/did.json`;
77
+ const host = decodeURIComponent(did.slice(8));
78
+ if (!host || /[/?#@\s]/.test(host)) {
79
+ throw new Error(`Invalid did:web: ${did}`);
80
+ }
81
+ const parsed = new URL(`https://${host}/.well-known/did.json`);
82
+ if (parsed.username || parsed.password ||
83
+ parsed.pathname !== "/.well-known/did.json" ||
84
+ parsed.search || parsed.hash) {
85
+ throw new Error(`Invalid did:web: ${did}`);
86
+ }
87
+ url = parsed.href;
73
88
  }
74
89
  else
75
90
  throw new Error(`Unsupported DID method: ${did}`);
76
- const res = await fetch(url, { signal });
91
+ const res = await fetch(url, { signal: withTimeout(signal) });
77
92
  if (!res.ok)
78
93
  throw new Error(`Could not resolve ${did}: ${res.status}`);
79
94
  return await res.json();
@@ -149,11 +164,12 @@ export async function getRecord(id, cid, signal) {
149
164
  }
150
165
  }
151
166
  /** List every dev.fisl.at record in a repo. */
152
- export async function* listRecords(id) {
167
+ export async function* listRecords(id, signal) {
153
168
  let cursor;
154
169
  do {
155
170
  const res = await xrpc(id.pds, "com.atproto.repo.listRecords", {
156
171
  params: { repo: id.did, collection: NSID, limit: 100, cursor },
172
+ signal,
157
173
  });
158
174
  for (const r of res.records) {
159
175
  yield { cid: r.uri.split("/").pop(), record: r.value };
@@ -1,4 +1,4 @@
1
- import type { Cid } from "./cid.ts";
1
+ import type { Cid } from "./cid.js";
2
2
 
3
3
  export function base32Encode(bytes: Uint8Array): string;
4
4
  export function base32Decode(s: string): Uint8Array | null;
package/dist/src/cid.js CHANGED
@@ -3,7 +3,6 @@
3
3
  // A CID is 36 bytes: version 0x01, codec, hash type, hash length 0x20 and a
4
4
  // 32-byte digest. Its only string form is "b" + lowercase base32, no padding.
5
5
  import { blake3 } from "@noble/hashes/blake3.js";
6
- import { sha256 } from "@noble/hashes/sha2.js";
7
6
  export const CODEC_RAW = 0x55;
8
7
  export const CODEC_DRISL = 0x71;
9
8
  export const HASH_SHA256 = 0x12;
@@ -13,6 +12,9 @@ export { base32Decode, base32Encode, isCid, parseCid } from "./cid-core.js";
13
12
  // @ts-types="./cid-core.d.ts"
14
13
  import { base32Encode } from "./cid-core.js";
15
14
  export function cidFromDigest(digest, codec = CODEC_RAW, hash = HASH_SHA256) {
15
+ if (digest.length !== 32) {
16
+ throw new RangeError(`Expected a 32-byte digest, got ${digest.length}`);
17
+ }
16
18
  const bytes = new Uint8Array(36);
17
19
  bytes.set([0x01, codec, hash, 0x20]);
18
20
  bytes.set(digest, 4);
@@ -25,11 +27,14 @@ export async function cidForBytes(bytes) {
25
27
  }
26
28
  /** The DASL CID of a file. Streams the file, so large files are fine. */
27
29
  export async function cidForFile(path) {
28
- const h = sha256.create();
29
- const { createReadStream } = await import("node:fs");
30
+ const [{ createHash }, { createReadStream }] = await Promise.all([
31
+ import("node:crypto"),
32
+ import("node:fs"),
33
+ ]);
34
+ const h = createHash("sha256");
30
35
  for await (const chunk of createReadStream(path))
31
36
  h.update(chunk);
32
- return cidFromDigest(h.digest());
37
+ return cidFromDigest(new Uint8Array(h.digest()));
33
38
  }
34
39
  /** Check that bytes match a CID, using the CID's hash function. */
35
40
  export async function verifyBytes(cid, bytes) {