football-docs 0.12.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -94,6 +94,45 @@ Add to `claude_desktop_config.json`:
94
94
 
95
95
  Provider filters use the indexed provider keys shown by `list_providers`, but common aliases are accepted. Examples: `fbref`, `understat`, `ClubElo`, `football-data.co.uk`, and `engsoccerdata` search `free-sources`; `Sofascore` searches `soccerdata`; `ESPN`, `ESPN FC`, and `espn-soccer` search `espn`; `FMDB` searches `fmdb-pro`; `Transfer Room` searches `transferroom`; `Hudl Wyscout` searches `wyscout`; `Stats Perform` / `Opta F24` / `WhoScored` search `opta`; `Metrica`, `Sportec` / `DFL`, and `TRACAB` search `databallpy`; `Second Spectrum` searches `kloppy`; `Hawk-Eye`, `SciSports`, `Signality`, `Respovision`, `GradientSports` and `OptaVision` search `fast-forward`; `unravel` searches `unravelsports`; `SportRadar API` / `Soccer Extended` search `sportradar`; `The Sports DB` / `TSDB` search `thesportsdb`; `StatsBomb Open Data` searches `statsbomb`.
96
96
 
97
+ ## How the index stays current
98
+
99
+ The package ships a docs index, but doc fixes do not wait for a new package
100
+ version. Once a day at most, the server checks the
101
+ [`data-latest`](https://github.com/withqwerty/football-docs/releases/tag/data-latest)
102
+ release of this repository for a newer index built from `main`:
103
+
104
+ - It reads a small signed manifest (`manifest-v1-signed.json`) and, only when that
105
+ names a newer build, downloads the index (about 6 MB).
106
+ - It accepts the manifest only if its ed25519 signature verifies against a public
107
+ key shipped in the package (`src/data-signing.ts`). The manifest carries the
108
+ index's size and SHA-256, so the signature covers the index too.
109
+ - It checks the download's size and SHA-256, its SQLite integrity, its exact
110
+ schema and its metadata before using it, and keeps the one it had on any failure.
111
+ - It stores downloads in `$XDG_DATA_HOME/football-docs/data/` (by default
112
+ `~/.local/share/football-docs/data/`). The next tool call uses the new file; no
113
+ restart is needed.
114
+ - It runs in the background after start-up and never delays a tool call.
115
+ `list_providers` ends with the build time of the index in use and whether it is
116
+ bundled or downloaded.
117
+
118
+ Privacy: the check is one HTTPS request a day to GitHub, plus the download when
119
+ there is one. No search queries or other usage data are sent.
120
+
121
+ Settings, as environment variables in the server's MCP configuration:
122
+
123
+ - `FOOTBALL_DOCS_DATA=bundled`: use only the index inside the package. No network,
124
+ no downloads.
125
+ - `FOOTBALL_DOCS_DATA=auto`: the default for an installed package. Check daily and
126
+ use the newest valid index.
127
+ - `FOOTBALL_DOCS_DB_PATH=<file>`: use exactly this index file.
128
+ - `FOOTBALL_DOCS_DATA_BASE_URL=<url>`: read the manifest and index from a mirror
129
+ (HTTPS only).
130
+
131
+ Offline, or behind a proxy that Node's built-in `fetch` does not use, the check
132
+ fails quietly and the server keeps the index it has. Under CI (`CI` set) the check
133
+ does not run. A server running from a git checkout defaults to `bundled`, so
134
+ development and tests always use the working tree's docs.
135
+
97
136
  ## Example queries
98
137
 
99
138
  - "What is Opta qualifier 76?" (big chance)
@@ -248,6 +287,47 @@ npm run ingest -- --provider kloppy # re-ingest one provider (incremental)
248
287
 
249
288
  Each crawled doc carries provenance metadata (source URL, source type, upstream version, crawl timestamp) that is surfaced in search results, so agents can distinguish between curated content and upstream documentation.
250
289
 
290
+ ### How doc changes reach users
291
+
292
+ A merge to `main` that touches `docs/` or `providers.json` runs
293
+ `.github/workflows/data.yml`, which rebuilds the index, runs the tests against it,
294
+ checks that the **published** server can use it (`scripts/check-data-compat.mjs`),
295
+ and publishes it to the `data-latest` release. Installed servers pick it up within
296
+ about a day, including servers that have been running for days (they check again
297
+ every six hours, at most once a day). Merging a doc PR is therefore also shipping it; there is no later step at
298
+ which to stop it. To undo a bad doc change, revert it on `main`, which publishes a
299
+ newer build.
300
+
301
+ **What the signature guarantees.** The publish job signs the manifest with a key
302
+ held only in the `data-publish` environment, whose deployment policy allows only
303
+ `main`. A manifest that verifies was therefore produced by `data.yml` running on
304
+ `main`. Replacing release assets by hand, or from a workflow on another branch,
305
+ cannot produce one. It does **not** mean anyone reviewed the change: `main`
306
+ accepts a PR with no approvals, so anyone who can merge to `main` can still ship
307
+ data. Requiring approvals on `main`, or required reviewers on the `data-publish`
308
+ environment (which makes every doc publish wait for a person), would close that
309
+ too.
310
+
311
+ **Rotating the key:** generate a new ed25519 pair, add its public key to
312
+ `TRUSTED_KEYS` in `src/data-signing.ts`, release, then replace the
313
+ `DATA_SIGNING_KEY` environment secret and `DATA_SIGNING_PUBLIC_KEY` in `data.yml`.
314
+ Drop the old key in a later release. A lost private key is handled the same way.
315
+
316
+ The index carries its own metadata (`meta` table, `src/data-format.ts`): a schema
317
+ version, the oldest server version that can read it, the build stamp and the
318
+ provider registry. Two rules follow:
319
+
320
+ - **Changing the schema** (`SCHEMA_SQL`) needs `DATA_SCHEMA_VERSION` raised and an
321
+ npm release. Servers read only `manifest-v<their schema>.json`, so older servers
322
+ keep their last compatible data rather than breaking.
323
+ - **Data that relies on new server code** (for example a new `providers.json` field
324
+ the tools must read) needs `MIN_SERVER_VERSION` raised, and that server released
325
+ first. Until then the compatibility check fails, and no installed server would
326
+ accept the build anyway.
327
+
328
+ Code changes, including changes to `src/ingest.ts`, still ship only through a
329
+ release.
330
+
251
331
  ### Cutting a release
252
332
 
253
333
  **Pushing the tag is the release.** `.github/workflows/release.yml` runs on any
package/data/docs.db CHANGED
Binary file
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The on-disk format of the docs index, shared by ingest and the server.
3
+ *
4
+ * The index can reach a server two ways: inside the npm package, or downloaded
5
+ * later from the data-latest release (see data-update.ts). Both paths must agree
6
+ * on what a usable file looks like, so the schema, the metadata keys and the
7
+ * validation all live here.
8
+ */
9
+ import Database from "better-sqlite3";
10
+ import { z } from "zod";
11
+ /** Bump when the table layout changes. Servers only use data with their own version. */
12
+ export declare const DATA_SCHEMA_VERSION = 1;
13
+ /**
14
+ * The oldest server release that can read data built by this code. Raise it when
15
+ * the data starts to rely on server code that older releases lack (a new field in
16
+ * providers.json the tools must read, for example), and release that server first.
17
+ */
18
+ export declare const MIN_SERVER_VERSION = "0.13.0";
19
+ export declare const SCHEMA_SQL = "\n CREATE TABLE IF NOT EXISTS docs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n provider TEXT NOT NULL,\n category TEXT NOT NULL,\n title TEXT NOT NULL,\n content TEXT NOT NULL,\n source_url TEXT,\n source_type TEXT NOT NULL DEFAULT 'curated',\n upstream_version TEXT,\n crawled_at TEXT\n );\n\n CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(\n provider,\n category,\n title,\n content,\n content='docs',\n content_rowid='id',\n tokenize='porter unicode61'\n );\n\n CREATE TRIGGER IF NOT EXISTS docs_ai AFTER INSERT ON docs BEGIN\n INSERT INTO docs_fts(rowid, provider, category, title, content)\n VALUES (new.id, new.provider, new.category, new.title, new.content);\n END;\n\n CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n";
20
+ declare const providerEntrySchema: z.ZodObject<{
21
+ description: z.ZodString;
22
+ display_name: z.ZodString;
23
+ aliases: z.ZodArray<z.ZodString>;
24
+ access_level: z.ZodString;
25
+ licence_status: z.ZodString;
26
+ public_safety_notes: z.ZodString;
27
+ version: z.ZodNullable<z.ZodString>;
28
+ sources: z.ZodArray<z.ZodObject<{
29
+ url: z.ZodOptional<z.ZodString>;
30
+ type: z.ZodString;
31
+ note: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$loose>>;
33
+ last_crawled: z.ZodNullable<z.ZodString>;
34
+ }, z.core.$loose>;
35
+ export declare const providersFileSchema: z.ZodObject<{
36
+ providers: z.ZodRecord<z.ZodString, z.ZodObject<{
37
+ description: z.ZodString;
38
+ display_name: z.ZodString;
39
+ aliases: z.ZodArray<z.ZodString>;
40
+ access_level: z.ZodString;
41
+ licence_status: z.ZodString;
42
+ public_safety_notes: z.ZodString;
43
+ version: z.ZodNullable<z.ZodString>;
44
+ sources: z.ZodArray<z.ZodObject<{
45
+ url: z.ZodOptional<z.ZodString>;
46
+ type: z.ZodString;
47
+ note: z.ZodOptional<z.ZodString>;
48
+ }, z.core.$loose>>;
49
+ last_crawled: z.ZodNullable<z.ZodString>;
50
+ }, z.core.$loose>>;
51
+ }, z.core.$loose>;
52
+ export type ProvidersFile = z.infer<typeof providersFileSchema>;
53
+ export type ProviderRegistryEntry = z.infer<typeof providerEntrySchema>;
54
+ export interface DataMeta {
55
+ schemaVersion: number;
56
+ minServerVersion: string;
57
+ /** ISO-8601 time of the source commit. */
58
+ dataStamp: string;
59
+ /** dataStamp as epoch milliseconds; compare this, never the string. */
60
+ stampMs: number;
61
+ commit: string | null;
62
+ providers: ProvidersFile;
63
+ }
64
+ /** Compare two x.y.z versions; a pre-release suffix is ignored. */
65
+ export declare function compareVersions(a: string, b: string): number;
66
+ /**
67
+ * Read and check the meta table. Returns null when the file predates the table
68
+ * (older releases, and the in-memory databases some tests build).
69
+ */
70
+ export declare function readMeta(db: Database.Database): DataMeta | null;
71
+ export interface MetaInput {
72
+ dataStamp: string;
73
+ commit: string | null;
74
+ providersJson: string;
75
+ }
76
+ /** Replace the meta table's contents. Used by ingest. */
77
+ export declare function writeMeta(db: Database.Database, input: MetaInput): void;
78
+ /** Settings for any docs database this process opens, bundled or downloaded. */
79
+ export declare function hardenConnection(db: Database.Database): void;
80
+ export type ValidationResult = {
81
+ ok: true;
82
+ meta: DataMeta;
83
+ } | {
84
+ ok: false;
85
+ reason: string;
86
+ };
87
+ /**
88
+ * Decide whether a file is a docs index this server can use: the exact schema,
89
+ * a supported schema version, a minimum server version it meets, a valid provider
90
+ * registry and at least one chunk. `integrity` adds a full quick_check, used for
91
+ * freshly downloaded files.
92
+ */
93
+ export declare function validateDatabase(path: string, serverVersion: string, options?: {
94
+ integrity?: boolean;
95
+ }): ValidationResult;
96
+ export {};
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The on-disk format of the docs index, shared by ingest and the server.
3
+ *
4
+ * The index can reach a server two ways: inside the npm package, or downloaded
5
+ * later from the data-latest release (see data-update.ts). Both paths must agree
6
+ * on what a usable file looks like, so the schema, the metadata keys and the
7
+ * validation all live here.
8
+ */
9
+ import Database from "better-sqlite3";
10
+ import { z } from "zod";
11
+ /** Bump when the table layout changes. Servers only use data with their own version. */
12
+ export const DATA_SCHEMA_VERSION = 1;
13
+ /**
14
+ * The oldest server release that can read data built by this code. Raise it when
15
+ * the data starts to rely on server code that older releases lack (a new field in
16
+ * providers.json the tools must read, for example), and release that server first.
17
+ */
18
+ export const MIN_SERVER_VERSION = "0.13.0";
19
+ export const SCHEMA_SQL = `
20
+ CREATE TABLE IF NOT EXISTS docs (
21
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
22
+ provider TEXT NOT NULL,
23
+ category TEXT NOT NULL,
24
+ title TEXT NOT NULL,
25
+ content TEXT NOT NULL,
26
+ source_url TEXT,
27
+ source_type TEXT NOT NULL DEFAULT 'curated',
28
+ upstream_version TEXT,
29
+ crawled_at TEXT
30
+ );
31
+
32
+ CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(
33
+ provider,
34
+ category,
35
+ title,
36
+ content,
37
+ content='docs',
38
+ content_rowid='id',
39
+ tokenize='porter unicode61'
40
+ );
41
+
42
+ CREATE TRIGGER IF NOT EXISTS docs_ai AFTER INSERT ON docs BEGIN
43
+ INSERT INTO docs_fts(rowid, provider, category, title, content)
44
+ VALUES (new.id, new.provider, new.category, new.title, new.content);
45
+ END;
46
+
47
+ CREATE TABLE IF NOT EXISTS meta (
48
+ key TEXT PRIMARY KEY,
49
+ value TEXT NOT NULL
50
+ );
51
+ `;
52
+ const providerSourceSchema = z.looseObject({
53
+ url: z.string().optional(),
54
+ type: z.string(),
55
+ note: z.string().optional(),
56
+ });
57
+ const providerEntrySchema = z.looseObject({
58
+ description: z.string(),
59
+ display_name: z.string(),
60
+ aliases: z.array(z.string()),
61
+ access_level: z.string(),
62
+ licence_status: z.string(),
63
+ public_safety_notes: z.string(),
64
+ version: z.string().nullable(),
65
+ sources: z.array(providerSourceSchema),
66
+ last_crawled: z.string().nullable(),
67
+ });
68
+ export const providersFileSchema = z.looseObject({
69
+ providers: z.record(z.string(), providerEntrySchema),
70
+ });
71
+ /** Compare two x.y.z versions; a pre-release suffix is ignored. */
72
+ export function compareVersions(a, b) {
73
+ const parts = (version) => version
74
+ .split("-")[0]
75
+ .split(".")
76
+ .map((part) => Number.parseInt(part, 10) || 0);
77
+ const [left, right] = [parts(a), parts(b)];
78
+ for (let i = 0; i < 3; i += 1) {
79
+ const diff = (left[i] ?? 0) - (right[i] ?? 0);
80
+ if (diff !== 0)
81
+ return Math.sign(diff);
82
+ }
83
+ return 0;
84
+ }
85
+ function hasMetaTable(db) {
86
+ return Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get());
87
+ }
88
+ /**
89
+ * Read and check the meta table. Returns null when the file predates the table
90
+ * (older releases, and the in-memory databases some tests build).
91
+ */
92
+ export function readMeta(db) {
93
+ if (!hasMetaTable(db))
94
+ return null;
95
+ const rows = db.prepare("SELECT key, value FROM meta").all();
96
+ const values = new Map(rows.map((row) => [row.key, row.value]));
97
+ const schemaVersion = Number.parseInt(values.get("schema_version") ?? "", 10);
98
+ const minServerVersion = values.get("min_server_version") ?? "";
99
+ const dataStamp = values.get("data_stamp") ?? "";
100
+ const stampMs = Date.parse(dataStamp);
101
+ if (!Number.isInteger(schemaVersion))
102
+ throw new Error("meta.schema_version is missing or not an integer");
103
+ if (!/^\d+\.\d+\.\d+/.test(minServerVersion))
104
+ throw new Error("meta.min_server_version is missing");
105
+ if (!Number.isFinite(stampMs))
106
+ throw new Error("meta.data_stamp is missing or not a date");
107
+ let providersJson;
108
+ try {
109
+ providersJson = JSON.parse(values.get("providers_json") ?? "");
110
+ }
111
+ catch {
112
+ throw new Error("meta.providers_json is not JSON");
113
+ }
114
+ const providers = providersFileSchema.safeParse(providersJson);
115
+ if (!providers.success)
116
+ throw new Error("meta.providers_json does not match the provider registry format");
117
+ return {
118
+ schemaVersion,
119
+ minServerVersion,
120
+ dataStamp,
121
+ stampMs,
122
+ commit: values.get("commit") || null,
123
+ providers: providers.data,
124
+ };
125
+ }
126
+ /** Replace the meta table's contents. Used by ingest. */
127
+ export function writeMeta(db, input) {
128
+ const insert = db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)");
129
+ db.transaction(() => {
130
+ db.prepare("DELETE FROM meta").run();
131
+ insert.run("schema_version", String(DATA_SCHEMA_VERSION));
132
+ insert.run("min_server_version", MIN_SERVER_VERSION);
133
+ insert.run("data_stamp", new Date(input.dataStamp).toISOString());
134
+ if (input.commit)
135
+ insert.run("commit", input.commit);
136
+ insert.run("providers_json", input.providersJson);
137
+ })();
138
+ }
139
+ /** FTS5's internal tables. Their SQL is written by SQLite, not by us. */
140
+ const FTS_SHADOW_TABLE = /^docs_fts_(data|idx|content|docsize|config)$/;
141
+ /**
142
+ * The schema as comparable rows. The objects SCHEMA_SQL defines are compared
143
+ * exactly; the FTS5 shadow tables by name and type only, because users' installs
144
+ * may build a different SQLite whose FTS5 writes their SQL differently.
145
+ */
146
+ function schemaRows(db) {
147
+ return db
148
+ .prepare("SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name")
149
+ .all()
150
+ .filter((row) => row.name !== "sqlite_sequence")
151
+ .map((row) => (FTS_SHADOW_TABLE.test(row.name) ? { ...row, sql: null } : row));
152
+ }
153
+ let referenceSchema;
154
+ /** The exact sqlite_master rows a database built from SCHEMA_SQL has. */
155
+ function expectedSchema() {
156
+ if (!referenceSchema) {
157
+ const reference = new Database(":memory:");
158
+ reference.exec(SCHEMA_SQL);
159
+ referenceSchema = JSON.stringify(schemaRows(reference));
160
+ reference.close();
161
+ }
162
+ return referenceSchema;
163
+ }
164
+ /** Settings for any docs database this process opens, bundled or downloaded. */
165
+ export function hardenConnection(db) {
166
+ db.pragma("trusted_schema = OFF");
167
+ db.pragma("cell_size_check = ON");
168
+ }
169
+ /**
170
+ * Decide whether a file is a docs index this server can use: the exact schema,
171
+ * a supported schema version, a minimum server version it meets, a valid provider
172
+ * registry and at least one chunk. `integrity` adds a full quick_check, used for
173
+ * freshly downloaded files.
174
+ */
175
+ export function validateDatabase(path, serverVersion, options = {}) {
176
+ let db;
177
+ try {
178
+ db = new Database(path, { readonly: true, fileMustExist: true });
179
+ hardenConnection(db);
180
+ if (options.integrity) {
181
+ const check = db.pragma("quick_check", { simple: true });
182
+ if (check !== "ok")
183
+ return { ok: false, reason: `integrity check failed (${String(check)})` };
184
+ }
185
+ if (JSON.stringify(schemaRows(db)) !== expectedSchema()) {
186
+ return { ok: false, reason: "schema does not match this server's schema" };
187
+ }
188
+ const meta = readMeta(db);
189
+ if (!meta)
190
+ return { ok: false, reason: "no meta table" };
191
+ if (meta.schemaVersion !== DATA_SCHEMA_VERSION) {
192
+ return { ok: false, reason: `schema version ${meta.schemaVersion}, server reads ${DATA_SCHEMA_VERSION}` };
193
+ }
194
+ if (compareVersions(serverVersion, meta.minServerVersion) < 0) {
195
+ return { ok: false, reason: `needs server ${meta.minServerVersion} or newer (this is ${serverVersion})` };
196
+ }
197
+ if (!db.prepare("SELECT 1 FROM docs LIMIT 1").get())
198
+ return { ok: false, reason: "no chunks" };
199
+ return { ok: true, meta };
200
+ }
201
+ catch (error) {
202
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };
203
+ }
204
+ finally {
205
+ db?.close();
206
+ }
207
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Signatures on data-latest manifests.
3
+ *
4
+ * The publish job in .github/workflows/data.yml signs each manifest with an
5
+ * ed25519 key held only in the data-publish environment, which only workflows
6
+ * running on main can use. Servers accept a manifest only if a key listed here
7
+ * verifies it. Replacing release assets by hand, or from a workflow on another
8
+ * branch, therefore cannot put an index on users' machines: without the key it
9
+ * cannot produce a manifest they accept, and the manifest carries the index's
10
+ * size and SHA-256.
11
+ *
12
+ * To rotate: generate a new key pair, add its public key here, release, then
13
+ * replace the DATA_SIGNING_KEY secret and DATA_SIGNING_PUBLIC_KEY in data.yml.
14
+ * Remove the old key in a later release.
15
+ */
16
+ export interface TrustedKey {
17
+ /** First 16 hex characters of the SHA-256 of the raw public key. */
18
+ id: string;
19
+ /** The raw 32-byte ed25519 public key, base64. */
20
+ publicKey: string;
21
+ }
22
+ export declare const TRUSTED_KEYS: readonly TrustedKey[];
23
+ export declare function keyIdFor(publicKey: string): string;
24
+ export declare class SignatureError extends Error {
25
+ }
26
+ /**
27
+ * Check a signed manifest and return the manifest JSON it carries. The payload
28
+ * is verified as the exact string that was signed, before anything parses it.
29
+ */
30
+ export declare function verifySignedManifest(envelope: unknown, keys?: readonly TrustedKey[]): string;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Signatures on data-latest manifests.
3
+ *
4
+ * The publish job in .github/workflows/data.yml signs each manifest with an
5
+ * ed25519 key held only in the data-publish environment, which only workflows
6
+ * running on main can use. Servers accept a manifest only if a key listed here
7
+ * verifies it. Replacing release assets by hand, or from a workflow on another
8
+ * branch, therefore cannot put an index on users' machines: without the key it
9
+ * cannot produce a manifest they accept, and the manifest carries the index's
10
+ * size and SHA-256.
11
+ *
12
+ * To rotate: generate a new key pair, add its public key here, release, then
13
+ * replace the DATA_SIGNING_KEY secret and DATA_SIGNING_PUBLIC_KEY in data.yml.
14
+ * Remove the old key in a later release.
15
+ */
16
+ import { createHash, createPublicKey, verify } from "node:crypto";
17
+ import { z } from "zod";
18
+ export const TRUSTED_KEYS = [
19
+ { id: "e5a0dcbb72a87e45", publicKey: "1FjljvdILY3mrvrUeK4FqO8KbyYL4iDbTO0nIoNJuO8=" },
20
+ ];
21
+ /** DER prefix that wraps a raw ed25519 public key as SubjectPublicKeyInfo. */
22
+ const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
23
+ export function keyIdFor(publicKey) {
24
+ return createHash("sha256").update(Buffer.from(publicKey, "base64")).digest("hex").slice(0, 16);
25
+ }
26
+ const envelopeSchema = z.object({
27
+ /** The manifest JSON, exactly as signed. */
28
+ payload: z.string(),
29
+ /** Base64 ed25519 signature over the payload's UTF-8 bytes. */
30
+ signature: z.string(),
31
+ key_id: z.string(),
32
+ });
33
+ export class SignatureError extends Error {
34
+ }
35
+ /**
36
+ * Check a signed manifest and return the manifest JSON it carries. The payload
37
+ * is verified as the exact string that was signed, before anything parses it.
38
+ */
39
+ export function verifySignedManifest(envelope, keys = TRUSTED_KEYS) {
40
+ const parsed = envelopeSchema.safeParse(envelope);
41
+ if (!parsed.success)
42
+ throw new SignatureError("signed manifest is malformed");
43
+ const key = keys.find((candidate) => candidate.id === parsed.data.key_id);
44
+ if (!key)
45
+ throw new SignatureError(`manifest is signed with unknown key ${parsed.data.key_id}`);
46
+ const publicKey = createPublicKey({
47
+ key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(key.publicKey, "base64")]),
48
+ format: "der",
49
+ type: "spki",
50
+ });
51
+ const valid = verify(null, Buffer.from(parsed.data.payload, "utf-8"), publicKey, Buffer.from(parsed.data.signature, "base64"));
52
+ if (!valid)
53
+ throw new SignatureError("manifest signature does not verify");
54
+ return parsed.data.payload;
55
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Which docs index the server opens.
3
+ *
4
+ * The npm package ships an index, and data-update.ts can download newer ones
5
+ * into the data directory. The server uses the newest file it can validate.
6
+ * Downloaded files are named by stamp and never overwritten, so several server
7
+ * processes can share the directory without replacing a file another one reads.
8
+ */
9
+ import { type DataMeta } from "./data-format.js";
10
+ export type DataMode = "auto" | "bundled";
11
+ export interface DataSourceOptions {
12
+ /** The index inside the npm package. */
13
+ bundledPath: string;
14
+ /** Where downloaded indexes live. */
15
+ dataDir: string;
16
+ /** This server's package version, checked against each file's min_server_version. */
17
+ serverVersion: string;
18
+ mode: DataMode;
19
+ /** FOOTBALL_DOCS_DB_PATH: use exactly this file. */
20
+ pinnedPath?: string;
21
+ log?: (message: string) => void;
22
+ }
23
+ export interface DataSelection {
24
+ path: string;
25
+ source: "bundled" | "downloaded" | "pinned";
26
+ meta: DataMeta | null;
27
+ }
28
+ export declare function defaultDataDir(env?: NodeJS.ProcessEnv): string;
29
+ /**
30
+ * FOOTBALL_DOCS_DATA picks the mode. Without it, a server running from a git
31
+ * checkout uses its own bundled file, so development and tests always see the
32
+ * working tree's docs and never touch the network or the user's cache.
33
+ */
34
+ export declare function dataModeFor(env: NodeJS.ProcessEnv, packageRoot: string): DataMode;
35
+ export declare function cachedFileName(stampMs: number): string;
36
+ /**
37
+ * Choose the index to open. The newest valid file wins; on a tie the bundled
38
+ * file wins. If the bundled file fails validation (an index built before the
39
+ * meta table existed, in a development checkout) it is still the fallback, so
40
+ * the server behaves as it did before downloads existed.
41
+ */
42
+ export declare function selectDatabase(options: DataSourceOptions): DataSelection;
43
+ /** The newest stamp among downloaded files, or null. Cheap: one directory listing. */
44
+ export declare function newestCachedStamp(dataDir: string): number | null;
45
+ /**
46
+ * Holds the chosen index for a long-running server and chooses again when
47
+ * needed: when the chosen file has gone (another process cleaned it up), or when
48
+ * a newer downloaded file appears. The server may run for days, and another
49
+ * server process sharing the data directory may be the one that downloads the
50
+ * newer file, so this checks the directory on each call rather than waiting for
51
+ * its own update check.
52
+ */
53
+ export declare class IndexChooser {
54
+ private readonly options;
55
+ private selection;
56
+ private newestSeen;
57
+ constructor(options: DataSourceOptions);
58
+ current(): DataSelection;
59
+ }
60
+ /**
61
+ * Remove leftovers from the data directory: temporary downloads older than an
62
+ * hour, and downloaded indexes older than the active one that have not changed
63
+ * for a week. Errors are ignored; a file that cannot be removed now is tried again
64
+ * at the next start.
65
+ */
66
+ export declare function cleanDataDir(dataDir: string, activeStampMs: number | null, now?: number): void;