stanford-openarch 0.0.0 → 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.
- package/cli/check.js +467 -0
- package/cli/draft.js +75 -0
- package/cli/init.js +511 -0
- package/cli/mcp.js +302 -0
- package/cli/openarch.js +856 -0
- package/cli/pathCheck.js +114 -0
- package/cli/research.js +248 -0
- package/cli/safeFile.js +69 -0
- package/cli/ui.js +209 -0
- package/members/kit/README.md +215 -0
- package/members/kit/catalog.js +217 -0
- package/members/kit/csv.js +51 -0
- package/members/kit/index.js +286 -0
- package/members/kit/searchIndex.js +61 -0
- package/members/lib/fileSafety.js +35 -0
- package/members/lib/verifyQuote.js +210 -0
- package/package.json +22 -3
- package/protocol/MEMBERSHIP-AGREEMENT.md +105 -0
- package/protocol/OPENARCH-PROTOCOL.md +475 -0
- package/protocol/PARTNER-TERMS.md +43 -0
- package/server/lib/mcpTools.js +194 -0
- package/server/lib/readCapped.js +34 -0
- package/server/lib/vocabulary.js +177 -0
- package/README.md +0 -3
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// catalog.js — the member kit's data: openarch-member.json plus a catalog (CSV, TSV or
|
|
2
|
+
// JSONL) and the folder of files beside it, read into the documents an adapter serves.
|
|
3
|
+
//
|
|
4
|
+
// What a member brings is usually a spreadsheet and a folder (the newcomer walkthrough,
|
|
5
|
+
// 2026-11-26): one row per document, a column naming its file, perhaps a column naming
|
|
6
|
+
// its transcript. This turns that into documents, refusing — with the line and the fix —
|
|
7
|
+
// anything the protocol could not serve honestly: a duplicate or unsafe id, a file that is
|
|
8
|
+
// missing or outside the archive folder, a collection or terms id the manifest does not
|
|
9
|
+
// define. Withheld kinds are never loaded; counts cover only what is served (§4.7a).
|
|
10
|
+
import { readFileSync, existsSync, statSync, realpathSync, createReadStream, writeFileSync } from "node:fs";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { dirname, resolve, relative, extname, isAbsolute, sep, basename } from "node:path";
|
|
13
|
+
import { parseCsv } from "./csv.js";
|
|
14
|
+
import { MATERIAL_KINDS, SERVE_MODES, WITHHOLD_REASONS } from "../../server/lib/vocabulary.js";
|
|
15
|
+
|
|
16
|
+
export const LOCAL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/;
|
|
17
|
+
const KIND_BY_EXT = {
|
|
18
|
+
pdf: "pdf",
|
|
19
|
+
jpg: "image", jpeg: "image", png: "image", tif: "image", tiff: "image", gif: "image", webp: "image", jp2: "image",
|
|
20
|
+
mp4: "video", mov: "video", m4v: "video", webm: "video", avi: "video",
|
|
21
|
+
mp3: "audio", wav: "audio", m4a: "audio", flac: "audio", ogg: "audio",
|
|
22
|
+
xlsx: "spreadsheet", xls: "spreadsheet", xlsm: "spreadsheet", ods: "spreadsheet", csv: "spreadsheet",
|
|
23
|
+
eml: "email", msg: "email", mbox: "email",
|
|
24
|
+
txt: "text", html: "text", htm: "text", md: "text", docx: "text", doc: "text", rtf: "text",
|
|
25
|
+
json: "dataset", jsonl: "dataset", xml: "dataset", sqlite: "dataset", zip: "dataset",
|
|
26
|
+
};
|
|
27
|
+
const MEDIA_BY_EXT = {
|
|
28
|
+
pdf: "application/pdf", jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", tif: "image/tiff", tiff: "image/tiff", gif: "image/gif", webp: "image/webp", jp2: "image/jp2",
|
|
29
|
+
mp4: "video/mp4", mov: "video/quicktime", m4v: "video/mp4", webm: "video/webm", avi: "video/x-msvideo",
|
|
30
|
+
mp3: "audio/mpeg", wav: "audio/wav", m4a: "audio/mp4", flac: "audio/flac", ogg: "audio/ogg",
|
|
31
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xls: "application/vnd.ms-excel", xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12", ods: "application/vnd.oasis.opendocument.spreadsheet", csv: "text/csv",
|
|
32
|
+
eml: "message/rfc822", msg: "application/vnd.ms-outlook", mbox: "application/mbox",
|
|
33
|
+
txt: "text/plain; charset=utf-8", html: "text/html; charset=utf-8", htm: "text/html; charset=utf-8", md: "text/markdown; charset=utf-8",
|
|
34
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", doc: "application/msword", rtf: "application/rtf",
|
|
35
|
+
json: "application/json", jsonl: "application/x-ndjson", xml: "application/xml", sqlite: "application/vnd.sqlite3", zip: "application/zip",
|
|
36
|
+
};
|
|
37
|
+
export const kindOf = (path) => KIND_BY_EXT[extname(path).slice(1).toLowerCase()] ?? "dataset";
|
|
38
|
+
export const mediaTypeOf = (path) => MEDIA_BY_EXT[extname(path).slice(1).toLowerCase()] ?? "application/octet-stream";
|
|
39
|
+
const KIND_IDS = new Set(MATERIAL_KINDS.map((k) => k.id));
|
|
40
|
+
const MODE_IDS = new Set(SERVE_MODES.map((m) => m.id));
|
|
41
|
+
const REASON_IDS = new Set(WITHHOLD_REASONS.map((r) => r.id));
|
|
42
|
+
|
|
43
|
+
/** An http(s) address, or null: nothing else is ever rendered as a link (ind-sec PR #3 review, S3). */
|
|
44
|
+
export const httpOnly = (v) => { const t = String(v ?? "").trim(); return /^https?:\/\/[^\s"<>]+$/i.test(t) ? t : null; };
|
|
45
|
+
|
|
46
|
+
/** A page break in a text file (form feed, as pdftotext writes it) becomes the protocol's [[page N]] marker. */
|
|
47
|
+
export function markPages(text) {
|
|
48
|
+
const t = String(text).replace(/\r\n?/g, "\n");
|
|
49
|
+
if (/\[\[page \d+\]\]/.test(t)) return { text: t, pagesMarked: true, pages: (t.match(/\[\[page \d+\]\]/g) || []).length };
|
|
50
|
+
if (!t.includes("\f")) return { text: t, pagesMarked: false, pages: null };
|
|
51
|
+
const parts = t.split("\f");
|
|
52
|
+
while (parts.length > 1 && parts[parts.length - 1].trim() === "") parts.pop();
|
|
53
|
+
return { text: parts.map((p, i) => `[[page ${i + 1}]]\n${p.replace(/^\n+/, "")}`).join("\n"), pagesMarked: true, pages: parts.length };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
class ConfigError extends Error {}
|
|
57
|
+
const need = (cond, msg) => { if (!cond) throw new ConfigError(msg); };
|
|
58
|
+
|
|
59
|
+
/** Read and check openarch-member.json; returns the config with defaults filled. */
|
|
60
|
+
export function readConfig(configPath) {
|
|
61
|
+
const path = resolve(configPath);
|
|
62
|
+
need(existsSync(path), `No ${path}. Run openarch member init to write one.`);
|
|
63
|
+
let c;
|
|
64
|
+
try { c = JSON.parse(readFileSync(path, "utf8")); } catch (e) { throw new ConfigError(`${path} is not valid JSON: ${e.message}`); }
|
|
65
|
+
need(typeof c.member === "string" && /^[a-z0-9][a-z0-9-]{1,40}$/.test(c.member), `"member" must be your archive's short name: lowercase letters, digits and hyphens (e.g. "lakeside"). It prefixes every id you serve.`);
|
|
66
|
+
for (const k of ["name", "institution", "contact"]) need(typeof c[k] === "string" && c[k].trim(), `"${k}" is required.`);
|
|
67
|
+
need(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(c.contact), `"contact" must be an email address.`);
|
|
68
|
+
need(c.home === undefined || c.home === "" || httpOnly(c.home), `"home" is the archive's own website, an http(s) address.`);
|
|
69
|
+
need(typeof c.public_base === "string" && /^https?:\/\/[^/\s]+$/i.test(c.public_base.replace(/\/+$/, "")), `"public_base" is the address the hub will reach this adapter at, e.g. "https://archives.example.edu" (no path, no trailing slash).`);
|
|
70
|
+
c.public_base = c.public_base.replace(/\/+$/, "");
|
|
71
|
+
need(c.catalog && typeof c.catalog.path === "string", `"catalog.path" names your catalog file (CSV, TSV or JSONL), relative to ${path}.`);
|
|
72
|
+
c.catalog.columns = c.catalog.columns ?? {};
|
|
73
|
+
need(typeof c.catalog.columns.id === "string" && typeof c.catalog.columns.title === "string", `"catalog.columns" must name at least the id and title columns.`);
|
|
74
|
+
c.text = { kind: "ocr", ...(c.text ?? {}) };
|
|
75
|
+
need(["ocr", "born-digital", "transcript", "none"].includes(c.text.kind), `"text.kind" is one of ocr, born-digital, transcript, none.`);
|
|
76
|
+
need(c.terms && typeof c.terms === "object" && Object.keys(c.terms).length, `"terms" defines at least one reuse statement, e.g. { "public-record": { "label": "Public record", "reuse": "research-and-education" } }.`);
|
|
77
|
+
for (const [id, t] of Object.entries(c.terms)) need(t && t.label && (t.reuse || t.url), `terms "${id}" needs a label and a reuse statement or url.`);
|
|
78
|
+
need(Array.isArray(c.collections) && c.collections.length, `"collections" lists at least one collection: { "id": "${c.member}/<name>", "title": "…", "terms": "<a terms id>" }.`);
|
|
79
|
+
for (const col of c.collections) {
|
|
80
|
+
need(typeof col.id === "string" && col.id.startsWith(`${c.member}/`) && /^[a-z0-9][a-z0-9/_-]*$/.test(col.id), `collection id "${col.id}" must start with "${c.member}/" (lowercase, digits, -, _).`);
|
|
81
|
+
need(col.title, `collection "${col.id}" needs a title.`);
|
|
82
|
+
need(c.terms[col.terms], `collection "${col.id}" names terms "${col.terms}", which "terms" does not define.`);
|
|
83
|
+
}
|
|
84
|
+
need(c.collections.length === 1 || c.catalog.columns.collection, `With more than one collection, "catalog.columns.collection" names the column that says which collection a row belongs to.`);
|
|
85
|
+
for (const k of ["rights", "permalinks", "agreement", "sharing"]) need(c[k] && typeof c[k] === "object", `"${k}" is missing: run openarch member init, which asks for the declarations.`);
|
|
86
|
+
for (const [k, m] of Object.entries(c.sharing.share ?? {})) need(KIND_IDS.has(k) && MODE_IDS.has(m), `sharing.share.${k} = ${JSON.stringify(m)}: kinds are ${[...KIND_IDS].join(", ")}; modes ${[...MODE_IDS].join(", ")}.`);
|
|
87
|
+
for (const [k, r] of Object.entries(c.sharing.withhold ?? {})) need(KIND_IDS.has(k) && REASON_IDS.has(r), `sharing.withhold.${k} = ${JSON.stringify(r)}: reasons are ${[...REASON_IDS].join(", ")}.`);
|
|
88
|
+
// permalinks: the member's own site ({id} in its pattern), or the kit's page at public_base/view/{id}
|
|
89
|
+
if (!c.permalinks.pattern) c.permalinks.pattern = `${c.public_base}/view/{id}`;
|
|
90
|
+
need(String(c.permalinks.pattern).includes("{id}"), `permalinks.pattern must contain {id}.`);
|
|
91
|
+
c.serves_view = c.permalinks.pattern === `${c.public_base}/view/{id}`;
|
|
92
|
+
c.limits = { search_results_max: 50, document_bytes_max: 2_000_000, ...(c.limits ?? {}) };
|
|
93
|
+
c.__dir = dirname(path);
|
|
94
|
+
c.__path = path;
|
|
95
|
+
return c;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const sha256File = (path) => new Promise((ok, no) => { const h = createHash("sha256"); createReadStream(path).on("data", (d) => h.update(d)).on("end", () => ok(h.digest("hex"))).on("error", no); });
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Load the catalog into documents. Throws a ConfigError listing every problem (up to 20),
|
|
102
|
+
* so a member fixes the spreadsheet once rather than one error per run.
|
|
103
|
+
* @returns {Promise<{docs: Map<string, object>, skipped: {withheld: number, notHeld: number}, warnings: string[]}>}
|
|
104
|
+
*/
|
|
105
|
+
export async function loadCatalog(c, { log = () => {} } = {}) {
|
|
106
|
+
const catPath = resolve(c.__dir, c.catalog.path);
|
|
107
|
+
need(existsSync(catPath), `The catalog ${catPath} does not exist (catalog.path in ${c.__path}).`);
|
|
108
|
+
const root = realpathSync(resolve(c.__dir, c.catalog.files_root ?? dirname(c.catalog.path)));
|
|
109
|
+
const raw = readFileSync(catPath, "utf8");
|
|
110
|
+
let rows, header;
|
|
111
|
+
if (/\.jsonl?$/i.test(catPath)) {
|
|
112
|
+
rows = []; const problems = [];
|
|
113
|
+
raw.split(/\r?\n/).forEach((l, i) => { if (!l.trim()) return; try { const o = JSON.parse(l); Object.defineProperty(o, "__line", { value: i + 1 }); rows.push(o); } catch (e) { problems.push(`line ${i + 1}: not JSON (${e.message})`); } });
|
|
114
|
+
need(!problems.length, `${catPath}:\n ${problems.slice(0, 20).join("\n ")}`);
|
|
115
|
+
header = [...new Set(rows.flatMap((r) => Object.keys(r)))];
|
|
116
|
+
} else {
|
|
117
|
+
const p = parseCsv(raw);
|
|
118
|
+
need(!p.problems.length, `${catPath}:\n ${p.problems.slice(0, 20).join("\n ")}`);
|
|
119
|
+
rows = p.rows; header = p.header;
|
|
120
|
+
}
|
|
121
|
+
const col = c.catalog.columns;
|
|
122
|
+
const missingCols = Object.entries(col).filter(([, name]) => typeof name === "string" && !header.includes(name));
|
|
123
|
+
need(!missingCols.length, `${catPath} has no column ${missingCols.map(([k, n]) => `"${n}" (catalog.columns.${k})`).join(", ")}. Its columns are: ${header.join(", ")}.`);
|
|
124
|
+
|
|
125
|
+
// the sha256 of each file, cached by path, size and modification time so a restart is quick
|
|
126
|
+
const cachePath = resolve(process.env.OPENARCH_CACHE_DIR || c.__dir, ".openarch-cache.json");
|
|
127
|
+
let cache = {}; try { cache = JSON.parse(readFileSync(cachePath, "utf8")); } catch { cache = {}; }
|
|
128
|
+
const nextCache = {};
|
|
129
|
+
const share = c.sharing.share ?? {}, withhold = c.sharing.withhold ?? {};
|
|
130
|
+
const byMatch = new Map(c.collections.map((x) => [String(x.match ?? x.title).trim().toLowerCase(), x]));
|
|
131
|
+
const docs = new Map(), problems = [], warnings = [], pageMismatch = [];
|
|
132
|
+
let withheld = 0, notHeld = 0;
|
|
133
|
+
const safePath = (p, line, what) => {
|
|
134
|
+
if (!p) return null;
|
|
135
|
+
const abs = isAbsolute(p) ? p : resolve(dirname(catPath), p);
|
|
136
|
+
if (!existsSync(abs)) { problems.push(`line ${line}: ${what} ${p} does not exist`); return null; }
|
|
137
|
+
const real = realpathSync(abs);
|
|
138
|
+
if (real !== root && !real.startsWith(root + sep)) { problems.push(`line ${line}: ${what} ${p} is outside the archive folder ${root}`); return null; }
|
|
139
|
+
// never the member's own files (.env, the application's receipt) or any dotfile (review nit)
|
|
140
|
+
if (relative(root, real).split(sep).some((part) => part.startsWith("."))) { problems.push(`line ${line}: ${what} ${p} is a hidden file; the archive serves no dotfiles`); return null; }
|
|
141
|
+
if (dirname(real) === realpathSync(c.__dir) && /^(openarch-member\.json|index\.js|package(-lock)?\.json)$/.test(basename(real))) { problems.push(`line ${line}: ${what} ${p} is one of the adapter's own files`); return null; }
|
|
142
|
+
return real;
|
|
143
|
+
};
|
|
144
|
+
for (const r of rows) {
|
|
145
|
+
const line = r.__line;
|
|
146
|
+
const id = String(r[col.id] ?? "").trim();
|
|
147
|
+
if (!LOCAL_ID_RE.test(id)) { problems.push(`line ${line}: id ${JSON.stringify(id)} — use letters, digits, ".", "_", "~" or "-" (no spaces or slashes), up to 128`); continue; }
|
|
148
|
+
if (docs.has(id)) { problems.push(`line ${line}: id ${id} repeats an earlier row`); continue; }
|
|
149
|
+
const title = String(r[col.title] ?? "").trim();
|
|
150
|
+
if (!title) { problems.push(`line ${line}: ${id} has no title`); continue; }
|
|
151
|
+
// its collection
|
|
152
|
+
let collection = c.collections[0];
|
|
153
|
+
if (c.collections.length > 1 || col.collection) {
|
|
154
|
+
const v = String(r[col.collection] ?? "").trim().toLowerCase();
|
|
155
|
+
collection = byMatch.get(v) ?? (c.collections.length === 1 ? c.collections[0] : null);
|
|
156
|
+
if (!collection) { problems.push(`line ${line}: ${id}'s collection ${JSON.stringify(r[col.collection])} matches no collection's "match" or title`); continue; }
|
|
157
|
+
}
|
|
158
|
+
// its files, and the kind that decides what is shared
|
|
159
|
+
const filePaths = col.file ? String(r[col.file] ?? "").split(";").map((x) => x.trim()).filter(Boolean) : [];
|
|
160
|
+
const files = [];
|
|
161
|
+
for (const [k, fp] of filePaths.entries()) {
|
|
162
|
+
const real = safePath(fp, line, "file");
|
|
163
|
+
if (!real) continue;
|
|
164
|
+
files.push({ file_id: k === 0 ? "primary" : `file-${k + 1}`, role: k === 0 ? "primary" : "attachment", kind: kindOf(real), media_type: mediaTypeOf(real), path: real });
|
|
165
|
+
}
|
|
166
|
+
const kind = files[0]?.kind ?? ((col.kind ? String(r[col.kind] ?? "").trim() : "") || c.default_kind || "text");
|
|
167
|
+
if (withhold[kind]) { withheld++; continue; }
|
|
168
|
+
if (!share[kind]) { notHeld++; continue; }
|
|
169
|
+
// its text: a path to a text file, or the text itself. A kind shared as metadata only is
|
|
170
|
+
// never read at all: text that is loaded is indexed, and a phrase search against it would
|
|
171
|
+
// confirm the withheld words one guess at a time (ind-sec PR #3 review, B3)
|
|
172
|
+
let text = "";
|
|
173
|
+
if (c.text.kind !== "none" && col.text && share[kind] !== "metadata") {
|
|
174
|
+
const v = String(r[col.text] ?? "");
|
|
175
|
+
if ((c.text.from ?? "file") === "file") { const real = v.trim() ? safePath(v.trim(), line, "text file") : null; text = real ? readFileSync(real, "utf8") : ""; }
|
|
176
|
+
else text = v;
|
|
177
|
+
}
|
|
178
|
+
let marked = markPages(text);
|
|
179
|
+
const catPages = col.pages ? Number.parseInt(String(r[col.pages] ?? ""), 10) || null : null;
|
|
180
|
+
// Form feeds that disagree with the catalog's own page count are not page breaks to trust:
|
|
181
|
+
// serving them as [[page N]] would cut a 41-page letter into "3 pages" mid-sentence, and a
|
|
182
|
+
// partner citing or paying by page would get the wrong page (walkthrough 3, 2026-11-26).
|
|
183
|
+
if (marked.pagesMarked && catPages && marked.pages !== catPages && !/\[\[page \d+\]\]/.test(text)) {
|
|
184
|
+
pageMismatch.push(`line ${line} (${id}): ${marked.pages} page${marked.pages === 1 ? "" : "s"} by its text's form feeds, ${catPages} by the catalog`);
|
|
185
|
+
marked = { text: String(text).replace(/\r\n?/g, "\n").replace(/\f/g, "\n\n"), pagesMarked: false, pages: null };
|
|
186
|
+
}
|
|
187
|
+
const authorsRaw = col.authors ? String(r[col.authors] ?? "") : "";
|
|
188
|
+
docs.set(id, {
|
|
189
|
+
id, title, collection: collection.id, terms: collection.terms, kind, mode: share[kind],
|
|
190
|
+
date: col.date ? (String(r[col.date] ?? "").trim() || null) : null,
|
|
191
|
+
authors: authorsRaw.split(c.catalog.authors_separator ?? ";").map((a) => a.trim()).filter(Boolean),
|
|
192
|
+
type: col.type ? (String(r[col.type] ?? "").trim() || null) : null,
|
|
193
|
+
// only http(s) addresses become links: a javascript: URL in a catalog cell would run on the page (S3)
|
|
194
|
+
source_url: col.source_url ? httpOnly(r[col.source_url]) : null,
|
|
195
|
+
permalink_override: col.permalink ? httpOnly(r[col.permalink]) : null,
|
|
196
|
+
text: marked.text, pages_marked: marked.pagesMarked, pages: marked.pages ?? catPages,
|
|
197
|
+
files: share[kind] === "files" ? files : [],
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
need(!problems.length, `${catPath}: ${problems.length} problem${problems.length === 1 ? "" : "s"}:\n ${problems.slice(0, 20).join("\n ")}${problems.length > 20 ? `\n … and ${problems.length - 20} more` : ""}`);
|
|
201
|
+
// checksums, after the catalog is known to be sound
|
|
202
|
+
for (const d of docs.values()) for (const f of d.files) {
|
|
203
|
+
const st = statSync(f.path);
|
|
204
|
+
const key = `${f.path}\t${st.size}\t${st.mtimeMs}\t${st.ino}\t${st.ctimeMs}`;
|
|
205
|
+
f.bytes = st.size;
|
|
206
|
+
f.dev = st.dev; f.ino = st.ino; // what is served must still be this file (S5)
|
|
207
|
+
f.sha256 = cache[key] ?? await sha256File(f.path);
|
|
208
|
+
nextCache[key] = f.sha256;
|
|
209
|
+
}
|
|
210
|
+
try { writeFileSync(cachePath, JSON.stringify(nextCache)); } catch (e) { warnings.push(`could not write ${cachePath} (${e.message}); checksums are recomputed at each start`); }
|
|
211
|
+
if (pageMismatch.length) warnings.push(`${pageMismatch.length} document(s) whose text's page breaks disagree with the catalog's page count are served whole, without page markers, with the catalog's count: ${pageMismatch.slice(0, 5).join("; ")}${pageMismatch.length > 5 ? `; … and ${pageMismatch.length - 5} more` : ""}`);
|
|
212
|
+
if (notHeld) warnings.push(`${notHeld} row(s) are of a kind your sharing grid does not list, so they are not served (add the kind to sharing.share or sharing.withhold)`);
|
|
213
|
+
log(`openarch member kit: ${docs.size} document(s) loaded from ${relative(process.cwd(), catPath) || catPath}${withheld ? ` · ${withheld} withheld` : ""}${notHeld ? ` · ${notHeld} of an unlisted kind` : ""}`);
|
|
214
|
+
return { docs, skipped: { withheld, notHeld }, warnings };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export { ConfigError };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// csv.js — the member kit's CSV reader (RFC 4180, as spreadsheets export it).
|
|
2
|
+
// Handles a byte-order mark, CRLF or LF line ends, quoted fields with commas,
|
|
3
|
+
// quotes ("") and line breaks inside them, and a trailing blank line. A row with
|
|
4
|
+
// more cells than the header is reported, never silently trimmed.
|
|
5
|
+
//
|
|
6
|
+
// parseCsv(text) → { header: string[], rows: Array<Record<string,string>>, problems: string[] }
|
|
7
|
+
|
|
8
|
+
export function parseCsv(text, { delimiter } = {}) {
|
|
9
|
+
let s = String(text);
|
|
10
|
+
if (s.charCodeAt(0) === 0xfeff) s = s.slice(1);
|
|
11
|
+
// a spreadsheet saved as "tab separated" is common enough to detect from the header line
|
|
12
|
+
const firstLine = s.slice(0, s.search(/\r?\n|$/));
|
|
13
|
+
const d = delimiter ?? (firstLine.includes("\t") && !firstLine.includes(",") ? "\t" : firstLine.includes(";") && !firstLine.includes(",") ? ";" : ",");
|
|
14
|
+
const records = [];
|
|
15
|
+
let row = [], field = "", i = 0, quoted = false, line = 1, rowLine = 1;
|
|
16
|
+
const problems = [];
|
|
17
|
+
const endField = () => { row.push(field); field = ""; };
|
|
18
|
+
const endRow = () => { endField(); records.push({ cells: row, line: rowLine }); row = []; rowLine = line; };
|
|
19
|
+
while (i < s.length) {
|
|
20
|
+
const c = s[i];
|
|
21
|
+
if (quoted) {
|
|
22
|
+
if (c === '"') {
|
|
23
|
+
if (s[i + 1] === '"') { field += '"'; i += 2; continue; }
|
|
24
|
+
quoted = false; i++; continue;
|
|
25
|
+
}
|
|
26
|
+
if (c === "\n") line++;
|
|
27
|
+
field += c; i++; continue;
|
|
28
|
+
}
|
|
29
|
+
if (c === '"' && field === "") { quoted = true; i++; continue; }
|
|
30
|
+
if (c === d) { endField(); i++; continue; }
|
|
31
|
+
if (c === "\r" && s[i + 1] === "\n") { line++; endRow(); i += 2; continue; }
|
|
32
|
+
if (c === "\n" || c === "\r") { line++; endRow(); i++; continue; }
|
|
33
|
+
field += c; i++;
|
|
34
|
+
}
|
|
35
|
+
if (quoted) problems.push(`line ${rowLine}: a quoted field never closes`);
|
|
36
|
+
if (field !== "" || row.length) endRow();
|
|
37
|
+
const nonEmpty = records.filter((r) => r.cells.some((x) => x.trim() !== ""));
|
|
38
|
+
if (!nonEmpty.length) return { header: [], rows: [], problems: ["the file is empty"], delimiter: d };
|
|
39
|
+
const header = nonEmpty[0].cells.map((h) => h.trim());
|
|
40
|
+
const seen = new Set();
|
|
41
|
+
for (const h of header) { if (!h) problems.push("the header has an empty column name"); else if (seen.has(h)) problems.push(`the header repeats the column "${h}"`); seen.add(h); }
|
|
42
|
+
const rows = [];
|
|
43
|
+
for (const r of nonEmpty.slice(1)) {
|
|
44
|
+
if (r.cells.length > header.length && r.cells.slice(header.length).some((x) => x.trim() !== "")) problems.push(`line ${r.line}: ${r.cells.length} cells for ${header.length} columns`);
|
|
45
|
+
const o = {};
|
|
46
|
+
header.forEach((h, k) => { o[h] = (r.cells[k] ?? "").trim(); });
|
|
47
|
+
Object.defineProperty(o, "__line", { value: r.line, enumerable: false });
|
|
48
|
+
rows.push(o);
|
|
49
|
+
}
|
|
50
|
+
return { header, rows, problems, delimiter: d };
|
|
51
|
+
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
// members/kit — an openarch member from a configuration file (protocol §4, §7).
|
|
2
|
+
//
|
|
3
|
+
// import { startMember } from "stanford-openarch/member-kit";
|
|
4
|
+
// await startMember("openarch-member.json");
|
|
5
|
+
//
|
|
6
|
+
// `openarch member init` writes openarch-member.json, a three-line index.js that calls
|
|
7
|
+
// startMember, a .env and the deploy files. The kit serves the protocol from the
|
|
8
|
+
// member's catalog and files (members/kit/catalog.js): manifest, search, documents
|
|
9
|
+
// (text, page ranges), citations, quote verification and — for the kinds the sharing
|
|
10
|
+
// grid shares as files — the files. A member updates the kit by updating its package,
|
|
11
|
+
// stanford-openarch; its own code stays three lines. A member whose holdings live in a
|
|
12
|
+
// database passes its own `load` function (see members/kit/README.md).
|
|
13
|
+
//
|
|
14
|
+
// Environment:
|
|
15
|
+
// PORT (3101) · HOST (127.0.0.1; 0.0.0.0 inside a container)
|
|
16
|
+
// OPENARCH_HUB_CREDENTIAL_SHA256 the SHA-256 (hex) of the credential the hub presents
|
|
17
|
+
// OPENARCH_HUB_CREDENTIAL or the credential itself (hashed at start, never logged)
|
|
18
|
+
// OPENARCH_DEV=1 no credential: open to any caller (development only)
|
|
19
|
+
// Without a credential and without OPENARCH_DEV=1, every protocol call but the manifest
|
|
20
|
+
// answers 503: a member is never open by accident (P3 #26). The public pages (/, /view/<id>,
|
|
21
|
+
// /robots.txt, /healthz) need no credential; /view shows a document's record and citation,
|
|
22
|
+
// and its text only when the member opts in (ind-sec PR #3 review, S2).
|
|
23
|
+
import express from "express";
|
|
24
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
25
|
+
import { createReadStream, readFileSync, watch, openSync, fstatSync, closeSync, constants as FS } from "node:fs";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
import { readConfig, loadCatalog, ConfigError, httpOnly } from "./catalog.js";
|
|
28
|
+
import { buildIndex, search, snippet } from "./searchIndex.js";
|
|
29
|
+
import { fold, buildFoldedIndex, verifyQuoteAgainstFolded, withVerbatimSpan } from "../lib/verifyQuote.js";
|
|
30
|
+
import { fileHeaders } from "../lib/fileSafety.js";
|
|
31
|
+
import { extname } from "node:path";
|
|
32
|
+
|
|
33
|
+
export const KIT_VERSION = JSON.parse(readFileSync(fileURLToPath(new URL("../../package.json", import.meta.url)), "utf8")).version;
|
|
34
|
+
const PROTOCOL = "0.1";
|
|
35
|
+
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
|
|
36
|
+
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
37
|
+
const tokensOf = (text) => (text ? Math.ceil(text.length / 4) : null);
|
|
38
|
+
|
|
39
|
+
/** The member's state: config, documents, index. Rebuilt whole on a reload, swapped at once. */
|
|
40
|
+
async function loadState(configPath, { log }) {
|
|
41
|
+
const config = readConfig(configPath);
|
|
42
|
+
const { docs, warnings } = await loadCatalog(config, { log });
|
|
43
|
+
for (const w of warnings) log(`warning: ${w}`);
|
|
44
|
+
return { config, docs, index: buildIndex(docs), folded: new Map(), loadedAt: new Date().toISOString() };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function manifestOf({ config: c, docs }) {
|
|
48
|
+
const counts = new Map();
|
|
49
|
+
for (const d of docs.values()) counts.set(d.collection, (counts.get(d.collection) ?? 0) + 1);
|
|
50
|
+
const anyFiles = [...docs.values()].some((d) => d.files.length);
|
|
51
|
+
const anyPages = [...docs.values()].some((d) => d.pages_marked);
|
|
52
|
+
return {
|
|
53
|
+
protocol: PROTOCOL, member: c.member, name: c.name, institution: c.institution, contact: c.contact,
|
|
54
|
+
...(c.home ? { home: c.home } : {}), ...(c.logo ? { logo: c.logo } : {}), ...(c.terms_statement ? { terms_statement: c.terms_statement } : {}),
|
|
55
|
+
capabilities: ["search", "documents", "citations", "verify_quote", ...(anyFiles ? ["files"] : []), ...(anyPages ? ["page_ranges"] : [])],
|
|
56
|
+
collections: c.collections.map((col) => ({ id: col.id, title: col.title, documents: counts.get(col.id) ?? 0, terms: col.terms, ...(col.description ? { description: col.description } : {}) })),
|
|
57
|
+
terms: c.terms,
|
|
58
|
+
limits: c.limits,
|
|
59
|
+
permalink_base: c.permalinks.pattern,
|
|
60
|
+
search_syntax: 'plain words must all appear; "a quoted phrase" must appear as written',
|
|
61
|
+
rights: c.rights, permalinks: c.permalinks, agreement: c.agreement, sharing: c.sharing,
|
|
62
|
+
software: `openarch-member-kit/${KIT_VERSION}`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const permalinkOf = (c, d) => d.permalink_override || c.permalinks.pattern.replace("{id}", encodeURIComponent(d.id));
|
|
67
|
+
const fileUrl = (c, d, f) => `${c.public_base}/openarch/v1/documents/${encodeURIComponent(d.id)}/files/${encodeURIComponent(f.file_id)}`;
|
|
68
|
+
|
|
69
|
+
function citationOf(c, d, style) {
|
|
70
|
+
const url = permalinkOf(c, d);
|
|
71
|
+
const authors = d.authors.length ? d.authors.join(", ") : null;
|
|
72
|
+
const date = d.date || "n.d.";
|
|
73
|
+
const year = /^\d{4}/.test(d.date ?? "") ? d.date.slice(0, 4) : "n.d.";
|
|
74
|
+
const where = `${c.name}, ${c.institution}`;
|
|
75
|
+
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
|
76
|
+
const apaDate = (() => { const m = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?/.exec(d.date ?? ""); if (!m) return "n.d."; return [m[1], m[2] ? `${MONTHS[Number(m[2]) - 1]}${m[3] ? ` ${Number(m[3])}` : ""}` : null].filter(Boolean).join(", "); })();
|
|
77
|
+
switch (style) {
|
|
78
|
+
case "chicago": return `${authors ? `${authors}. ` : ""}"${d.title}." ${date}. ${where}. ${url}.`;
|
|
79
|
+
case "mla": return `${authors ? `${authors}. ` : ""}"${d.title}." ${c.name}, ${c.institution}, ${date}, ${url}.`;
|
|
80
|
+
case "bibtex": return `@misc{${c.member}_${d.id.replace(/[^A-Za-z0-9]/g, "_")}, ${authors ? `author={${authors}}, ` : ""}title={${d.title}}, year={${year}}, howpublished={${where}}, url={${url}}}`;
|
|
81
|
+
default: return authors ? `${authors}. (${apaDate}). ${d.title}. ${where}. ${url}` : `${d.title}. (${apaDate}). ${where}. ${url}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** ?pages=3-5,8 → [3,4,5,8], or null for a malformed range. */
|
|
86
|
+
function parsePages(spec) {
|
|
87
|
+
const out = new Set();
|
|
88
|
+
for (const part of String(spec).split(",")) {
|
|
89
|
+
const m = /^\s*(\d{1,5})\s*(?:-\s*(\d{1,5}))?\s*$/.exec(part);
|
|
90
|
+
if (!m) return null;
|
|
91
|
+
const a = Number(m[1]), b = Number(m[2] ?? m[1]);
|
|
92
|
+
if (a < 1 || b < a || b - a > 10_000) return null;
|
|
93
|
+
for (let p = a; p <= b; p++) out.add(p);
|
|
94
|
+
}
|
|
95
|
+
return [...out].sort((x, y) => x - y);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Cut a UTF-8 string to at most `max` bytes without splitting a character. */
|
|
99
|
+
function capBytes(text, max) {
|
|
100
|
+
const b = Buffer.from(text);
|
|
101
|
+
if (b.length <= max) return { text, truncated: false };
|
|
102
|
+
let end = max;
|
|
103
|
+
while (end > 0 && (b[end] & 0xc0) === 0x80) end--;
|
|
104
|
+
return { text: b.subarray(0, end).toString("utf8"), truncated: true };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createMember(stateRef, { hubCredentialSha256 = null, dev = false, log = null } = {}) {
|
|
108
|
+
const app = express();
|
|
109
|
+
app.disable("x-powered-by");
|
|
110
|
+
app.set("trust proxy", false);
|
|
111
|
+
// One line per call: when, what, the answer, how long. The path only — a search's words are
|
|
112
|
+
// the partner's and stay out of the log. OPENARCH_LOG=0 silences it.
|
|
113
|
+
if (log && process.env.OPENARCH_LOG !== "0") app.use((req, res, next) => {
|
|
114
|
+
const t0 = Date.now(), path = req.originalUrl.split("?")[0];
|
|
115
|
+
res.on("finish", () => { if (path !== "/healthz") log(`${new Date().toISOString()} ${req.method} ${path} ${res.statusCode} ${Date.now() - t0}ms${res.statusCode === 401 ? " (refused: not the hub's credential)" : ""}`); });
|
|
116
|
+
next();
|
|
117
|
+
});
|
|
118
|
+
app.use(express.json({ limit: "64kb", inflate: false }));
|
|
119
|
+
const S = () => stateRef.current;
|
|
120
|
+
const want = hubCredentialSha256 ? Buffer.from(hubCredentialSha256, "hex") : null;
|
|
121
|
+
const fromHub = (req) => { if (!want) return false; const tok = (req.get("authorization") || "").replace(/^Bearer\s+/i, ""); return Boolean(tok) && timingSafeEqual(Buffer.from(sha256(tok), "hex"), want); };
|
|
122
|
+
const gate = (req, res, next) => {
|
|
123
|
+
if (!want) return dev ? next() : res.status(503).json({ error: "no_credential", message: "This member has no hub credential configured; it answers no one until it has (set OPENARCH_HUB_CREDENTIAL, or OPENARCH_DEV=1 for development)." });
|
|
124
|
+
const tok = (req.get("authorization") || "").replace(/^Bearer\s+/i, "");
|
|
125
|
+
const got = Buffer.from(sha256(tok), "hex");
|
|
126
|
+
if (!tok || !timingSafeEqual(got, want)) return res.status(401).json({ error: "unauthorized", message: "This member answers only the openarch hub." });
|
|
127
|
+
next();
|
|
128
|
+
};
|
|
129
|
+
const getDoc = (raw) => {
|
|
130
|
+
const s = S(), id = String(raw ?? "");
|
|
131
|
+
const local = id.startsWith(`${s.config.member}/`) ? id.slice(s.config.member.length + 1) : id;
|
|
132
|
+
return s.docs.get(local) ?? null;
|
|
133
|
+
};
|
|
134
|
+
const textOf = (d) => (d.mode === "metadata" ? "" : d.text);
|
|
135
|
+
|
|
136
|
+
const r = express.Router();
|
|
137
|
+
r.get("/manifest", (_req, res) => res.json(manifestOf(S())));
|
|
138
|
+
r.get("/search", gate, (req, res) => {
|
|
139
|
+
const s = S(), c = s.config;
|
|
140
|
+
const q = String(req.query.q ?? "").trim();
|
|
141
|
+
if (!q) return res.status(400).json({ error: "bad_request", message: "q is required" });
|
|
142
|
+
const limit = Math.min(Math.max(Number.parseInt(String(req.query.limit ?? "25"), 10) || 25, 1), c.limits.search_results_max);
|
|
143
|
+
let offset = 0;
|
|
144
|
+
if (req.query.cursor) {
|
|
145
|
+
const m = /^o:(\d{1,9})$/.exec(Buffer.from(String(req.query.cursor), "base64url").toString("utf8"));
|
|
146
|
+
if (!m) return res.status(400).json({ error: "bad_cursor", message: "cursor is not one this member returned" });
|
|
147
|
+
offset = Number(m[1]);
|
|
148
|
+
}
|
|
149
|
+
const collection = req.query.collection ? String(req.query.collection) : null;
|
|
150
|
+
const { total, ids } = search(s.index, s.docs, q, { collection, limit, offset });
|
|
151
|
+
const next = offset + ids.length < total ? Buffer.from(`o:${offset + ids.length}`).toString("base64url") : null;
|
|
152
|
+
res.json({
|
|
153
|
+
total, total_is_estimate: false, cursor: next,
|
|
154
|
+
results: ids.map((id) => s.docs.get(id)).map((d) => ({
|
|
155
|
+
id: `${c.member}/${d.id}`, title: d.title, date: d.date, collection: d.collection,
|
|
156
|
+
...(d.mode !== "metadata" ? { snippet: snippet(d, q) } : {}),
|
|
157
|
+
permalink: permalinkOf(c, d), tokens: tokensOf(textOf(d)), terms: d.terms, material_kind: d.kind,
|
|
158
|
+
})),
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
r.get("/documents/:id", gate, (req, res) => {
|
|
162
|
+
const s = S(), c = s.config, d = getDoc(req.params.id);
|
|
163
|
+
if (!d) return res.status(404).json({ error: "unknown_document", message: `no document ${req.params.id}` });
|
|
164
|
+
const text = textOf(d);
|
|
165
|
+
const meta = {
|
|
166
|
+
id: `${c.member}/${d.id}`, title: d.title, date: d.date, authors: d.authors, type: d.type, collection: d.collection,
|
|
167
|
+
permalink: permalinkOf(c, d), source_url: d.source_url, terms: d.terms, material_kind: d.kind,
|
|
168
|
+
tokens: tokensOf(text), pages: d.pages, has_files: d.files.length > 0,
|
|
169
|
+
};
|
|
170
|
+
if (String(req.query.text ?? "true") === "false") return res.json(meta);
|
|
171
|
+
const textKind = text ? c.text.kind : "none";
|
|
172
|
+
if (req.query.pages !== undefined) {
|
|
173
|
+
if (!d.pages_marked) return res.status(422).json({ error: "no_page_markers", message: "this document's text has no [[page N]] markers" });
|
|
174
|
+
const want = parsePages(req.query.pages);
|
|
175
|
+
if (!want) return res.status(400).json({ error: "bad_pages", message: "pages is a list of numbers and ranges, e.g. 3-5,8" });
|
|
176
|
+
const parts = text.split(/(?=\[\[page \d+\]\])/);
|
|
177
|
+
const byPage = new Map(parts.map((p) => [Number(/^\[\[page (\d+)\]\]/.exec(p)?.[1]), p]));
|
|
178
|
+
const got = want.filter((p) => byPage.has(p)), missing = want.filter((p) => !byPage.has(p));
|
|
179
|
+
if (!got.length) return res.status(416).json({ error: "pages_out_of_range", message: `this document has ${d.pages} page(s)` });
|
|
180
|
+
const capped = capBytes(got.map((p) => byPage.get(p)).join(""), c.limits.document_bytes_max);
|
|
181
|
+
const cut = capped.text;
|
|
182
|
+
return res.json({ ...meta, ...(capped.truncated ? { truncated: true, partial: true } : {}), text: cut, text_kind: textKind, pages_marked: true, tokens: tokensOf(cut), pages_returned: got, pages_missing: missing, pages_total: d.pages });
|
|
183
|
+
}
|
|
184
|
+
const capped = capBytes(text, c.limits.document_bytes_max);
|
|
185
|
+
res.json({ ...meta, text: capped.text, text_kind: textKind, pages_marked: d.pages_marked, ...(capped.truncated ? { truncated: true, partial: true, warnings: [`text cut at document_bytes_max (${c.limits.document_bytes_max} bytes)`] } : {}) });
|
|
186
|
+
});
|
|
187
|
+
r.get("/documents/:id/citation", gate, (req, res) => {
|
|
188
|
+
const s = S(), d = getDoc(req.params.id);
|
|
189
|
+
if (!d) return res.status(404).json({ error: "unknown_document", message: `no document ${req.params.id}` });
|
|
190
|
+
const style = ["apa", "chicago", "mla", "bibtex"].includes(String(req.query.style)) ? String(req.query.style) : "apa";
|
|
191
|
+
res.json({ style, citation: citationOf(s.config, d, style), permalink: permalinkOf(s.config, d) });
|
|
192
|
+
});
|
|
193
|
+
r.post("/verify-quote", gate, (req, res) => {
|
|
194
|
+
const s = S(), d = getDoc(req.body?.id);
|
|
195
|
+
if (!d) return res.status(404).json({ error: "unknown_document", message: `no document ${req.body?.id}` });
|
|
196
|
+
if (typeof req.body?.quote !== "string" || !req.body.quote.trim()) return res.status(400).json({ error: "bad_quote", message: "quote must be a non-empty string" });
|
|
197
|
+
const text = textOf(d);
|
|
198
|
+
if (!text) return res.json({ id: `${s.config.member}/${d.id}`, status: "fabricated", confidence: 0, offset: null, note: "this member serves no text for this document", method: "openarch-kit-text-match-v1" });
|
|
199
|
+
let f = s.folded.get(d.id);
|
|
200
|
+
if (!f) { const hay = fold(text); f = { hay, index: buildFoldedIndex(hay) }; s.folded.set(d.id, f); }
|
|
201
|
+
const v = withVerbatimSpan(text, verifyQuoteAgainstFolded(f.hay, req.body.quote, f.index));
|
|
202
|
+
res.json({ id: `${s.config.member}/${d.id}`, ...v, method: "openarch-kit-text-match-v1" });
|
|
203
|
+
});
|
|
204
|
+
r.get("/documents/:id/files", gate, (req, res) => {
|
|
205
|
+
const s = S(), d = getDoc(req.params.id);
|
|
206
|
+
if (!d) return res.status(404).json({ error: "unknown_document", message: `no document ${req.params.id}` });
|
|
207
|
+
res.json({ id: `${s.config.member}/${d.id}`, files: d.files.map((f) => ({ file_id: f.file_id, kind: f.kind, role: f.role, media_type: f.media_type, bytes: f.bytes, sha256: f.sha256, url: fileUrl(s.config, d, f) })) });
|
|
208
|
+
});
|
|
209
|
+
r.get("/documents/:id/files/:file", gate, (req, res) => {
|
|
210
|
+
const d = getDoc(req.params.id);
|
|
211
|
+
const f = d?.files.find((x) => x.file_id === req.params.file);
|
|
212
|
+
if (!f) return res.status(404).json({ error: "unknown_file", message: "no such file for this document" });
|
|
213
|
+
// Open without following a link, then check the open file is the one loaded: a file swapped
|
|
214
|
+
// for a symbolic link (or replaced) after load is never served (ind-sec PR #3 review, S5)
|
|
215
|
+
let fd;
|
|
216
|
+
try {
|
|
217
|
+
fd = openSync(f.path, FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0));
|
|
218
|
+
const st = fstatSync(fd);
|
|
219
|
+
if (!st.isFile() || st.dev !== f.dev || st.ino !== f.ino || st.size !== f.bytes) { closeSync(fd); return res.status(409).json({ error: "file_changed", message: "this file changed since the catalog was loaded; the archive reloads it" }); }
|
|
220
|
+
} catch { if (fd !== undefined) try { closeSync(fd); } catch { /* closed */ } return res.status(404).json({ error: "unknown_file", message: "no such file for this document" }); }
|
|
221
|
+
res.set({ "Content-Type": f.media_type, "Content-Length": String(f.bytes), "X-Content-SHA256": f.sha256, ...fileHeaders(f.media_type, `${d.id}${extname(f.path).replace(/[^.A-Za-z0-9]/g, "").slice(0, 10)}`) });
|
|
222
|
+
createReadStream(null, { fd }).on("error", () => res.destroy()).pipe(res);
|
|
223
|
+
});
|
|
224
|
+
app.use("/openarch/v1", r);
|
|
225
|
+
|
|
226
|
+
// the details (credential state, counts) only to the hub; anyone else learns it is up (review nit)
|
|
227
|
+
app.get("/healthz", (req, res) => { const s = S(); if (!fromHub(req)) return res.json({ ok: true }); res.json({ ok: true, member: s.config.member, documents: s.docs.size, loaded_at: s.loadedAt, kit: KIT_VERSION, credential: "set" }); });
|
|
228
|
+
// the adapter's address in a browser: say what it is, never a bare "Cannot GET /"
|
|
229
|
+
const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
|
230
|
+
app.get("/", (_req, res) => { const c = S().config; res.set({ "Content-Security-Policy": PAGE_CSP, "X-Content-Type-Options": "nosniff" }); res.type("text/html").send(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(c.name)} · openarch</title><style>body{font:16px/1.55 system-ui,sans-serif;max-width:40rem;margin:3rem auto;padding:0 1rem;color:#1a1a1a;background:#fff}@media (prefers-color-scheme:dark){body{background:#121212;color:#e8e8e8}a{color:#8ab4f8}}</style><h1>${esc(c.name)}</h1><p>${esc(c.institution)}. This address serves the archive to the openarch network of university archives. Each document's citation opens its own page here.</p>${httpOnly(c.home) ? `<p><a href="${esc(httpOnly(c.home))}">The archive's own website</a></p>` : ""}</html>`); });
|
|
231
|
+
// robots: what the member declared about automated access, said to crawlers too
|
|
232
|
+
app.get("/robots.txt", (_req, res) => res.type("text/plain").send(S().config.rights?.automated_access === "allowed" ? "User-agent: *\nAllow: /view/\nDisallow: /openarch/\n" : "User-agent: *\nDisallow: /\n"));
|
|
233
|
+
// the permalink page: a human opens the document here (the permalink standard's third promise)
|
|
234
|
+
app.get("/view/:id", (req, res) => {
|
|
235
|
+
const s = S(), c = s.config;
|
|
236
|
+
if (!c.serves_view) return res.status(404).type("text/plain").send("Not found.");
|
|
237
|
+
const auto = c.rights?.automated_access;
|
|
238
|
+
const robots = auto === "allowed" ? null : "noindex, nofollow, noarchive";
|
|
239
|
+
res.set({ "Content-Security-Policy": PAGE_CSP, "X-Content-Type-Options": "nosniff" });
|
|
240
|
+
if (robots) res.set("X-Robots-Tag", robots);
|
|
241
|
+
const d = getDoc(req.params.id);
|
|
242
|
+
if (!d) return res.status(404).type("text/html").send(`<!doctype html><meta charset="utf-8"><title>Not found</title><p>No document ${esc(req.params.id)} in ${esc(c.name)}.`);
|
|
243
|
+
// the text is opt-in: shown only when automated access is allowed, or the member sets
|
|
244
|
+
// "view": { "text": true }; never more than the member's own document_bytes_max (S2)
|
|
245
|
+
const showText = auto !== "forbidden" && (auto === "allowed" || c.view?.text === true) && c.view?.text !== false;
|
|
246
|
+
const text = showText ? capBytes(textOf(d), c.limits.document_bytes_max).text.replace(/\[\[page (\d+)\]\]\n?/g, "\n— page $1 —\n") : "";
|
|
247
|
+
res.type("text/html").send(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${robots ? `<meta name="robots" content="${robots}">` : ""}<title>${esc(d.title)} · ${esc(c.name)}</title>
|
|
248
|
+
<style>body{font:16px/1.55 system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;color:#1a1a1a;background:#fff}h1{font-size:1.4rem;line-height:1.3}dl{display:grid;grid-template-columns:max-content 1fr;gap:.2rem 1rem;color:#444}dt{font-weight:600}pre{white-space:pre-wrap;font:14px/1.5 ui-monospace,monospace;background:#f6f6f4;padding:1rem;border-radius:6px}@media (prefers-color-scheme:dark){body{background:#121212;color:#e8e8e8}dl{color:#bbb}pre{background:#1e1e1e}}</style>
|
|
249
|
+
<p><a href="${esc(httpOnly(c.home) || c.public_base)}">${esc(c.name)}</a> · ${esc(c.institution)}</p><h1>${esc(d.title)}</h1>
|
|
250
|
+
<dl>${d.date ? `<dt>Date</dt><dd>${esc(d.date)}</dd>` : ""}${d.authors.length ? `<dt>By</dt><dd>${esc(d.authors.join(", "))}</dd>` : ""}${d.type ? `<dt>Type</dt><dd>${esc(d.type)}</dd>` : ""}<dt>Collection</dt><dd>${esc(c.collections.find((x) => x.id === d.collection)?.title ?? d.collection)}</dd><dt>Identifier</dt><dd>${esc(`${c.member}/${d.id}`)}</dd><dt>Terms</dt><dd>${esc(c.terms[d.terms]?.label ?? d.terms)}</dd>${d.source_url ? `<dt>Source</dt><dd><a href="${esc(d.source_url)}">${esc(d.source_url)}</a></dd>` : ""}</dl>
|
|
251
|
+
<p><strong>Cite as</strong>: ${esc(citationOf(c, d, "chicago"))}</p>${c.rights?.attribution === "required" ? `<p><strong>Credit required</strong>: every reuse credits ${esc(c.name)}.</p>` : ""}${c.rights?.statement ? `<p><em>${esc(c.rights.statement)}</em></p>` : ""}${d.files.length ? `<p>The ${esc(d.kind === "pdf" ? "scan" : "file")} itself is available to researchers through openarch.</p>` : ""}${text ? `<pre>${esc(text.trim())}</pre>` : `<p>${esc(c.name)} serves this document's text to researchers through openarch.</p>`}</html>`);
|
|
252
|
+
});
|
|
253
|
+
app.use((err, req, res, _next) => {
|
|
254
|
+
const status = err?.type === "entity.parse.failed" ? 400 : err?.status === 413 || err?.type === "entity.too.large" ? 413 : 500;
|
|
255
|
+
if (status === 500) (log ?? console.error)(`${new Date().toISOString()} ${req.method} ${req.originalUrl.split("?")[0]} 500 ${err?.message ?? err}`);
|
|
256
|
+
if (res.headersSent) return res.destroy();
|
|
257
|
+
res.status(status).json({ error: status === 400 ? "bad_json" : status === 413 ? "too_large" : "internal", message: status === 500 ? "the adapter hit an error" : "the request body was not accepted" });
|
|
258
|
+
});
|
|
259
|
+
return app;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Read the config, load the catalog, listen. A SIGHUP (or `systemctl reload`) re-reads the
|
|
264
|
+
* catalog and swaps it in whole; a bad catalog is refused and the running one kept.
|
|
265
|
+
*/
|
|
266
|
+
export async function startMember(configPath = "openarch-member.json", { port = Number.parseInt(process.env.PORT ?? "", 10) || 3101, host = process.env.HOST || "127.0.0.1", log = console.log } = {}) {
|
|
267
|
+
const dev = process.env.OPENARCH_DEV === "1";
|
|
268
|
+
const credSha = process.env.OPENARCH_HUB_CREDENTIAL_SHA256 || (process.env.OPENARCH_HUB_CREDENTIAL ? sha256(process.env.OPENARCH_HUB_CREDENTIAL) : null);
|
|
269
|
+
if (credSha && !/^[0-9a-f]{64}$/i.test(credSha)) throw new ConfigError("OPENARCH_HUB_CREDENTIAL_SHA256 must be 64 hex characters (the SHA-256 of the credential).");
|
|
270
|
+
if (process.env.OPENARCH_HUB_CREDENTIAL && !/^oa_hub_[0-9a-f]{40}$/.test(process.env.OPENARCH_HUB_CREDENTIAL)) log(" warning: OPENARCH_HUB_CREDENTIAL is not shaped like a hub credential (oa_hub_ and 40 hex characters); use the one the operator sent, or the one openarch member init wrote.");
|
|
271
|
+
const stateRef = { current: await loadState(configPath, { log }) };
|
|
272
|
+
const app = createMember(stateRef, { hubCredentialSha256: credSha?.toLowerCase() ?? null, dev, log });
|
|
273
|
+
const reload = async () => {
|
|
274
|
+
try { stateRef.current = await loadState(configPath, { log }); log("openarch member kit: catalog reloaded"); }
|
|
275
|
+
catch (e) { log(`openarch member kit: reload refused, still serving the previous catalog — ${e.message}`); }
|
|
276
|
+
};
|
|
277
|
+
process.on("SIGHUP", reload);
|
|
278
|
+
if (process.env.OPENARCH_WATCH === "1") { let t; watch(stateRef.current.config.__dir, () => { clearTimeout(t); t = setTimeout(reload, 1500); }); }
|
|
279
|
+
const server = await new Promise((ok, no) => { const s = app.listen(port, host, () => ok(s)); s.on("error", no); });
|
|
280
|
+
const c = stateRef.current.config;
|
|
281
|
+
log(`openarch member ${c.member} · ${c.name} · http://${host}:${port}/openarch/v1/manifest · public address ${c.public_base}`);
|
|
282
|
+
if (!credSha) log(dev ? " NO HUB CREDENTIAL — open to any caller (OPENARCH_DEV=1). Development only." : " NO HUB CREDENTIAL — every call but the manifest answers 503. Set OPENARCH_HUB_CREDENTIAL (openarch member init wrote one to .env).");
|
|
283
|
+
return { app, server, state: stateRef };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export { readConfig, loadCatalog, ConfigError };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// searchIndex.js — the member kit's search (protocol §4.2): an in-memory word index
|
|
2
|
+
// over each document's title, metadata and text. Plain words must all appear; a
|
|
3
|
+
// "quoted phrase" must appear as written (after folding case and accents). Results
|
|
4
|
+
// rank by how often the words occur, a title hit counting most; ties break by id, so
|
|
5
|
+
// pages are stable and the cursor (an offset) continues exactly where a page ended.
|
|
6
|
+
//
|
|
7
|
+
// Sized for the archives the kit is for: tens of thousands of documents. A larger
|
|
8
|
+
// archive passes its own search function to createMember (see members/kit/README.md).
|
|
9
|
+
|
|
10
|
+
export const foldText = (s) => String(s ?? "").normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
|
11
|
+
const WORD = /[\p{L}\p{N}]+/gu;
|
|
12
|
+
const words = (s) => foldText(s).match(WORD) ?? [];
|
|
13
|
+
|
|
14
|
+
export function buildIndex(docs) {
|
|
15
|
+
const postings = new Map(); // word → Map(docId → weight)
|
|
16
|
+
const folded = new Map(); // docId → folded searchable text, for phrases
|
|
17
|
+
const add = (w, id, n) => { let m = postings.get(w); if (!m) postings.set(w, (m = new Map())); m.set(id, (m.get(id) ?? 0) + n); };
|
|
18
|
+
for (const d of docs.values()) {
|
|
19
|
+
const meta = [d.authors.join(" "), d.type, d.date, d.collection].filter(Boolean).join(" ");
|
|
20
|
+
for (const w of words(d.title)) add(w, d.id, 3);
|
|
21
|
+
for (const w of words(meta)) add(w, d.id, 1);
|
|
22
|
+
for (const w of words(d.text.replace(/\[\[page \d+\]\]/g, " "))) add(w, d.id, 1);
|
|
23
|
+
folded.set(d.id, foldText(`${d.title}\n${meta}\n${d.text}`).replace(/\s+/g, " "));
|
|
24
|
+
}
|
|
25
|
+
return { postings, folded, size: docs.size };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Parse a query into plain words and quoted phrases. */
|
|
29
|
+
export function parseQuery(q) {
|
|
30
|
+
const phrases = [], rest = [];
|
|
31
|
+
String(q).replace(/"([^"]+)"|(\S+)/g, (_m, ph, w) => { if (ph) phrases.push(ph); else rest.push(w); return ""; });
|
|
32
|
+
return { words: [...new Set(rest.flatMap(words))], phrases: phrases.map((p) => foldText(p).replace(/\s+/g, " ").trim()).filter(Boolean) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function search(index, docs, q, { collection = null, limit = 25, offset = 0 } = {}) {
|
|
36
|
+
const { words: ws, phrases } = parseQuery(q);
|
|
37
|
+
const need = [...ws, ...phrases.flatMap((p) => p.match(WORD) ?? [])];
|
|
38
|
+
if (!need.length) return { total: 0, ids: [] };
|
|
39
|
+
// the rarest word first narrows the candidates fastest
|
|
40
|
+
const lists = [...new Set(need)].map((w) => index.postings.get(w) ?? new Map()).sort((a, b) => a.size - b.size);
|
|
41
|
+
let candidates = [...lists[0].keys()];
|
|
42
|
+
for (const l of lists.slice(1)) candidates = candidates.filter((id) => l.has(id));
|
|
43
|
+
if (phrases.length) candidates = candidates.filter((id) => phrases.every((p) => index.folded.get(id).includes(p)));
|
|
44
|
+
if (collection) candidates = candidates.filter((id) => docs.get(id)?.collection === collection);
|
|
45
|
+
const score = (id) => lists.reduce((s, l) => s + (l.get(id) ?? 0), 0);
|
|
46
|
+
const ranked = candidates.map((id) => [id, score(id)]).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([id]) => id);
|
|
47
|
+
return { total: ranked.length, ids: ranked.slice(offset, offset + limit) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A short passage around the first word of the query found in the text, else the opening. */
|
|
51
|
+
export function snippet(doc, q, max = 200) {
|
|
52
|
+
const plain = doc.text.replace(/\[\[page \d+\]\]\n?/g, " ").replace(/\s+/g, " ").trim();
|
|
53
|
+
if (!plain) return "";
|
|
54
|
+
const lower = foldText(plain);
|
|
55
|
+
const { words: ws, phrases } = parseQuery(q);
|
|
56
|
+
let at = -1;
|
|
57
|
+
for (const t of [...phrases, ...ws]) { const i = lower.indexOf(t); if (i >= 0 && (at < 0 || i < at)) at = i; }
|
|
58
|
+
const start = Math.max(0, at - 60);
|
|
59
|
+
const cut = plain.slice(start, start + max);
|
|
60
|
+
return `${start > 0 ? "…" : ""}${cut}${start + max < plain.length ? "…" : ""}`;
|
|
61
|
+
}
|