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.
@@ -0,0 +1,35 @@
1
+ // fileSafety.js — the headers every served or relayed file carries (ind-sec PR #3 review, S4).
2
+ // A member's files are documents, never pages of ours: an .html, .xml or .svg served inline would
3
+ // run as active content on the serving origin. Every file gets nosniff and a sandboxing CSP; the
4
+ // active types go as attachments.
5
+ const ACTIVE = /^(text\/html|application\/xhtml\+xml|application\/xml|text\/xml|image\/svg\+xml)\b/i;
6
+ export const isActiveMediaType = (t) => ACTIVE.test(String(t ?? ""));
7
+
8
+ /**
9
+ * The one place a member's file redirect may send a partner (ind-sec run-2 #31,
10
+ * get_file:member-location-under-key-instruction): an absolute https URL with no
11
+ * credentials in it, else null. A relative, http, scheme-relative or userinfo
12
+ * Location (or one with a backslash, which clients parse differently) is the
13
+ * member's error, never relayed; the hub answers 502 instead. What is relayed is
14
+ * the parsed URL's own spelling, never the member's raw header.
15
+ */
16
+ export function memberFileLocation(raw, { refuseOrigins = [] } = {}) {
17
+ if (typeof raw !== "string" || raw.length > 4096 || /[\x00-\x20\x7f\\]/.test(raw)) return null; // a backslash parses differently from one client to the next
18
+ let u;
19
+ try { u = new URL(raw); } catch { return null; }
20
+ if (u.protocol !== "https:" || u.username || u.password || !u.hostname) return null;
21
+ // never the hub's own address: a member's storage is never the hub, and a redirect there
22
+ // would spend the partner's key on a document the member picked (ind-sec, #5 review)
23
+ if (refuseOrigins.some((o) => { try { return new URL(o).origin === u.origin; } catch { return false; } })) return null;
24
+ return u.href;
25
+ }
26
+
27
+ /** Headers for a file response: { "X-Content-Type-Options", "Content-Security-Policy", "Content-Disposition" }. */
28
+ export function fileHeaders(mediaType, filename) {
29
+ const safeName = String(filename ?? "file").replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 120) || "file";
30
+ return {
31
+ "X-Content-Type-Options": "nosniff",
32
+ "Content-Security-Policy": "sandbox; default-src 'none'",
33
+ "Content-Disposition": `${isActiveMediaType(mediaType) ? "attachment" : "inline"}; filename="${safeName}"`,
34
+ };
35
+ }
@@ -0,0 +1,210 @@
1
+ // verifyQuote.js — a member adapter's quote check (protocol §4.5), a text match
2
+ // over the same text the member serves (shared by INDRA's and PETRA's adapters). INDRA's own watchdog (quoteAnchor v3: n-gram
3
+ // Jaccard, rare-word + edit distance, ellipsis splits) is not yet exposed over
4
+ // HTTP; until it is, this is a smaller, honest version of the same idea, and the
5
+ // verdict names its method so a partner knows which one it got.
6
+ //
7
+ // anchored the quotation, after folding, is a substring (offset given), or
8
+ // every one of its word 5-grams is present when it is long enough
9
+ // to have them
10
+ // uncertain most of its 5-grams (or, for short quotes, most of its words)
11
+ // are present — a paraphrase, an OCR error, or a splice
12
+ // fabricated the text does not support it
13
+ //
14
+ // Pure: (text, quote) → { status, confidence, offset, matched_span? }.
15
+ //
16
+ // Bounded (ind-sec openarch run-1): each distinct 5-gram or word is looked up
17
+ // once, and at most PROBES_MAX of them, evenly spaced, so a long quotation costs
18
+ // a fixed number of scans of the text. "anchored" by 5-grams needs every one of
19
+ // them checked; a sampled check can say "uncertain" at most.
20
+
21
+ const PAGE_MARK = /\[\[(?:page|sheet)[^\]]*\]\]/g;
22
+
23
+ /** Fold case, quotes, dashes, ligatures and whitespace so OCR and typing agree. */
24
+ export function fold(s) {
25
+ return String(s)
26
+ .replace(PAGE_MARK, " ")
27
+ .toLowerCase()
28
+ .replace(/[‘’‚‛]/g, "'")
29
+ .replace(/[“”„‟"]/g, "")
30
+ .replace(/[‐-―−]/g, "-")
31
+ .replace(/­/g, "")
32
+ .replace(/fi/g, "fi").replace(/fl/g, "fl")
33
+ .replace(/-\n\s*/g, "") // hyphenation across a line break
34
+ .replace(/[^\p{L}\p{N}'\-.,;:()/%$ ]+/gu, " ")
35
+ .replace(/\s+/g, " ")
36
+ .trim();
37
+ }
38
+
39
+ const words = (s) => s.split(" ").filter(Boolean);
40
+ const PROBES_MAX = 200;
41
+ /** At most `max` of `xs`, evenly spaced, the first and the last kept. */
42
+ const spread = (xs, max) => (xs.length <= max ? xs : Array.from({ length: max }, (_, i) => xs[Math.round((i * (xs.length - 1)) / (max - 1))]));
43
+
44
+ function ngrams(ws, n) {
45
+ const out = [];
46
+ for (let i = 0; i + n <= ws.length; i++) out.push(ws.slice(i, i + n).join(" "));
47
+ return out;
48
+ }
49
+
50
+ export const verifyQuoteAgainstText = (text, quote) => verifyQuoteAgainstFolded(fold(text), quote);
51
+
52
+ // ── an index of a folded text, built once per cached document (ind-sec run-2,
53
+ // gradient per-ngram-fulltext-scan): without it, each of up to 200 probes of a long
54
+ // invented quotation scanned the whole text (200 x 5 MB). With it, a probe is a binary
55
+ // search, and the text is read only to confirm a hit and give its offset.
56
+ const fnv = (s, from = 0, to = s.length) => { let h = 2166136261; for (let i = from; i < to; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; };
57
+ const mix5 = (hs, at = 0) => { let h = 2166136261; for (let k = at; k < at + 5; k++) h = Math.imul(h ^ hs[k], 16777619); return (h >>> 0) >>> 4; }; // 28 bits
58
+ const OFF = 2 ** 25; // offsets below 32 MB (document_bytes_max is 20 MB): 28 + 25 bits fit a double exactly
59
+
60
+ /** { grams: Float64Array of hash28 * 2^25 + offset, sorted; words: Set; vocab: the distinct words joined; bytes }. */
61
+ export function buildFoldedIndex(hay) {
62
+ if (typeof hay !== "string" || hay.length >= OFF) return null; // too long to index: the plain scans apply
63
+ // typed arrays: a 20 MB text has about 4M words, and plain arrays of them would cost the
64
+ // adapter several times its index while it is built
65
+ let count = hay.length ? 1 : 0;
66
+ for (let i = 0; i < hay.length; i++) if (hay.charCodeAt(i) === 32) count++;
67
+ const starts = new Uint32Array(count), hashes = new Uint32Array(count);
68
+ for (let i = 0, k = 0; i < hay.length; k++) {
69
+ let j = hay.indexOf(" ", i);
70
+ if (j < 0) j = hay.length;
71
+ starts[k] = i; hashes[k] = fnv(hay, i, j);
72
+ i = j + 1;
73
+ }
74
+ const n = Math.max(0, starts.length - 4);
75
+ const grams = new Float64Array(n);
76
+ for (let i = 0; i < n; i++) grams[i] = mix5(hashes, i) * OFF + starts[i];
77
+ grams.sort();
78
+ const words = new Set();
79
+ for (let i = 0; i < starts.length; i++) words.add(hay.slice(starts[i], i + 1 < starts.length ? starts[i + 1] - 1 : hay.length));
80
+ const vocab = [...words].join(" ");
81
+ return { grams, words, vocab, bytes: grams.byteLength + 2 * vocab.length + 64 * words.size };
82
+ }
83
+
84
+ /** The first offset at which the word-aligned 5-word run `g` (words `ws`) starts, or -1. */
85
+ function findGram(hay, index, g, ws) {
86
+ const h = mix5(ws.map((w) => fnv(w)));
87
+ const lo0 = h * OFF;
88
+ let lo = 0, hi = index.grams.length;
89
+ while (lo < hi) { const mid = (lo + hi) >>> 1; if (index.grams[mid] < lo0) lo = mid + 1; else hi = mid; }
90
+ // entries sharing the hash are in offset order: the first that really holds g is its first occurrence
91
+ for (let i = lo; i < index.grams.length && index.grams[i] < lo0 + OFF; i++) {
92
+ const at = index.grams[i] - lo0;
93
+ if (hay.startsWith(g, at) && (at + g.length === hay.length || hay.charCodeAt(at + g.length) === 32)) return at;
94
+ }
95
+ return -1;
96
+ }
97
+
98
+ /** The same check against text already folded (an adapter folds a document once and keeps it);
99
+ * `index` (buildFoldedIndex) makes the gradient's probes lookups instead of scans. */
100
+ export function verifyQuoteAgainstFolded(hay, quote, index = null) {
101
+ // ellipsis: split BEFORE folding (folding would erase the mark), then every fragment must anchor, in order
102
+ // Punctuation at a quotation's edges belongs to the sentence quoting it, not to the source:
103
+ // American style puts the comma inside the quotation marks ("…its potential,"). Each
104
+ // fragment drops it before matching; inner punctuation still has to match (ETNA, 2026-11-26).
105
+ const edges = (f) => f.replace(/^[\s.,;:!?]+|[\s.,;:!?]+$/g, "");
106
+ const fragments = String(quote).split(/\s*(?:\.\.\.|…|\[\s*\.\.\.\s*\]|\[…\])\s*/).map((f) => edges(fold(f))).filter(Boolean);
107
+ const q = fragments.join(" ");
108
+ if (!q) return { status: "fabricated", confidence: 0, offset: null };
109
+ if (fragments.length > 1) {
110
+ let cursor = 0;
111
+ const offsets = [];
112
+ for (const f of fragments) {
113
+ const at = hay.indexOf(f, cursor);
114
+ if (at < 0) return gradient(hay, fragments.join(" "), index);
115
+ offsets.push(at);
116
+ cursor = at + f.length;
117
+ }
118
+ // the fragments as found, never the text the ellipsis leaves out
119
+ return { status: "anchored", confidence: 1, offset: offsets[0], fragment_offsets: offsets, matched_span: fragments.join(" … ").slice(0, 400) };
120
+ }
121
+
122
+ const at = hay.indexOf(q);
123
+ if (at >= 0) return { status: "anchored", confidence: 1, offset: at, matched_span: q.slice(0, 400) };
124
+ return gradient(hay, q, index);
125
+ }
126
+
127
+ /** No exact hit: how much of the quotation the text supports. */
128
+ function gradient(hay, q, index = null) {
129
+ const qw = words(q);
130
+ if (qw.length >= 6) {
131
+ const all = [...new Set(ngrams(qw, 5))];
132
+ const grams = spread(all, PROBES_MAX);
133
+ const sampled = grams.length < all.length;
134
+ // indexed, a run matches on word boundaries; unindexed (PETRA's short texts), anywhere
135
+ const found = grams.map((g) => (index ? findGram(hay, index, g, g.split(" ")) : hay.indexOf(g)));
136
+ const hit = found.filter((at) => at >= 0).length;
137
+ const ratio = hit / grams.length;
138
+ if (ratio === 1 && !sampled) return { status: "anchored", confidence: 0.98, offset: found[0] };
139
+ // any 5-word run of the quotation present in the text = partly found
140
+ if (hit > 0) {
141
+ // the passage as the document has it: from the first matching run to the last, when they sit together
142
+ const spans = grams.map((g, i) => [found[i], g.length]).filter(([at]) => at >= 0);
143
+ const start = Math.min(...spans.map(([at]) => at)), end = Math.max(...spans.map(([at, len]) => at + len));
144
+ const together = end - start <= q.length * 2;
145
+ const confidence = Number(Math.min(sampled ? 0.95 : 1, 0.4 + 0.6 * ratio).toFixed(2));
146
+ return { status: "uncertain", confidence, offset: spans[0][0], ...(together ? { matched_span: hay.slice(start, end).slice(0, 400), note: "the document's text differs from the quotation in places — often an OCR reading; compare matched_span" } : {}), ...(sampled ? { probes: `${grams.length} of the quotation's ${all.length} 5-word runs checked` } : {}) };
147
+ }
148
+ // no run at all can still be a loose paraphrase of a real passage: fall through to words
149
+ }
150
+ const content = spread([...new Set(qw.filter((w) => w.length > 3))], PROBES_MAX);
151
+ if (content.length === 0) return { status: "fabricated", confidence: 0, offset: null };
152
+ // a word (no spaces) is in the text iff it is inside one of its words: the distinct words suffice
153
+ const present = content.filter((w) => (index ? index.words.has(w) || index.vocab.includes(w) : hay.includes(w))).length;
154
+ const ratio = present / content.length;
155
+ if (qw.length < 6 && ratio === 1) return { status: "uncertain", confidence: 0.7, offset: null, note: "short quotation: its words are present but not as a run" };
156
+ return ratio >= 0.75 && qw.length >= 6
157
+ ? { status: "uncertain", confidence: Number((ratio * 0.6).toFixed(2)), offset: null }
158
+ : { status: "fabricated", confidence: Number((ratio * 0.3).toFixed(2)), offset: null };
159
+ }
160
+
161
+ // ── the passage as the document has it (§4.5) ────────────────────────────────
162
+ // matched_span above is cut from the FOLDED text (lowercased, punctuation dropped), but the
163
+ // protocol asks for "the passage as the document has it" so a reader can see the OCR reading
164
+ // (the newcomer walkthrough, 2026-11-26; member check V4). This finds the same words, in
165
+ // order, in the original text and returns that slice; when it cannot (a ligature, a word
166
+ // hyphenated across a line), it returns null and the caller omits matched_span rather
167
+ // than show text the document does not have.
168
+ const RX_ESC = /[.*+?^${}()|[\]\\]/g;
169
+ const CHAR_CLASS = { "'": "['‘’‚‛`]", "-": "[-‐‑‒–—―−]" };
170
+ // The separator between two words is exactly what fold() turns into a space or drops (ind-sec
171
+ // run-3 P2, verbatimSpan:punctuation-run-exponential-backtracking). It used to be any run of
172
+ // non-letters, so it could also swallow the punctuation fold keeps as words: a dot leader
173
+ // ". . . ." is words ".", and a run of k of them gave about 2^k ways to share the dots between
174
+ // separators and words, each tried before the match was found; a 30-dot table-of-contents line
175
+ // would hold the kit's only event loop for most of a minute. Now a separator is a page mark, a
176
+ // dash that fold joins across a line break ("-\n"), or a character that is not a letter, a
177
+ // number, or one fold keeps (' - . , ; : ( ) / % $ and the variants it maps onto them), so it
178
+ // never consumes a word. And it is matched atomically: a lookahead captures the longest
179
+ // separator, a backreference consumes it, and the engine never tries a shorter one (the page
180
+ // mark comes first, so the lookahead takes a mark whole). Each place tried in the text then
181
+ // costs one pass over the quotation's words, whatever the punctuation.
182
+ const KEPT = "'\\u2018-\\u201B\\-\\u2010-\\u2015\\u2212.,;:()/%$";
183
+ const SEP = `(?:\\[\\[(?:page|sheet)[^\\]]*\\]\\]|[\\-\\u2010-\\u2015\\u2212]\\n|[^\\p{L}\\p{N}${KEPT}])+`;
184
+ const atomicSep = (n) => `(?=(${SEP}))(?:\\${n})`; // (?:…): a digit after it never extends the group number
185
+ const wordRx = (w) => [...w].map((ch) => CHAR_CLASS[ch] ?? ch.replace(RX_ESC, "\\$&")).join("");
186
+ export function verbatimSpan(original, foldedSpan, { max = 600 } = {}) {
187
+ if (typeof original !== "string" || typeof foldedSpan !== "string" || !foldedSpan.trim()) return null;
188
+ const out = [];
189
+ let from = 0;
190
+ for (const fragment of foldedSpan.split(" … ")) {
191
+ const ws = fragment.split(" ").filter(Boolean);
192
+ if (!ws.length) continue;
193
+ let rx;
194
+ try { rx = new RegExp(ws.map((w, i) => (i ? atomicSep(i) : "") + wordRx(w)).join(""), "giu"); } catch { return null; }
195
+ rx.lastIndex = from;
196
+ const m = rx.exec(original);
197
+ if (!m) return null;
198
+ out.push(m[0].replace(/\[\[(?:page|sheet)[^\]]*\]\]/g, " ").replace(/\s+/g, " ").trim());
199
+ from = m.index + m[0].length;
200
+ }
201
+ const s = out.join(" … ");
202
+ return s ? s.slice(0, max) : null;
203
+ }
204
+ /** A verdict with matched_span (and the fragments of an ellipsis) replaced by the document's own words. */
205
+ export function withVerbatimSpan(original, verdict) {
206
+ if (!verdict || typeof verdict.matched_span !== "string") return verdict;
207
+ const v = verbatimSpan(original, verdict.matched_span);
208
+ const { matched_span: _folded, ...rest } = verdict;
209
+ return v ? { ...rest, matched_span: v } : rest;
210
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "stanford-openarch",
3
- "version": "0.0.0",
4
- "description": "Reserved for openarch (OpenArches LLC). Install the CLI from your openarch hub, not from npm.",
5
- "license": "UNLICENSED"
3
+ "version": "0.1.0",
4
+ "description": "openarch — the command line and the member kit: use the network, or connect an archive to it.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "node": ">=20.6"
9
+ },
10
+ "bin": {
11
+ "openarch": "cli/openarch.js"
12
+ },
13
+ "exports": {
14
+ "./member-kit": "./members/kit/index.js",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "dependencies": {
18
+ "express": "^4.21.2",
19
+ "@modelcontextprotocol/sdk": "^1.12.0",
20
+ "zod": "^3.24.0"
21
+ },
22
+ "openarch": {
23
+ "hub": "https://openarch.stanford.edu"
24
+ }
6
25
  }
@@ -0,0 +1,105 @@
1
+ # openarch membership agreement, version 0.1
2
+
3
+ A member is an institution that connects an archive to the network. By joining, the
4
+ institution, through the person named in its application, agrees to the following.
5
+ Each point is short because each is checked, by the conformance walk, by the hub, or
6
+ by the operator, and a point that cannot be checked is not in this agreement.
7
+
8
+ ## 1. What the member serves
9
+
10
+ The member answers the calls of the protocol (manifest, search, document, citation
11
+ and, if it chooses, quote verification and files) over its own holdings. Text is the
12
+ floor: OCR and text layers, the text rendering of spreadsheets, transcripts, token
13
+ counts, metadata, citations and reuse terms, with a permalink to the original at its
14
+ source. Files — the image, the PDF, the video — are served only for the kinds of
15
+ material the member marks `files` in its sharing grid (§2), under the terms it
16
+ declared, and may be withdrawn at any time by changing the grid.
17
+
18
+ ## 2. Declarations
19
+
20
+ The member declares, in the fixed vocabulary of the protocol and in its manifest:
21
+
22
+ - the **basis of its rights** in the materials it serves (`rights.basis`), per collection
23
+ where collections differ;
24
+ - **what it grants** others — the reuse it permits, whether credit is required, and
25
+ whether automated access is allowed (`rights.grant`, `rights.attribution`,
26
+ `rights.automated_access`);
27
+ - its **permalink standard** (`permalinks`): the pattern of its citable addresses and
28
+ the three promises below;
29
+ - its **sharing grid** (`sharing`): for each kind of material it holds, whether it is
30
+ shared — and how far: the record, the text, or the files — or withheld, and why. The
31
+ grid is the member's policy, kept at the hub and changeable in its account at any
32
+ time; the hub routes by it, and no file of a withheld kind is served through the
33
+ network whatever the member's adapter would answer.
34
+
35
+ The member keeps these declarations true. A change is a new declaration, dated, and
36
+ the earlier one stays on record at the hub.
37
+
38
+ ## 3. The permalink standard
39
+
40
+ Every document the member serves has a citable address of the declared pattern, and:
41
+
42
+ - an id is **minted once and never reused**, even when a document is removed, merged
43
+ or re-ingested;
44
+ - **every earlier form resolves forever**, by alias or redirect;
45
+ - the permalink **opens the document for a person**, not an API payload.
46
+
47
+ Citations issued through the network name this permalink, so the standard is what
48
+ makes a citation to any member look and behave the same way.
49
+
50
+ ## 4. Keys
51
+
52
+ The hub presents the member's adapter one credential (`oa_hub_…`), which the hub mints when
53
+ it approves the member and sends to the member once; the adapter answers no other party's
54
+ key. It may keep its own per-partner accounting from the key hash the hub forwards.
55
+ Keys on the member's side are held by named people; a key is revoked when the person
56
+ leaves.
57
+
58
+ ## 5. Takedown
59
+
60
+ The member answers a takedown or correction request about a document it serves within
61
+ ten business days, and withholds the document from the network while the request is
62
+ open if the request is plausible on its face.
63
+
64
+ ## 6. Records
65
+
66
+ The hub logs every routed call (who, what, how much, when) and shows a partner its own
67
+ ledger and the operator everything. The member may log the same on its side. Nothing
68
+ in the network stores a partner's reading beyond these ledgers.
69
+
70
+ ## 7. Leaving
71
+
72
+ A member may leave at any time by telling the operator; its documents stop being served
73
+ through the network at once. Citations already issued keep resolving under the
74
+ member's own permalink promise, which survives membership.
75
+
76
+ ## 8. The operator
77
+
78
+ Stanford University operates the hub and admits members and partners under this
79
+ agreement. Admission and key policy may later move to a quorum of members; that
80
+ changes who decides, not what is agreed here.
81
+
82
+ ## 9. Accuracy and responsibility
83
+
84
+ What the member serves is what it holds, unaltered. OCR is a verbatim rendition, a
85
+ transcript is what was said, metadata is honest, nothing is fabricated, doctored or
86
+ invented, and what is held back is declared as withheld, never silently omitted. The
87
+ member has the right to serve what it serves, under the basis it declared.
88
+
89
+ openarch relays what members serve. It does not check, warrant or vouch for a member's
90
+ data, and a partner receives it as served by the member. A member whose data turns out to
91
+ be polluted, fabricated, materially inaccurate, or served without the right to do so may
92
+ be suspended at once and removed from the network, by the operator, on notice to the
93
+ member's contact; and the member indemnifies openarch and Stanford University against any
94
+ claim, loss or cost arising from the data it served or from the way it served it. Nothing
95
+ in this section limits the member's own rights against a partner who misuses its data.
96
+
97
+ ## 10. Plain words, and counsel
98
+
99
+ This agreement is written to be read, and every point in it is checked by the network's
100
+ tools or the operator. It is not legal advice; Stanford University's counsel reviews it
101
+ before any member outside Stanford signs it, and a later version supersedes this one
102
+ only for members who accept the later version.
103
+
104
+ Accepted by name and date in the member's application and recorded in its manifest as
105
+ `agreement: { version, accepted_by, accepted_on }`.