@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.
package/README.md CHANGED
@@ -1,3 +1,293 @@
1
- # Temporary Holding Version
1
+ # @dasl/fisl
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
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.
6
+
7
+ Requires Node.js 22.13 or later.
8
+
9
+ ## Install
10
+
11
+ Use it as a library:
12
+
13
+ ```sh
14
+ npm install @dasl/fisl
15
+ ```
16
+
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.
114
+
115
+ ```ts
116
+ import { cidForFile, deleteRecord, listRecords, login, publish } from "@dasl/fisl";
117
+
118
+ const cid = await cidForFile("photo.jpg");
119
+ const session = await login("alice.bsky.social", process.env.APP_PASSWORD!);
120
+
121
+ await publish(session, [{
122
+ cid,
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
+ },
129
+ }]);
130
+
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);
136
+ ```
137
+
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:
220
+
221
+ ```ts
222
+ import { fislHandler, indexDir, MemoryStore, raslHandler } from "@dasl/fisl";
223
+
224
+ const fisl = fislHandler(new MemoryStore());
225
+ const rasl = raslHandler(await indexDir("./public"));
226
+
227
+ export default {
228
+ fetch: async (req: Request) =>
229
+ (await fisl(req)) ?? (await rasl(req)) ?? new Response(null, { status: 404 }),
230
+ };
231
+ ```
232
+
233
+ See `examples/kiwix.ts` in the repository for an end-to-end publishing example.
234
+
235
+ ## Package entry points
236
+
237
+ The package splits Node-specific adapters into subpaths so the core library stays portable across runtimes:
238
+
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.
248
+
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/`.
250
+
251
+ ## Defaults, limits, and safety
252
+
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.
258
+
259
+ ## How indexing works
260
+
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:
262
+
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.
266
+
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.
268
+
269
+ ## Development
270
+
271
+ Repository development and tests require Node.js 24 or later. From the repository root:
272
+
273
+ ```sh
274
+ npm install
275
+ npm run build
276
+ npm test -w @dasl/fisl
277
+ ```
278
+
279
+ To run the CLI from a checkout without installing globally:
280
+
281
+ ```sh
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
285
+ ```
286
+
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.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The fisl command line tool. Install it with:
4
+ *
5
+ * ```sh
6
+ * npm install -g @dasl/fisl
7
+ * ```
8
+ *
9
+ * For the library, import from `@dasl/fisl`.
10
+ *
11
+ * @module
12
+ */
13
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,368 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The fisl command line tool. Install it with:
4
+ *
5
+ * ```sh
6
+ * npm install -g @dasl/fisl
7
+ * ```
8
+ *
9
+ * For the library, import from `@dasl/fisl`.
10
+ *
11
+ * @module
12
+ */
13
+ import { readFile, stat } from "node:fs/promises";
14
+ import { text } from "node:stream/consumers";
15
+ import { parseArgs } from "node:util";
16
+ import { backfill, cidForFile, deleteRecord, downloadCid, fetchCid, fislHandler, followJetstream, indexDir, isDatetime, JETSTREAM, listRecords, login, MemoryStore, parseCid, pollRepos, publish, RASL_PREFIX, raslHandler, resolve, resolveIdentity, Verifier, } from "./mod.js";
17
+ import { SqliteStore } from "./src/index/sqlite.js";
18
+ import { serve } from "./src/serve.js";
19
+ const USAGE = `fisl: publish, index, serve and fetch content by DASL CID
20
+
21
+ Usage:
22
+ fisl cid <file...>
23
+ fisl publish <file|cid> --url <url>... [--expires <datetime>] [--size <n>]
24
+ fisl publish --jsonl <file|->
25
+ fisl unpublish <cid...>
26
+ fisl list [<handle|did>]
27
+ fisl serve <dir> [--port 8080] [--hostname 0.0.0.0]
28
+ [--public-url https://host] [--publish] [--expires <datetime>]
29
+ fisl indexer [--port 8000] [--db <path>|:memory:] [--source jetstream|pds]
30
+ [--did <handle|did>]... [--backfill <handle|did>]...
31
+ [--interval <seconds>] [--jetstream <url>]
32
+ fisl resolve <cid> [--indexer <url>]... [--did <handle|did>]...
33
+ fisl get <cid> [--indexer <url>]... [--did <handle|did>]... [-o <file>]
34
+ [--allow-http] [--allow-private]
35
+
36
+ resolve and get use FISL_INDEXER when no --indexer or --did is given.
37
+ publish --jsonl reads one {"cid", ...record} object per line, as list prints.
38
+ Publishing needs a login. Set FISL_HANDLE and FISL_APP_PASSWORD, or pass
39
+ --handle and --password.`;
40
+ function fail(message) {
41
+ console.error(`fisl: ${message}`);
42
+ process.exit(1);
43
+ }
44
+ /** Parse flags. Unknown flags fail. */
45
+ function parse(args, options) {
46
+ try {
47
+ const { values, positionals } = parseArgs({
48
+ args,
49
+ options,
50
+ allowPositionals: true,
51
+ });
52
+ return { ...values, _: positionals };
53
+ }
54
+ catch (e) {
55
+ fail(e.message);
56
+ }
57
+ }
58
+ const LOGIN = {
59
+ handle: { type: "string" },
60
+ password: { type: "string" },
61
+ };
62
+ function session(flags) {
63
+ const handle = flags.handle ?? process.env.FISL_HANDLE;
64
+ const password = flags.password ?? process.env.FISL_APP_PASSWORD;
65
+ if (!handle || !password) {
66
+ fail("set FISL_HANDLE and FISL_APP_PASSWORD, or --handle and --password");
67
+ }
68
+ return login(handle, password);
69
+ }
70
+ async function resolveHandleOrFail(handle) {
71
+ try {
72
+ return (await resolveIdentity(handle)).did;
73
+ }
74
+ catch (e) {
75
+ fail(`could not resolve ${handle}: ${e.message}`);
76
+ }
77
+ }
78
+ function lookupArgs(args) {
79
+ const flags = parse(args, {
80
+ indexer: { type: "string", multiple: true, default: [] },
81
+ did: { type: "string", multiple: true, default: [] },
82
+ output: { type: "string", short: "o" },
83
+ "allow-http": { type: "boolean" },
84
+ "allow-private": { type: "boolean" },
85
+ });
86
+ const cid = flags._[0];
87
+ if (!cid || !parseCid(cid))
88
+ fail("needs a DASL CID");
89
+ let indexers = flags.indexer;
90
+ const env = process.env.FISL_INDEXER;
91
+ if (!indexers.length && !flags.did.length && env)
92
+ indexers = [env];
93
+ if (!indexers.length && !flags.did.length) {
94
+ fail("give --indexer or --did, or set FISL_INDEXER");
95
+ }
96
+ const opts = {
97
+ indexers,
98
+ publishers: flags.did,
99
+ onError: (source, e) => console.error(`${source}: ${e.message}`),
100
+ };
101
+ return { cid, opts, flags };
102
+ }
103
+ function checkExpires(expires) {
104
+ if (expires !== undefined && !isDatetime(expires)) {
105
+ fail(`--expires must be a datetime like 2026-12-31T00:00:00Z`);
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
+ }
116
+ const commands = {
117
+ async cid(args) {
118
+ const { _: files } = parse(args, {});
119
+ if (!files.length)
120
+ fail("cid needs at least one file");
121
+ for (const f of files) {
122
+ console.log(`${await cidForFile(f)} ${f}`);
123
+ }
124
+ },
125
+ async publish(args) {
126
+ const flags = parse(args, {
127
+ ...LOGIN,
128
+ url: { type: "string", multiple: true, default: [] },
129
+ expires: { type: "string" },
130
+ size: { type: "string" },
131
+ jsonl: { type: "string" },
132
+ });
133
+ if (flags.jsonl !== undefined) {
134
+ const input = flags.jsonl === "-"
135
+ ? await text(process.stdin)
136
+ : await readFile(flags.jsonl, "utf8");
137
+ const items = input.split("\n").filter((l) => l.trim()).map((l) => {
138
+ const { cid, ...record } = JSON.parse(l);
139
+ return { cid, record };
140
+ });
141
+ const s = await session(flags);
142
+ await publish(s, items);
143
+ console.log(`Published ${items.length} records as ${s.did}`);
144
+ return;
145
+ }
146
+ const target = flags._[0];
147
+ if (!target)
148
+ fail("publish needs a file or a CID");
149
+ if (!flags.url.length)
150
+ fail("publish needs at least one --url");
151
+ checkExpires(flags.expires);
152
+ let cid = target;
153
+ let size = flags.size === undefined ? undefined : Number(flags.size);
154
+ if (!parseCid(target)) {
155
+ cid = await cidForFile(target);
156
+ size ??= (await stat(target)).size;
157
+ }
158
+ const record = {
159
+ addrs: flags.url.map((url) => ({ url })),
160
+ };
161
+ if (size !== undefined)
162
+ record.size = size;
163
+ if (flags.expires)
164
+ record.expires = flags.expires;
165
+ const s = await session(flags);
166
+ await publish(s, [{ cid, record }]);
167
+ console.log(`at://${s.did}/dev.fisl.at/${cid}`);
168
+ },
169
+ async unpublish(args) {
170
+ const flags = parse(args, LOGIN);
171
+ if (!flags._.length)
172
+ fail("unpublish needs at least one CID");
173
+ const s = await session(flags);
174
+ for (const cid of flags._) {
175
+ await deleteRecord(s, cid);
176
+ console.log(`Deleted ${cid}`);
177
+ }
178
+ },
179
+ async list(args) {
180
+ const flags = parse(args, LOGIN);
181
+ const who = flags._[0] ?? flags.handle ?? process.env.FISL_HANDLE;
182
+ if (!who)
183
+ fail("list needs a handle or DID");
184
+ const id = await resolveIdentity(who);
185
+ for await (const { cid, record } of listRecords(id)) {
186
+ console.log(JSON.stringify({ cid, ...record }));
187
+ }
188
+ },
189
+ async indexer(args) {
190
+ const flags = parse(args, {
191
+ port: { type: "string", default: "8000" },
192
+ hostname: { type: "string", default: "0.0.0.0" },
193
+ db: { type: "string", default: "fisl-index.sqlite" },
194
+ source: { type: "string", default: "jetstream" },
195
+ did: { type: "string", multiple: true, default: [] },
196
+ backfill: { type: "string", multiple: true, default: [] },
197
+ interval: { type: "string", default: "60" },
198
+ jetstream: { type: "string", default: JETSTREAM },
199
+ });
200
+ if (flags.source !== "jetstream" && flags.source !== "pds") {
201
+ fail("--source must be jetstream or pds");
202
+ }
203
+ if (flags.source === "pds" && !flags.did.length) {
204
+ fail("--source pds needs at least one --did");
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
+ });
214
+ const store = flags.db === ":memory:"
215
+ ? new MemoryStore()
216
+ : await SqliteStore.open(flags.db);
217
+ const verifier = new Verifier();
218
+ const log = (msg) => console.error(msg);
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
+ ];
227
+ const fisl = fislHandler(store);
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
+ }
245
+ }, 60_000);
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
+ }
267
+ }
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();
275
+ }
276
+ },
277
+ async resolve(args) {
278
+ const { cid, opts } = lookupArgs(args);
279
+ for await (const loc of resolve(cid, opts)) {
280
+ console.log(JSON.stringify(loc));
281
+ }
282
+ },
283
+ async get(args) {
284
+ const { cid, opts, flags } = lookupArgs(args);
285
+ try {
286
+ const options = {
287
+ ...opts,
288
+ allowHttp: flags["allow-http"],
289
+ allowPrivate: flags["allow-private"],
290
+ log: (msg) => console.error(msg),
291
+ };
292
+ if (flags.output)
293
+ await downloadCid(cid, flags.output, options);
294
+ else
295
+ process.stdout.write(await fetchCid(cid, options));
296
+ }
297
+ catch (e) {
298
+ fail(e.message);
299
+ }
300
+ },
301
+ async serve(args) {
302
+ const flags = parse(args, {
303
+ ...LOGIN,
304
+ port: { type: "string", default: "8080" },
305
+ hostname: { type: "string", default: "0.0.0.0" },
306
+ "public-url": { type: "string" },
307
+ expires: { type: "string" },
308
+ publish: { type: "boolean" },
309
+ });
310
+ const dir = flags._[0];
311
+ if (!dir)
312
+ fail("serve needs a directory");
313
+ const port = parseNumberFlag("port", flags.port, { min: 0, max: 65535 });
314
+ const publicUrl = flags["public-url"]?.replace(/\/$/, "");
315
+ if (flags.publish && !publicUrl)
316
+ fail("--publish needs --public-url");
317
+ checkExpires(flags.expires);
318
+ // Log in first, so a bad password fails before hashing a large directory.
319
+ let s;
320
+ if (flags.publish)
321
+ s = await session(flags);
322
+ const files = await indexDir(dir, {
323
+ onFile: (f) => console.error(`${f.cid} ${f.name}`),
324
+ });
325
+ console.error(`Indexed ${files.size} files`);
326
+ const rasl = raslHandler(files);
327
+ const server = await serve(async (req) => (await rasl(req)) ?? new Response("Not found", { status: 404 }), { port, hostname: flags.hostname });
328
+ const stop = () => {
329
+ void server.shutdown();
330
+ };
331
+ process.once("SIGINT", stop);
332
+ process.once("SIGTERM", stop);
333
+ console.error(`Serving ${RASL_PREFIX}{cid}`);
334
+ try {
335
+ if (s) {
336
+ await publish(s, [...files.values()].map((f) => ({
337
+ cid: f.cid,
338
+ record: {
339
+ addrs: [{ url: `${publicUrl}${RASL_PREFIX}${f.cid}` }],
340
+ size: f.size,
341
+ ...(flags.expires ? { expires: flags.expires } : {}),
342
+ },
343
+ })));
344
+ console.error(`Published ${files.size} records as ${s.did}`);
345
+ }
346
+ await server.finished;
347
+ }
348
+ finally {
349
+ process.off("SIGINT", stop);
350
+ process.off("SIGTERM", stop);
351
+ await server.shutdown();
352
+ await files.dispose();
353
+ }
354
+ },
355
+ };
356
+ // Exit quietly when the reader closes the pipe, as in `fisl list | head`.
357
+ process.stdout.on("error", (e) => {
358
+ if (e.code === "EPIPE")
359
+ process.exit(0);
360
+ throw e;
361
+ });
362
+ const [name, ...rest] = process.argv.slice(2);
363
+ const command = Object.hasOwn(commands, name) ? commands[name] : undefined;
364
+ if (!command || rest.includes("--help")) {
365
+ console.log(USAGE);
366
+ process.exit(command || name === "help" || !name ? 0 : 1);
367
+ }
368
+ await command(rest);