@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,113 @@
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, rm, 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
+ const prev = files.get(cid);
55
+ files.set(cid, f);
56
+ if (prev)
57
+ await rm(prev.path, { force: true }).catch(() => { });
58
+ onFile?.(f);
59
+ }
60
+ };
61
+ try {
62
+ const results = await Promise.allSettled(Array.from({ length: Math.max(1, concurrency) }, worker));
63
+ const failed = results.find((r) => r.status === "rejected");
64
+ if (failed?.status === "rejected")
65
+ throw failed.reason;
66
+ return files;
67
+ }
68
+ catch (e) {
69
+ await files.dispose();
70
+ throw e;
71
+ }
72
+ }
73
+ const CORS = {
74
+ "access-control-allow-origin": "*",
75
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
76
+ };
77
+ /**
78
+ * A handler for RASL requests. Returns null for paths outside
79
+ * /.well-known/rasl/, so it can be combined with other handlers.
80
+ */
81
+ export function raslHandler(files) {
82
+ return async (req) => {
83
+ const { pathname } = new URL(req.url);
84
+ if (!pathname.startsWith(RASL_PREFIX))
85
+ return null;
86
+ if (req.method === "OPTIONS") {
87
+ return new Response(null, { status: 204, headers: CORS });
88
+ }
89
+ if (req.method !== "GET" && req.method !== "HEAD") {
90
+ return new Response("Method not allowed", { status: 405, headers: CORS });
91
+ }
92
+ const cid = pathname.slice(RASL_PREFIX.length);
93
+ if (!parseCid(cid)) {
94
+ return new Response("Not a DASL CID", { status: 400, headers: CORS });
95
+ }
96
+ const f = files.get(cid);
97
+ if (!f)
98
+ return new Response("Not found", { status: 404, headers: CORS });
99
+ const headers = {
100
+ ...CORS,
101
+ "content-type": "application/octet-stream",
102
+ "content-length": String(f.size),
103
+ // Content behind a CID never changes.
104
+ "cache-control": "public, max-age=31536000, immutable",
105
+ };
106
+ if (req.method === "HEAD")
107
+ return new Response(null, { headers });
108
+ const { createReadStream } = await import("node:fs");
109
+ const { Readable } = await import("node:stream");
110
+ const body = Readable.toWeb(createReadStream(f.path));
111
+ return new Response(body, { headers });
112
+ };
113
+ }
@@ -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
+ }).slice(0, 32);
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,78 @@
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
+ let request;
27
+ try {
28
+ request = toRequest(req, abort.signal);
29
+ }
30
+ catch {
31
+ res.statusCode = 400;
32
+ res.end("Bad request");
33
+ return;
34
+ }
35
+ try {
36
+ const response = await handler(request);
37
+ res.statusCode = response.status;
38
+ for (const [name, value] of response.headers) {
39
+ res.appendHeader(name, value);
40
+ }
41
+ if (!response.body || req.method === "HEAD") {
42
+ await response.body?.cancel();
43
+ res.end();
44
+ return;
45
+ }
46
+ await pipeline(Readable.fromWeb(response.body), res);
47
+ }
48
+ catch (e) {
49
+ // The client went away. Nothing to report.
50
+ if (abort.signal.aborted)
51
+ return;
52
+ if (!res.headersSent) {
53
+ console.error(e);
54
+ res.statusCode = 500;
55
+ res.end("Internal server error");
56
+ }
57
+ else {
58
+ res.destroy(e);
59
+ }
60
+ }
61
+ });
62
+ const finished = new Promise((resolve) => server.on("close", resolve));
63
+ return new Promise((resolve, reject) => {
64
+ server.once("error", reject);
65
+ server.listen(port, hostname, () => {
66
+ server.off("error", reject);
67
+ resolve({
68
+ port: server.address().port,
69
+ finished,
70
+ shutdown: () => {
71
+ server.close();
72
+ server.closeAllConnections();
73
+ return finished;
74
+ },
75
+ });
76
+ });
77
+ });
78
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
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.2.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
+ ],
33
+ "scripts": {
34
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/*-core.js src/*-core.d.ts dist/src/ && chmod +x dist/cli.js",
35
+ "check": "tsc",
36
+ "test": "node --test test/*.test.ts",
37
+ "fisl": "node cli.ts",
38
+ "prepack": "npm run build"
39
+ },
40
+ "dependencies": {
41
+ "@atproto/repo": "^0.11.1",
42
+ "@noble/hashes": "^2.4.0",
43
+ "multiformats": "13.4.2"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^26.6.5",
47
+ "@types/ws": "^8.18.2",
48
+ "typescript": "^7.0.2",
49
+ "ws": "^8.22.0"
50
+ }
51
+ }