@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,61 @@
1
+ // Verify a dev.fisl.at record against a signed commit (ATFISL indexing step 2).
2
+ //
3
+ // com.atproto.sync.getRecord returns a CAR with the signed commit and the
4
+ // MST path to the record, or a proof that the record does not exist.
5
+ import { def, MemoryBlockstore, MST, readCarWithRoot, verifyCommitSig, } from "@atproto/repo";
6
+ import { resolveIdentity, xrpc, XrpcError } from "../atproto.js";
7
+ import { NSID } from "../record.js";
8
+ /** Check a getRecord proof and extract the record and commit rev. */
9
+ export async function verifyProof(car, id, rkey, collection = NSID) {
10
+ if (!id.signingKey)
11
+ throw new Error(`${id.did} has no signing key`);
12
+ const { root, blocks } = await readCarWithRoot(car);
13
+ const store = new MemoryBlockstore(blocks);
14
+ const commit = await store.readObj(root, def.commit);
15
+ if (commit.did !== id.did)
16
+ throw new Error(`Commit is for ${commit.did}`);
17
+ if (!(await verifyCommitSig(commit, id.signingKey))) {
18
+ throw new Error(`Bad commit signature for ${id.did}`);
19
+ }
20
+ const leaf = await MST.load(store, commit.data).get(`${collection}/${rkey}`);
21
+ const record = leaf
22
+ ? (await store.readRecord(leaf))
23
+ : null;
24
+ return { record, rev: commit.rev };
25
+ }
26
+ /**
27
+ * Fetch and verify records from their PDS. Caches identities, and
28
+ * resolves again once if a proof fails, in case the key or PDS changed.
29
+ */
30
+ export class Verifier {
31
+ #ids = new Map();
32
+ async identity(did, fresh = false) {
33
+ let id = fresh ? undefined : this.#ids.get(did);
34
+ if (!id) {
35
+ id = await resolveIdentity(did);
36
+ this.#ids.set(did, id);
37
+ }
38
+ return id;
39
+ }
40
+ async verify(did, cid) {
41
+ try {
42
+ return await this.#fetch(await this.identity(did), cid);
43
+ }
44
+ catch {
45
+ return await this.#fetch(await this.identity(did, true), cid);
46
+ }
47
+ }
48
+ async #fetch(id, cid) {
49
+ try {
50
+ const car = await xrpc(id.pds, "com.atproto.sync.getRecord", { params: { did: id.did, collection: NSID, rkey: cid } });
51
+ return await verifyProof(car, id, cid);
52
+ }
53
+ catch (e) {
54
+ // Some PDSes answer with an error, not a proof of absence.
55
+ if (e instanceof XrpcError && e.error === "RecordNotFound") {
56
+ return { record: null };
57
+ }
58
+ throw e;
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,11 @@
1
+ import { type Session } from "./atproto.ts";
2
+ import { type AtfislRecord } from "./record.ts";
3
+ export interface Announcement {
4
+ cid: string;
5
+ record: AtfislRecord;
6
+ }
7
+ /**
8
+ * Publish one record per CID, replacing any existing record for that CID.
9
+ * Writes in batches of up to 200 records per commit.
10
+ */
11
+ export declare function publish(session: Session, items: Announcement[]): Promise<void>;
@@ -0,0 +1,24 @@
1
+ // Publish dev.fisl.at records for CIDs.
2
+ import { listRecords, putRecords } from "./atproto.js";
3
+ import { parseCid } from "./cid.js";
4
+ import { validate } from "./record.js";
5
+ const BATCH = 200;
6
+ /**
7
+ * Publish one record per CID, replacing any existing record for that CID.
8
+ * Writes in batches of up to 200 records per commit.
9
+ */
10
+ export async function publish(session, items) {
11
+ for (const { cid, record } of items) {
12
+ if (!parseCid(cid))
13
+ throw new Error(`Not a DASL CID: ${cid}`);
14
+ const errors = validate(record);
15
+ if (errors.length)
16
+ throw new Error(`${cid}: ${errors.join("; ")}`);
17
+ }
18
+ const existing = new Set();
19
+ for await (const r of listRecords(session))
20
+ existing.add(r.cid);
21
+ for (let i = 0; i < items.length; i += BATCH) {
22
+ await putRecords(session, items.slice(i, i + BATCH), existing);
23
+ }
24
+ }
@@ -0,0 +1,24 @@
1
+ export interface IndexedFile {
2
+ cid: string;
3
+ path: string;
4
+ /** Path relative to the served directory. */
5
+ name: string;
6
+ size: number;
7
+ }
8
+ /** Immutable snapshots owned by this index. Dispose after stopping the server. */
9
+ export declare class IndexedFiles extends Map<string, IndexedFile> {
10
+ readonly snapshotDir: string;
11
+ constructor(snapshotDir: string);
12
+ dispose(): Promise<void>;
13
+ }
14
+ export declare const RASL_PREFIX = "/.well-known/rasl/";
15
+ /** Hash every file in a directory. Files with the same content share a CID. */
16
+ export declare function indexDir(dir: string, { concurrency, onFile }?: {
17
+ concurrency?: number;
18
+ onFile?: (f: IndexedFile) => void;
19
+ }): Promise<IndexedFiles>;
20
+ /**
21
+ * A handler for RASL requests. Returns null for paths outside
22
+ * /.well-known/rasl/, so it can be combined with other handlers.
23
+ */
24
+ export declare function raslHandler(files: Map<string, IndexedFile>): (req: Request) => Promise<Response | null>;
@@ -0,0 +1,110 @@
1
+ // Serve a directory over RASL: GET|HEAD /.well-known/rasl/{cid}
2
+ // See https://dasl.ing/rasl.html
3
+ import { cidForFile, parseCid } from "../cid.js";
4
+ /** Immutable snapshots owned by this index. Dispose after stopping the server. */
5
+ export class IndexedFiles extends Map {
6
+ snapshotDir;
7
+ constructor(snapshotDir) {
8
+ super();
9
+ this.snapshotDir = snapshotDir;
10
+ }
11
+ async dispose() {
12
+ const { rm } = await import("node:fs/promises");
13
+ await rm(this.snapshotDir, { recursive: true, force: true });
14
+ this.clear();
15
+ }
16
+ }
17
+ export const RASL_PREFIX = "/.well-known/rasl/";
18
+ /** List the regular files in a directory tree, skipping dotfiles. */
19
+ async function* walk(dir) {
20
+ const { readdir } = await import("node:fs/promises");
21
+ const { join } = await import("node:path");
22
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
23
+ if (entry.name.startsWith("."))
24
+ continue;
25
+ const path = join(dir, entry.name);
26
+ if (entry.isDirectory())
27
+ yield* walk(path);
28
+ else if (entry.isFile())
29
+ yield path;
30
+ }
31
+ }
32
+ /** Hash every file in a directory. Files with the same content share a CID. */
33
+ export async function indexDir(dir, { concurrency = 4, onFile } = {}) {
34
+ const { copyFile, mkdtemp, stat } = await import("node:fs/promises");
35
+ const { join, relative } = await import("node:path");
36
+ const { tmpdir } = await import("node:os");
37
+ const snapshots = await mkdtemp(join(tmpdir(), "fisl-rasl-"));
38
+ const files = new IndexedFiles(snapshots);
39
+ const paths = walk(dir);
40
+ const worker = async () => {
41
+ for await (const path of paths) {
42
+ const snapshot = join(snapshots, crypto.randomUUID());
43
+ await copyFile(path, snapshot);
44
+ const [cid, info] = await Promise.all([
45
+ cidForFile(snapshot),
46
+ stat(snapshot),
47
+ ]);
48
+ const f = {
49
+ cid,
50
+ path: snapshot,
51
+ name: relative(dir, path),
52
+ size: info.size,
53
+ };
54
+ files.set(cid, f);
55
+ onFile?.(f);
56
+ }
57
+ };
58
+ try {
59
+ const results = await Promise.allSettled(Array.from({ length: Math.max(1, concurrency) }, worker));
60
+ const failed = results.find((r) => r.status === "rejected");
61
+ if (failed?.status === "rejected")
62
+ throw failed.reason;
63
+ return files;
64
+ }
65
+ catch (e) {
66
+ await files.dispose();
67
+ throw e;
68
+ }
69
+ }
70
+ const CORS = {
71
+ "access-control-allow-origin": "*",
72
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
73
+ };
74
+ /**
75
+ * A handler for RASL requests. Returns null for paths outside
76
+ * /.well-known/rasl/, so it can be combined with other handlers.
77
+ */
78
+ export function raslHandler(files) {
79
+ return async (req) => {
80
+ const { pathname } = new URL(req.url);
81
+ if (!pathname.startsWith(RASL_PREFIX))
82
+ return null;
83
+ if (req.method === "OPTIONS") {
84
+ return new Response(null, { status: 204, headers: CORS });
85
+ }
86
+ if (req.method !== "GET" && req.method !== "HEAD") {
87
+ return new Response("Method not allowed", { status: 405, headers: CORS });
88
+ }
89
+ const cid = pathname.slice(RASL_PREFIX.length);
90
+ if (!parseCid(cid)) {
91
+ return new Response("Not a DASL CID", { status: 400, headers: CORS });
92
+ }
93
+ const f = files.get(cid);
94
+ if (!f)
95
+ return new Response("Not found", { status: 404, headers: CORS });
96
+ const headers = {
97
+ ...CORS,
98
+ "content-type": "application/octet-stream",
99
+ "content-length": String(f.size),
100
+ // Content behind a CID never changes.
101
+ "cache-control": "public, max-age=31536000, immutable",
102
+ };
103
+ if (req.method === "HEAD")
104
+ return new Response(null, { headers });
105
+ const { createReadStream } = await import("node:fs");
106
+ const { Readable } = await import("node:stream");
107
+ const body = Readable.toWeb(createReadStream(f.path));
108
+ return new Response(body, { headers });
109
+ };
110
+ }
@@ -0,0 +1,8 @@
1
+ export const NSID: "dev.fisl.at";
2
+
3
+ export function isDatetime(v: unknown): v is string;
4
+ export function effectiveExpiry(
5
+ addr: { expires?: unknown; [key: string]: unknown },
6
+ record: { expires?: unknown; [key: string]: unknown },
7
+ ): number | null;
8
+ export function validate(r: unknown): string[];
@@ -0,0 +1,58 @@
1
+ export const NSID = "dev.fisl.at";
2
+ const DATETIME_RE =
3
+ /^[0-9]{4}-[01][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9](\.[0-9]{1,20})?(Z|[+-][0-2][0-9]:[0-5][0-9])$/;
4
+
5
+ export function isDatetime(v) {
6
+ return typeof v === "string" && DATETIME_RE.test(v) &&
7
+ !Number.isNaN(Date.parse(v));
8
+ }
9
+
10
+ /** The earliest of the addr's and the record's expiry, or null if neither has one. */
11
+ export function effectiveExpiry(
12
+ addr,
13
+ record,
14
+ ) {
15
+ const times = [addr.expires, record.expires].filter(isDatetime).map((t) =>
16
+ Date.parse(t)
17
+ );
18
+ return times.length ? Math.min(...times) : null;
19
+ }
20
+
21
+ /** Problems that make a record invalid for the Lexicon. Empty if valid. */
22
+ export function validate(r) {
23
+ const errors = [];
24
+ if (typeof r !== "object" || r === null || Array.isArray(r)) {
25
+ return ["record is not an object"];
26
+ }
27
+ const rec = r;
28
+ if (rec.$type !== undefined && rec.$type !== NSID) {
29
+ errors.push(`$type is ${rec.$type}, expected ${NSID}`);
30
+ }
31
+ if (!Array.isArray(rec.addrs)) {
32
+ errors.push("addrs must be an array");
33
+ } else {
34
+ if (rec.addrs.length < 1 || rec.addrs.length > 32) {
35
+ errors.push("addrs must hold 1 to 32 entries");
36
+ }
37
+ rec.addrs.forEach((a, i) => {
38
+ if (typeof a?.url !== "string") {
39
+ return errors.push(`addr ${i} has no url`);
40
+ }
41
+ if (!URL.canParse(a.url)) errors.push(`addr ${i} url is not absolute`);
42
+ if (a.url.length > 2048) errors.push(`addr ${i} url is over 2048 chars`);
43
+ if (a.expires !== undefined && !isDatetime(a.expires)) {
44
+ errors.push(`addr ${i} expires is not a datetime`);
45
+ }
46
+ });
47
+ }
48
+ if (
49
+ rec.size !== undefined &&
50
+ !(Number.isInteger(rec.size) && rec.size >= 0)
51
+ ) {
52
+ errors.push("size must be a non-negative integer");
53
+ }
54
+ if (rec.expires !== undefined && !isDatetime(rec.expires)) {
55
+ errors.push("expires is not a datetime");
56
+ }
57
+ return errors;
58
+ }
@@ -0,0 +1,35 @@
1
+ export { NSID } from "./record-core.js";
2
+ export interface Addr {
3
+ url: string;
4
+ expires?: string;
5
+ [key: string]: unknown;
6
+ }
7
+ /** A dev.fisl.at record. The record key is the CID; the record has no CID field. */
8
+ export interface AtfislRecord {
9
+ $type?: string;
10
+ addrs: Addr[];
11
+ size?: number;
12
+ expires?: string;
13
+ [key: string]: unknown;
14
+ }
15
+ /** One entry in a FISL response. */
16
+ export interface Location {
17
+ publisher?: string;
18
+ addrs: Addr[];
19
+ size?: number;
20
+ expires?: string;
21
+ [key: string]: unknown;
22
+ }
23
+ /**
24
+ * AT Protocol Lexicon datetime: RFC 3339 with a required timezone.
25
+ */
26
+ export { effectiveExpiry, isDatetime, validate } from "./record-core.js";
27
+ /**
28
+ * Apply ATFISL indexing step 4. Drop expired or malformed addrs, but keep
29
+ * addrs with unknown schemes. Returns null if the record must be discarded.
30
+ */
31
+ export declare function liveRecord(r: unknown, now?: number): AtfislRecord | null;
32
+ /** Turn a stored record into a FISL location entry. */
33
+ export declare function toLocation(rec: AtfislRecord, publisher?: string): Location;
34
+ /** Earliest expiry in a record (record or any addr), or null. */
35
+ export declare function earliestExpiry(rec: AtfislRecord): number | null;
@@ -0,0 +1,47 @@
1
+ // dev.fisl.at records (ATFISL) and FISL location entries.
2
+ // See specs/atfisl.md and specs/fisl.md.
3
+ // @ts-types="./record-core.d.ts"
4
+ export { NSID } from "./record-core.js";
5
+ /**
6
+ * AT Protocol Lexicon datetime: RFC 3339 with a required timezone.
7
+ */
8
+ // @ts-types="./record-core.d.ts"
9
+ export { effectiveExpiry, isDatetime, validate } from "./record-core.js";
10
+ // @ts-types="./record-core.d.ts"
11
+ import { effectiveExpiry, isDatetime } from "./record-core.js";
12
+ /**
13
+ * Apply ATFISL indexing step 4. Drop expired or malformed addrs, but keep
14
+ * addrs with unknown schemes. Returns null if the record must be discarded.
15
+ */
16
+ export function liveRecord(r, now = Date.now()) {
17
+ if (typeof r !== "object" || r === null)
18
+ return null;
19
+ const rec = r;
20
+ if (rec.expires !== undefined) {
21
+ if (!isDatetime(rec.expires) || Date.parse(rec.expires) <= now)
22
+ return null;
23
+ }
24
+ if (!Array.isArray(rec.addrs))
25
+ return null;
26
+ const addrs = rec.addrs.filter((a) => {
27
+ if (typeof a?.url !== "string" || !URL.canParse(a.url))
28
+ return false;
29
+ if (a.expires !== undefined && !isDatetime(a.expires))
30
+ return false;
31
+ const exp = effectiveExpiry(a, rec);
32
+ return exp === null || exp > now;
33
+ });
34
+ if (!addrs.length)
35
+ return null;
36
+ return { ...rec, addrs };
37
+ }
38
+ /** Turn a stored record into a FISL location entry. */
39
+ export function toLocation(rec, publisher) {
40
+ const { $type: _, ...rest } = rec;
41
+ return publisher ? { ...rest, publisher } : rest;
42
+ }
43
+ /** Earliest expiry in a record (record or any addr), or null. */
44
+ export function earliestExpiry(rec) {
45
+ const times = rec.addrs.map((a) => effectiveExpiry(a, rec)).filter((t) => t !== null);
46
+ return times.length ? Math.min(...times) : null;
47
+ }
@@ -0,0 +1,12 @@
1
+ export interface Server {
2
+ /** The port the server listens on. Useful with port 0. */
3
+ port: number;
4
+ /** Resolves when the server closes. */
5
+ finished: Promise<void>;
6
+ /** Stop accepting connections and close open ones. */
7
+ shutdown(): Promise<void>;
8
+ }
9
+ export declare function serve(handler: (req: Request) => Response | Promise<Response>, { port, hostname }?: {
10
+ port?: number;
11
+ hostname?: string;
12
+ }): Promise<Server>;
@@ -0,0 +1,69 @@
1
+ // Serve a fetch-style handler with node:http. Node only.
2
+ import { createServer } from "node:http";
3
+ import { Readable } from "node:stream";
4
+ import { pipeline } from "node:stream/promises";
5
+ function toRequest(req, signal) {
6
+ const headers = new Headers();
7
+ for (let i = 0; i < req.rawHeaders.length; i += 2) {
8
+ headers.append(req.rawHeaders[i], req.rawHeaders[i + 1]);
9
+ }
10
+ const host = req.headers.host ?? "localhost";
11
+ const url = new URL(req.url ?? "/", `http://${host}`);
12
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
13
+ return new Request(url, {
14
+ method: req.method,
15
+ headers,
16
+ signal,
17
+ body: hasBody ? Readable.toWeb(req) : null,
18
+ // Node needs this to stream a request body.
19
+ ...(hasBody ? { duplex: "half" } : {}),
20
+ });
21
+ }
22
+ export function serve(handler, { port = 0, hostname = "0.0.0.0" } = {}) {
23
+ const server = createServer(async (req, res) => {
24
+ const abort = new AbortController();
25
+ res.on("close", () => abort.abort());
26
+ try {
27
+ const response = await handler(toRequest(req, abort.signal));
28
+ res.statusCode = response.status;
29
+ for (const [name, value] of response.headers) {
30
+ res.appendHeader(name, value);
31
+ }
32
+ if (!response.body || req.method === "HEAD") {
33
+ await response.body?.cancel();
34
+ res.end();
35
+ return;
36
+ }
37
+ await pipeline(Readable.fromWeb(response.body), res);
38
+ }
39
+ catch (e) {
40
+ // The client went away. Nothing to report.
41
+ if (abort.signal.aborted)
42
+ return;
43
+ if (!res.headersSent) {
44
+ console.error(e);
45
+ res.statusCode = 500;
46
+ res.end("Internal server error");
47
+ }
48
+ else {
49
+ res.destroy(e);
50
+ }
51
+ }
52
+ });
53
+ const finished = new Promise((resolve) => server.on("close", resolve));
54
+ return new Promise((resolve, reject) => {
55
+ server.once("error", reject);
56
+ server.listen(port, hostname, () => {
57
+ server.off("error", reject);
58
+ resolve({
59
+ port: server.address().port,
60
+ finished,
61
+ shutdown: () => {
62
+ server.close();
63
+ server.closeAllConnections();
64
+ return finished;
65
+ },
66
+ });
67
+ });
68
+ });
69
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@dasl/fisl",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Publish, index, serve and fetch content by DASL CID, with FISL and ATFISL",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.13"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/mod.d.ts",
16
+ "default": "./dist/mod.js"
17
+ },
18
+ "./serve": {
19
+ "types": "./dist/src/serve.d.ts",
20
+ "default": "./dist/src/serve.js"
21
+ },
22
+ "./sqlite": {
23
+ "types": "./dist/src/index/sqlite.d.ts",
24
+ "default": "./dist/src/index/sqlite.js"
25
+ }
26
+ },
27
+ "bin": {
28
+ "fisl": "dist/cli.js"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "CLI.md"
33
+ ],
34
+ "scripts": {
35
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/*-core.js src/*-core.d.ts dist/src/ && chmod +x dist/cli.js",
36
+ "check": "tsc",
37
+ "test": "node --test test/*.test.ts",
38
+ "fisl": "node cli.ts",
39
+ "prepack": "npm run build"
40
+ },
41
+ "dependencies": {
42
+ "@atproto/repo": "^0.11.1",
43
+ "@noble/hashes": "^2.4.0",
44
+ "multiformats": "13.4.2"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^26.6.5",
48
+ "@types/ws": "^8.18.2",
49
+ "typescript": "^7.0.2",
50
+ "ws": "^8.22.0"
51
+ }
52
+ }