@opennodes/registry 0.1.53 → 0.1.54

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
@@ -3,14 +3,14 @@
3
3
  The OpenNodes Protocol (ONP) reference registry — an open, federatable discovery service for AI inference nodes.
4
4
 
5
5
  ```bash
6
- npx @opennodes/registry # web app + API on http://127.0.0.1:4300
7
- ONP_DB=./registry.db npx @opennodes/registry # persistent SQLite + persistent signing key
8
- ONP_DB=postgres://user:pass@host/db npx @opennodes/registry
6
+ npx @opennodes/registry@0.1.54 # web app + API on http://127.0.0.1:4300
7
+ ONP_DB=./registry.db npx @opennodes/registry@0.1.54 # persistent SQLite + persistent signing key
8
+ ONP_DB=postgres://user:pass@host/db npx @opennodes/registry@0.1.54
9
9
  ```
10
10
 
11
11
  What it does:
12
12
 
13
- - **Registration with proof of resource** — namespace challenge (HTTP or DNS TXT), Stage A conformance probes, Stage B identity fingerprinting / context verification / capacity ramp, Stage C continuous liveness and blind probes. Trust tiers: `unverified → community → verified` (+ `disputed`, `suspended`). Claimed ≠ measured ≠ attested — always labeled, never blended. The tests cover only chat offerings (`onp.openai.chat/v1`). Speech, embeddings and other offerings are shown with `tested: false` and capped to `unverified`, whatever the node's tier, and listed in node detail and the export feed as `verification.untested_offerings`. A node with no chat offering stays unverified. The web app's qualification page (`/#/qualification`) lists the probe load of each stage: Stage A sends 1 blind call per chat offering at verification and on each `PUT /v0/nodes/{id}/ping`; Stage B sends up to 20 per chat offering when the operator asks for admission; Stage C sends a health check every 5 min and 1 blind call per node every hour, both on average.
13
+ - **Registration with proof of resource** — namespace challenge (HTTP or DNS TXT), Stage A conformance probes, Stage B identity fingerprinting / context verification / capacity ramp, Stage C continuous liveness and blind probes. Trust tiers: `unverified → community → verified` (+ `disputed`, `suspended`). Claimed ≠ measured ≠ attested — always labeled, never blended. The tests cover only chat offerings (`onp.openai.chat/v1`). Speech, embeddings and other offerings are shown with `tested: false` and capped to `unverified`, whatever the node's tier, and listed in node detail and the export feed as `verification.untested_offerings`. A node with no chat offering stays unverified. The web app's qualification page (`/#/qualification`) lists the probe load of each stage: Stage A sends 1 blind call per chat offering at verification and on each `PUT /v0/nodes/{id}/ping`; Stage A runs again at least every 6 h; Stage B sends up to 20 per chat offering, on the registry's own schedule (after a node reaches community, after a change, and at a random time up to 91 days after a pass; `POST /v0/nodes/{id}/admit` is admin-only); Stage C sends a health check every 5 min and 1 blind call per node every hour, both on average. Every probe prompt comes from the registry's private probe corpus (`ONP_PROBE_CORPUS`; format in `src/corpus.js`), never from text in the source. No identity reference for a model's artefact means no `verified`; a proprietary artefact (`urn:proprietary:{vendor}:…`) is admitted only from the vendor's namespace (`GET /v0/vendors`); a dispute ends only with a resolution the admin records (`POST /v0/admin/nodes/{id}/resolve`); an unsigned card never reaches `verified`.
14
14
  - **Operator marks** (ONP-3 §4b): `institutional` and `founding`, set by the registry admin on registered nodes and shown in `/v0/nodes`, node detail, search results and the web app. Labels only, never rank inputs:
15
15
 
16
16
  ```bash
@@ -21,7 +21,8 @@ What it does:
21
21
  The same request with `{"founding": false}` clears the mark; `/institutional` takes `{"institutional": true|false}`.
22
22
  - **Trusted and open pools** (ONP-3 §5e):
23
23
  - **Who lists:** any operator, from any country.
24
- - **Search filters:** `trust=trusted` returns only offerings for personal data: declared model lineage without CN, tier verified or higher, an operator in the trusted jurisdictions, `retention: none` and no training on inputs. Each part is also a filter of its own: `lineage=declared`, `exclude_lineage=CN`, `retention=none|ephemeral|logged`, `no_training=true`, `jurisdiction=`, `tier=`.
24
+ - **Search filters:** `trust=trusted` returns only offerings for personal data: declared model lineage without CN, tier verified or higher, an operator that declares a country in the trusted jurisdictions, a passing server-location check, and a declared `retention: none` and no training on inputs. Each part is also a filter of its own: `lineage=declared`, `exclude_lineage=CN`, `retention=none|ephemeral|logged`, `no_training=true`, `jurisdiction=`, `server_check=passed`, `tier=`.
25
+ - **Server-location checks** (`ONP_LOCATION=1`, ONP-3 §6.4) are required for a hosted trusted pool: without them no hosted offering passes the server check, and the registry warns at start. Every hosted result carries `jurisdiction.server_check` and `jurisdiction.evidence`; behind a CDN, the origin addresses a card declares (`endpoints.origin_addresses`) are checked instead.
25
26
  - **Labels:** every result carries `pool: "trusted"` or `"open"`.
26
27
  - **Recommend:** `policy.sensitive: true` uses the trusted pool, always under the registry's own view.
27
28
  - **Configuration:** `ONP_TRUSTED_JURISDICTIONS` (default `EU,CA`) sets the trusted countries, and `/v0/health` publishes the view as `trust.trusted`.
@@ -34,7 +35,7 @@ What it does:
34
35
  - **MCP surface** at `/mcp` (including `find_locations` and `find_residency`) and a signed **export feed** for federation.
35
36
  - **Web app** at `/`: OpenRouter-style catalog with model and node pages, hardware and measured performance, playground, multi-model chat (compare / jury / pipeline / iterative), the advisor, the Node Builder, and the "Where models run" page.
36
37
 
37
- Environment: `PORT`, `ONP_DB`, `ONP_REGISTRY_KEY`, `ONP_ADMIN_TOKEN`, `ONP_TRUSTED_JURISDICTIONS` (trusted pool operators, default `EU,CA`), `ONP_ALLOW_PRIVATE=1` (dev only: permit localhost nodes), `ONP_STAGE_C=0`, `ONP_REIMPORT=1`, `ONP_REIMPORT_SOURCES` (default `openrouter,huggingface`; also `models-dev`, `ollama`, and `openrouter-providers`, which makes one request per OpenRouter model, so give it a long `ONP_REIMPORT_MS`), `ONP_LOCATION_SEEDS=0` (skip the curated location seeds), `ONP_MAP_TILES` (basemap for the locations map: unset = OpenStreetMap, `off` = no map, or an XYZ URL template with `ONP_MAP_ATTRIBUTION`). The map loads Leaflet from cdnjs, pinned with subresource integrity, only on the "Where models run" page. Viewers' browsers then fetch tiles from the tile server. OpenStreetMap's tile policy asks for light use, so a busy registry should point `ONP_MAP_TILES` at its own or a commercial tile service.
38
+ Environment: `PORT`, `ONP_DB`, `ONP_REGISTRY_KEY`, `ONP_ADMIN_TOKEN`, `ONP_TRUSTED_JURISDICTIONS` (trusted pool operators, default `EU,CA`), `ONP_LOCATION=1` (server-location checks; the trusted pool needs them), `ONP_ALLOW_PRIVATE=1` (dev only: permit localhost nodes), `ONP_STAGE_C=0`, `ONP_REIMPORT=1`, `ONP_REIMPORT_SOURCES` (default `openrouter,huggingface`; also `models-dev`, `ollama`, and `openrouter-providers`, which makes one request per OpenRouter model, so give it a long `ONP_REIMPORT_MS`), `ONP_LOCATION_SEEDS=0` (skip the curated location seeds), `ONP_MAP_TILES` (basemap for the locations map: unset = OpenStreetMap, `off` = no map, or an XYZ URL template with `ONP_MAP_ATTRIBUTION`). The map loads Leaflet from cdnjs, pinned with subresource integrity, only on the "Where models run" page. Viewers' browsers then fetch tiles from the tile server. OpenStreetMap's tile policy asks for light use, so a busy registry should point `ONP_MAP_TILES` at its own or a commercial tile service.
38
39
 
39
40
  Location seeds are dated JSON files (`locations-{seed}.json`): providers, their sites with `basis`, `source` and `checked`, and the models each site serves. A provider whose models are listed becomes a listing-only node `import.seed.{seed}.{id}`; one that publishes no model list is shown with a note. An entry with `nodes` describes existing registry nodes instead: its sites are shown under the first of them, with that node's models when `placement` is `all`. With `placement: "all"`, or `serves_from: "{seed}:{id}"` (the node's whole API runs at that entry's sites), search and recommend also use the live sites as the node's serving locations, marked `via: "seed"`, for offerings whose card declares none, except for listings reached through the Hugging Face router or OpenRouter. Providers carry `kind` and `residency`; `residency_of: "{seed}:{id}"` reuses another entry's commitments (the Canadian and European regions of a cloud share the cloud's). Corrections and new countries are welcome by pull request: cite the provider's own page for `documented`, anything else is `claimed`.
40
41
 
package/bin.js CHANGED
@@ -14,7 +14,15 @@ const registry = await startRegistry({
14
14
  keyPath: process.env.ONP_REGISTRY_KEY ?? (persistent ? `${dbPath}.key.pem` : (dbPath.startsWith('postgres') ? 'onp-registry-key.pem' : null)),
15
15
  allowPrivateTargets: process.env.ONP_ALLOW_PRIVATE === '1', // dev only: permit localhost nodes
16
16
  registerPerHour: Number(process.env.ONP_REGISTER_PER_HOUR ?? 30), // per client address
17
- admitCooldownMs: Number(process.env.ONP_ADMIT_COOLDOWN_MS ?? 30 * 60_000), // Stage B per node
17
+ // Probe prompts for Stages A, B and C: a private JSON file (impl/packages/registry/src/corpus.js
18
+ // has the format). Unset = the public built-in corpus, which nodes can recognise: dev only.
19
+ probeCorpus: process.env.ONP_PROBE_CORPUS || null,
20
+ // Stage A at least every 6 h and Stage B quarterly, on change and after reaching community
21
+ // (ONP-3 §4a). ONP_SCHEDULE=0 turns the timetable off; Stage B then runs only on admin request.
22
+ schedule: process.env.ONP_SCHEDULE === '0' ? null : {
23
+ ...(process.env.ONP_STAGE_A_MS ? { stageAIntervalMs: Number(process.env.ONP_STAGE_A_MS) } : {}),
24
+ ...(process.env.ONP_STAGE_B_MS ? { stageBIntervalMs: Number(process.env.ONP_STAGE_B_MS) } : {}),
25
+ },
18
26
  trustProxy: process.env.ONP_TRUST_PROXY === '1', // behind Caddy / a CDN
19
27
  adminToken: process.env.ONP_ADMIN_TOKEN ?? null,
20
28
  // Operator jurisdictions of the trusted pool (ONP-3 §5e): "EU,CA" unless set, e.g. "EU,CA,CH".
@@ -42,5 +50,6 @@ const registry = await startRegistry({
42
50
  } : null,
43
51
  });
44
52
  if (process.env.ONP_ALLOW_PRIVATE === '1') console.log('WARNING: SSRF guard disabled (ONP_ALLOW_PRIVATE=1) — dev only');
53
+ if (!process.env.ONP_PROBE_CORPUS) console.log('WARNING: no private probe corpus (ONP_PROBE_CORPUS): probes use the public built-in prompts, which nodes can recognise — dev only');
45
54
  console.log(`opennodes registry listening at ${registry.origin}`);
46
55
  console.log(`health: ${registry.origin}/v0/health`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opennodes/registry",
3
- "version": "0.1.53",
3
+ "version": "0.1.54",
4
4
  "description": "OpenNodes (ONP) reference registry: node registration with proof-of-resource qualification (Stage A/B/C), transparent ranking, enforceable estimates, catalog importers (OpenRouter, Hugging Face, models.dev, Ollama), MCP surface, and the web app (catalog, chat, advisor, Node Builder)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -43,7 +43,7 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@opennodes/core": "0.1.24",
46
+ "@opennodes/core": "0.1.25",
47
47
  "pg": "^8.13.1"
48
48
  }
49
49
  }
package/src/corpus.js ADDED
@@ -0,0 +1,166 @@
1
+ // Probe prompts (ONP-3 §4a). Every chat request the registry sends to a node, in Stages A, B and C,
2
+ // takes its text from a corpus, so a node cannot tell a probe from a customer's request by its words.
3
+ // A production registry keeps its corpus private: a JSON file outside the public source, named by
4
+ // ONP_PROBE_CORPUS. Without one the registry falls back to the small built-in corpus below, which is
5
+ // public and therefore fit only for development and tests; /v0/health says which one is in use.
6
+ //
7
+ // File format (every list is an array of non-empty strings, except `needles`):
8
+ // {
9
+ // "chat": ["short, ordinary requests"], // Stage A, the capacity ramp, Stage C blind probes (5 or more)
10
+ // "identity": ["prompts for identity references"], // optional, defaults to chat
11
+ // "filler": ["long passages of plain prose"], // the context probes' haystack
12
+ // "needles": [{"fact": "… {n} …", "question": "…"}] // the fact hidden in the haystack ({n}: an 8-digit number)
13
+ // }
14
+ // Identity prompts must read like the chat prompts (same kind of request, length and tone), or be
15
+ // left out so that references are captured from chat prompts: Stage C asks some of them in blind
16
+ // probes (stagec.js), which only work if a node cannot pick them out from the ordinary ones.
17
+ import { readFileSync } from 'node:fs';
18
+
19
+ /**
20
+ * Identity prompts of registries before revision 11. They were public, so a reference captured
21
+ * with them proves nothing: Stage B ignores such references. Kept only to recognise them.
22
+ */
23
+ export const LEGACY_IDENTITY_PROMPTS = Object.freeze([
24
+ 'ONP identity probe 1: repeat exactly: correlation-4417',
25
+ 'ONP identity probe 2: repeat exactly: meridian-9022',
26
+ 'ONP identity probe 3: repeat exactly: basalt-7301',
27
+ ]);
28
+
29
+ /** How many identity references a capture stores, and how many of them one Stage B run asks. */
30
+ export const IDENTITY_CAPTURE = 8;
31
+ export const IDENTITY_SAMPLE = 3;
32
+
33
+ const DEFAULT_NEEDLE = Object.freeze({
34
+ fact: 'The magic number is {n}.',
35
+ question: 'What is the magic number mentioned in the text above? Reply with the number only.',
36
+ });
37
+
38
+ /** Development corpus. Public, so nothing in it ever counts as private. */
39
+ export const BUILTIN_CORPUS = Object.freeze({
40
+ chat: Object.freeze([
41
+ 'What is the capital of Portugal?',
42
+ 'Give me three name ideas for a small neighbourhood bakery.',
43
+ 'Translate "good morning, how are you?" into German.',
44
+ 'Write one sentence describing an autumn afternoon.',
45
+ 'Convert 25 degrees Celsius to Fahrenheit.',
46
+ 'Suggest a short subject line for an email about a rescheduled meeting.',
47
+ 'List two benefits of stretching before a run.',
48
+ 'Explain what a prime number is in one sentence.',
49
+ 'Rewrite this more politely: send me the report now.',
50
+ 'What does HTTP stand for?',
51
+ 'Give a one-line tip for writing clear commit messages.',
52
+ 'Which is larger, a kilobyte or a megabyte?',
53
+ 'Name a vegetable that grows well in cold weather.',
54
+ 'What is a haiku? Answer briefly.',
55
+ 'Summarise in a few words: the library is open late during exam week.',
56
+ 'How many minutes are there in three hours?',
57
+ ]),
58
+ identity: Object.freeze([
59
+ 'Spell the word "necessary" backwards.',
60
+ 'List the first five prime numbers, separated by commas.',
61
+ 'What is 17 multiplied by 23? Answer with the number only.',
62
+ 'Name the planets of the solar system in order from the Sun.',
63
+ 'Write the letters of the alphabet from F to M.',
64
+ 'Give the plural of "cactus" and of "mouse".',
65
+ 'Which month comes two months after October?',
66
+ 'Complete the sequence: 2, 4, 8, 16, ...',
67
+ 'Name three primary colours.',
68
+ 'What is the chemical symbol for gold?',
69
+ ]),
70
+ filler: Object.freeze([
71
+ 'The town council met on Tuesday evening to discuss the new cycle lanes along the river road. '
72
+ + 'Residents raised questions about parking, delivery vans and the timing of the works, and the '
73
+ + 'engineers promised a second round of drawings before the summer. ',
74
+ 'In the old orchard behind the school the apple trees are pruned every February. The children help '
75
+ + 'gather the cut branches, which are dried and burned in the autumn bonfire, and the best fruit '
76
+ + 'goes to the harvest market in the square. ',
77
+ 'A good loaf needs flour, water, salt and time. Bakers who let the dough rise slowly overnight say '
78
+ + 'the crust is darker and the crumb more open, while quicker methods give a softer bread that keeps '
79
+ + 'for fewer days. ',
80
+ 'The ferry leaves the harbour at half past seven and calls at two islands before turning back. On '
81
+ + 'calm days passengers sit on the upper deck, and in winter the café below serves soup and tea to '
82
+ + 'the few commuters who make the crossing. ',
83
+ ]),
84
+ needles: Object.freeze([DEFAULT_NEEDLE]),
85
+ });
86
+
87
+ const strings = (value, name, { min = 1 } = {}) => {
88
+ if (!Array.isArray(value) || value.length < min || !value.every((s) => typeof s === 'string' && s.trim().length > 0 && s.length <= 20_000)) {
89
+ throw new Error(`probe corpus: "${name}" must be a list of at least ${min} non-empty strings`);
90
+ }
91
+ return Object.freeze([...value]);
92
+ };
93
+
94
+ const needlesOf = (value) => {
95
+ if (!Array.isArray(value) || !value.length || !value.every((n) => typeof n?.fact === 'string' && n.fact.includes('{n}') && typeof n?.question === 'string' && n.question.trim())) {
96
+ throw new Error('probe corpus: "needles" must be a list of {fact, question} with "{n}" in each fact');
97
+ }
98
+ return Object.freeze(value.map((n) => Object.freeze({ fact: n.fact, question: n.question })));
99
+ };
100
+
101
+ const pickFrom = (list, random) => list[Math.floor(random() * list.length)];
102
+
103
+ /** k distinct items of `list` in random order (all of them when k >= list.length). */
104
+ export function sample(list, k, random = Math.random) {
105
+ const copy = [...list];
106
+ for (let i = copy.length - 1; i > 0; i--) {
107
+ const j = Math.floor(random() * (i + 1));
108
+ [copy[i], copy[j]] = [copy[j], copy[i]];
109
+ }
110
+ return copy.slice(0, Math.max(0, k));
111
+ }
112
+
113
+ /**
114
+ * The registry's probe corpus. `source`: null (built-in), a path to a JSON file, or an object in
115
+ * the file format. A file that cannot be read or parsed is an error: a registry configured for a
116
+ * private corpus must never fall back to the public one silently.
117
+ */
118
+ export function loadCorpus(source = null, { random = Math.random } = {}) {
119
+ let raw = null, origin = 'built-in';
120
+ if (typeof source === 'string' && source) {
121
+ raw = JSON.parse(readFileSync(source, 'utf8'));
122
+ origin = 'file';
123
+ } else if (source && typeof source === 'object') {
124
+ raw = source;
125
+ origin = 'inline';
126
+ }
127
+ const isPrivate = raw !== null;
128
+ const base = raw ?? BUILTIN_CORPUS;
129
+ // A private corpus brings everything: a public haystack or needle question would give the
130
+ // context probes away even if every short prompt were private.
131
+ const chat = strings(base.chat, 'chat', { min: isPrivate ? 5 : 1 });
132
+ const identity = base.identity == null ? chat : strings(base.identity, 'identity');
133
+ const filler = strings(base.filler, 'filler');
134
+ const needles = needlesOf(base.needles);
135
+ const builtinPrompts = new Set([...BUILTIN_CORPUS.chat, ...BUILTIN_CORPUS.identity]);
136
+ const legacy = new Set(LEGACY_IDENTITY_PROMPTS);
137
+
138
+ return Object.freeze({
139
+ private: isPrivate,
140
+ origin,
141
+ chat, identity, filler, needles,
142
+ /** One ordinary request for Stage A, the capacity ramp or a blind probe. */
143
+ chatPrompt: () => pickFrom(chat, random),
144
+ /** Prompts for a reference capture. */
145
+ identityPrompts: (k = IDENTITY_CAPTURE) => sample(identity, k, random),
146
+ needle: () => pickFrom(needles, random),
147
+ /** `chars` characters of haystack, from the filler passages in random order. */
148
+ haystack(chars) {
149
+ const n = Math.max(0, Math.floor(chars));
150
+ let out = '';
151
+ while (out.length < n) out += sample(filler, filler.length, random).join('');
152
+ return out.slice(0, n);
153
+ },
154
+ /**
155
+ * Whether a stored reference may vouch for identity: never one captured with a legacy public
156
+ * prompt, and, once the corpus is private, never one captured with a built-in prompt.
157
+ */
158
+ usableReference: (prompt) => !legacy.has(prompt) && !(isPrivate && builtinPrompts.has(prompt)),
159
+ /** What /v0/health publishes: whether the corpus is private and its size, never its contents. */
160
+ summary: () => ({
161
+ private: isPrivate,
162
+ prompts: { chat: chat.length, identity: identity.length, filler: filler.length, needles: needles.length },
163
+ ...(isPrivate ? {} : { note: 'built-in development corpus: public, so nodes can recognise its probes' }),
164
+ }),
165
+ });
166
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "about": "Namespaces that may claim urn:proprietary:{vendor}:* artefacts (ONP-3 §6.3). A vendor listed here is admitted only from a node id inside one of its namespaces; any other vendor slug only from the node's own namespace (the id's second label). Registry admins add or replace entries with POST /v0/admin/vendors/{vendor}.",
3
+ "vendors": {
4
+ "openai": ["com.openai"],
5
+ "anthropic": ["com.anthropic"],
6
+ "google": ["com.google", "com.googleapis"],
7
+ "mistral": ["ai.mistral"],
8
+ "cohere": ["com.cohere", "ai.cohere"],
9
+ "deepseek": ["com.deepseek"],
10
+ "xai": ["ai.x"]
11
+ }
12
+ }
package/src/importers.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // Imported records enter as unverified, unsigned, source='import', and are
3
3
  // excluded from verified tiers until claimed by their operator.
4
4
  import { validateCard } from '@opennodes/core';
5
+ import { ARTIFACT } from './vendors.js';
5
6
 
6
7
  const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 100);
7
8
  const vendorSlug = (s) => slug(s).replace(/[._]/g, '-');
@@ -299,7 +300,8 @@ export async function importOllamaLibrary(store, entries) {
299
300
  model: {
300
301
  name: e.name,
301
302
  family: vendorSlug(e.name.split(/[.:0-9]/)[0] || e.name),
302
- artifact: `urn:proprietary:ollama:${vendorSlug(e.name)}`,
303
+ // Library models are open weights with a public record: ollama:{name} (ONP-2 §5), not a proprietary URN.
304
+ artifact: ARTIFACT.test(`ollama:${e.name}`) ? `ollama:${e.name}` : `urn:proprietary:ollama:${vendorSlug(e.name)}`,
303
305
  ...(paramsCandidates.length ? { params_b: Math.max(...paramsCandidates) } : {}),
304
306
  ...(e.description ? { description: String(e.description).slice(0, 500) } : {}),
305
307
  },
package/src/location.js CHANGED
@@ -8,14 +8,38 @@
8
8
  // is a soft warning (congestion or a forwarding hop can also cause it).
9
9
  // A front server that forwards requests elsewhere still defeats both; attested residency
10
10
  // (an auditor's credential) is the strong guarantee, planned for Draft 0.2.
11
+ // Behind a CDN the front says nothing, so an operator may declare in its signed card the origin
12
+ // addresses that serve the API (ONP-2 §4 `endpoints.origin_addresses`): each one must present a
13
+ // publicly trusted certificate for the API host, answer the API's model list exactly as the API
14
+ // does through the CDN, and is then located the same way. Unsigned cards' origins count for nothing.
11
15
  import net from 'node:net';
16
+ import https from 'node:https';
12
17
  import dns from 'node:dns/promises';
13
- import { EEA_COUNTRIES, distanceKm } from '@opennodes/core';
18
+ import { EEA_COUNTRIES, SERVER_CHECK_PASSES, distanceKm } from '@opennodes/core';
14
19
  import { isPrivateHost } from './namespace.js';
15
20
 
16
21
  const RIPESTAT = 'https://stat.ripe.net/data';
17
22
  const LOOKUP_TIMEOUT_MS = 30_000;
18
23
  const KM_PER_MS_RTT = 100; // ~2/3 c in fibre, out and back
24
+ /** At most this many declared origin addresses are checked; a card that declares more fails the origin check. */
25
+ export const MAX_ORIGIN_ADDRESSES = 4;
26
+
27
+ // Addresses an operator-declared origin may never be: the registry must not be steered into its own
28
+ // network. (Documentation ranges stay allowed: they are not routable, and tests use them.)
29
+ const NON_PUBLIC = new net.BlockList();
30
+ for (const [a, p] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
31
+ ['172.16.0.0', 12], ['192.168.0.0', 16], ['224.0.0.0', 4], ['240.0.0.0', 4]]) NON_PUBLIC.addSubnet(a, p, 'ipv4');
32
+ for (const [a, p] of [['::', 127], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8]]) NON_PUBLIC.addSubnet(a, p, 'ipv6');
33
+
34
+ /** A public unicast IP literal (v4 or v6)? An IPv4-mapped IPv6 address is judged by its IPv4 part. */
35
+ export function isPublicAddress(ip) {
36
+ const text = String(ip).toLowerCase();
37
+ const mapped = text.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
38
+ if (mapped) return isPublicAddress(mapped[1]);
39
+ const family = net.isIP(text);
40
+ if (family === 6 && text.startsWith('::ffff:')) return false; // mapped, in hex form: refuse rather than decode
41
+ return family !== 0 && !NON_PUBLIC.check(text, family === 6 ? 'ipv6' : 'ipv4');
42
+ }
19
43
 
20
44
  /** Networks whose addresses are anycast / CDN edges: their IP says nothing about where inference runs. */
21
45
  export const CDN_ASNS = new Map([
@@ -120,23 +144,9 @@ export async function remoteRtt(agent, host, fetchImpl = fetch) {
120
144
  return { site: body.site ?? agent.site, lat: body.lat ?? agent.lat, lon: body.lon ?? agent.lon, rtt_ms: body.rtt_ms ?? null };
121
145
  }
122
146
 
123
- /**
124
- * Check one node: resolve its API host, geolocate the first public IPv4, measure RTT from every
125
- * probe site, and compare with the declared country.
126
- * opts: { selfSite: {site, lat, lon}, agents: [{site, lat, lon, url, token}], fetchImpl, resolve, rtt }
127
- */
128
- export async function checkNodeLocation(card, opts = {}) {
147
+ /** Geolocate one address, measure RTT to it from every probe site, and compare with the declared country. */
148
+ async function locateAddress(ip, declared, opts) {
129
149
  const fetchImpl = opts.fetchImpl ?? fetch;
130
- let host = null;
131
- try { host = new URL(card?.endpoints?.openai).hostname; } catch { /* listing without an API */ }
132
- const declared = card?.node?.operator?.country ? String(card.node.operator.country).toUpperCase() : null;
133
- const out = { host, declared, checked_at: new Date().toISOString() };
134
- if (!host) return { ...out, verdict: 'unknown', reason: 'no API endpoint' };
135
-
136
- const ips = net.isIP(host) ? [host] : await (opts.resolve ?? ((h) => dns.resolve4(h)))(host).catch(() => []);
137
- const ip = ips.find((a) => !isPrivateHost(a));
138
- if (!ip) return { ...out, ips, verdict: 'unknown', reason: 'no public IPv4 address' };
139
-
140
150
  const server = await lookupIp(ip, { fetchImpl, asHolders: opts.asHolders });
141
151
  const vantages = [];
142
152
  const rtt = opts.rtt ?? measureRtt;
@@ -150,13 +160,153 @@ export async function checkNodeLocation(card, opts = {}) {
150
160
  let verdict = countryVerdict(declared, server);
151
161
  if (latency.verdict === 'too_fast' && verdict !== 'cdn') verdict = 'inconsistent'; // the geolocation itself is wrong
152
162
  return {
153
- ...out, ips,
154
163
  server: { country: server.country, city: server.city, asn: server.asn, network: server.network, cdn: server.cdn },
155
164
  verdict,
156
165
  latency,
157
166
  };
158
167
  }
159
168
 
169
+ /** The most of a model list an origin check reads; a longer answer counts as no list. */
170
+ const MAX_LIST_BYTES = 1_000_000;
171
+
172
+ /** The model ids of an OpenAI-style list (`{"data": [{"id": …}]}`), unique and sorted; null when the body is not one. */
173
+ export function modelIds(body) {
174
+ try {
175
+ const data = JSON.parse(body)?.data;
176
+ if (!Array.isArray(data)) return null;
177
+ return [...new Set(data.map((m) => m?.id).filter((id) => typeof id === 'string' && id))].sort();
178
+ } catch { return null; }
179
+ }
180
+
181
+ /**
182
+ * Ask the server at `ip` for the API, as the API host: it must complete a TLS handshake for `host` (SNI)
183
+ * with a certificate valid for that name under the public CA roots, then answer GET `path` with Host:
184
+ * `host` (and `headers`, such as the registry's probe credential, sent only after the certificate is
185
+ * accepted). Connects to the address itself on port 443: no DNS, no redirects. `ok` when the handshake
186
+ * completes and the status is below 500; `models` is the model list when the answer is 200 with an
187
+ * OpenAI-style list, else null. Used for the CDN front and for each declared origin alike. (`ca` replaces
188
+ * the public roots in tests only.)
189
+ */
190
+ export function probeOrigin(ip, host, { path = '/', headers = {}, timeoutMs = 10_000, port = 443, ca } = {}) {
191
+ return new Promise((resolve) => {
192
+ // One deadline for the whole exchange: the socket's idle timeout alone would let a server that
193
+ // drips its answer hold the check (and the daily sweep behind it) open.
194
+ let deadline = null;
195
+ const settle = (result) => { clearTimeout(deadline); resolve(result); };
196
+ const req = https.request({
197
+ host: ip, port, servername: host, path, method: 'GET', agent: false, timeout: timeoutMs, ...(ca ? { ca } : {}),
198
+ headers: { ...headers, host, accept: 'application/json', 'user-agent': 'opennodes-registry (origin check)' },
199
+ }, (res) => {
200
+ const status = res.statusCode;
201
+ const chunks = [];
202
+ let size = 0;
203
+ const done = () => {
204
+ const models = status === 200 && size <= MAX_LIST_BYTES ? modelIds(Buffer.concat(chunks).toString('utf8')) : null;
205
+ settle(status < 500 ? { ok: true, status, models } : { ok: false, status, models: null, reason: `HTTP ${status} for ${path}` });
206
+ };
207
+ res.on('data', (chunk) => { size += chunk.length; if (size > MAX_LIST_BYTES) res.destroy(); else chunks.push(chunk); });
208
+ res.on('end', done);
209
+ res.on('close', done); // also after a destroy: an over-long answer has no list
210
+ });
211
+ deadline = setTimeout(() => { settle({ ok: false, reason: 'timed out' }); req.destroy(); }, timeoutMs);
212
+ req.on('timeout', () => req.destroy(Object.assign(new Error('timed out'), { code: 'timed out' })));
213
+ req.on('error', (err) => settle({ ok: false, reason: err.code === 'ERR_TLS_CERT_ALTNAME_INVALID' ? `certificate not valid for ${host}` : String(err.code ?? err.message) }));
214
+ req.end();
215
+ });
216
+ }
217
+
218
+ /** What an origin check requests, from the front and from each origin: the API's model list, `{api path}/models`. */
219
+ function originProbePath(card) {
220
+ const api = new URL(card.endpoints.openai);
221
+ return `${api.pathname.replace(/\/$/, '')}/models`;
222
+ }
223
+
224
+ /** How two model lists differ, in words; null when they hold the same ids. */
225
+ function listDifference(origin, front) {
226
+ const have = new Set(origin), want = new Set(front);
227
+ const missing = front.filter((id) => !have.has(id)).length, extra = origin.filter((id) => !want.has(id)).length;
228
+ return missing || extra ? `lists other models than the API through the CDN (${missing} missing, ${extra} more)` : null;
229
+ }
230
+
231
+ /**
232
+ * Behind a CDN: check every origin address the card declares (`endpoints.origin_addresses`, ONP-2 §4).
233
+ * The declaration counts only in a signed card (`opts.signed`): it is the operator's signed statement of
234
+ * where the API runs. The registry first asks the API for its model list through the CDN (the front
235
+ * address `opts.frontIp`, with the key it probes with, `opts.key`); with no list there is nothing to
236
+ * compare, and the check fails. Each origin must then be (or resolve to) a public address, answer the
237
+ * same request as the API host with the same model list (probeOrigin), and be located with match or
238
+ * same_region; one that sits on a CDN network itself is `cdn`, not an origin. The result's verdict is
239
+ * `match` or `same_region` only when every declared address passes. Null when none is declared.
240
+ */
241
+ export async function checkOrigins(card, host, declared, opts = {}) {
242
+ const listed = declaredOrigins(card);
243
+ if (!listed.length) return null;
244
+ const signed = opts.signed !== false;
245
+ const fail = (reason, extra = {}) => ({ declared: listed, signed, verdict: 'unknown', reason, ...extra, addresses: [] });
246
+ if (!signed) return fail('origin addresses count only in a signed card (ONP-2 §8)');
247
+ if (listed.length > MAX_ORIGIN_ADDRESSES) return fail(`more than ${MAX_ORIGIN_ADDRESSES} origin addresses declared`);
248
+ const probe = opts.probeOrigin ?? probeOrigin;
249
+ const target = { path: originProbePath(card), headers: opts.key ? { authorization: `Bearer ${opts.key}` } : {} };
250
+ const asked = (ip) => probe(ip, host, target).catch((err) => ({ ok: false, reason: String(err.message) }));
251
+ // What the API answers through the CDN: every origin must give the same answer.
252
+ const front = opts.frontIp ? await asked(opts.frontIp) : { ok: false, reason: 'no front address' };
253
+ if (!front.models?.length) {
254
+ const why = front.models ? 'an empty list' : front.status ? `HTTP ${front.status}` : front.reason;
255
+ return fail(`the API gives the registry no model list through the CDN (${why}), so no origin can be compared with it`,
256
+ { front: { status: front.status ?? null, models: 0 } });
257
+ }
258
+ const addresses = [];
259
+ for (const address of listed) {
260
+ const ips = net.isIP(address) ? [address] : await (opts.resolve ?? ((h) => dns.resolve4(h)))(address).catch(() => []);
261
+ const ip = ips.find(isPublicAddress);
262
+ if (!ip) { addresses.push({ address, verdict: 'unknown', reason: ips.length ? 'not a public address' : 'does not resolve' }); continue; }
263
+ const serves = await asked(ip);
264
+ if (!serves.ok) { addresses.push({ address, ip, verdict: 'unknown', reason: `does not serve ${host}: ${serves.reason}` }); continue; }
265
+ const differs = serves.models ? listDifference(serves.models, front.models)
266
+ : `does not answer like the API through the CDN (HTTP ${serves.status}${serves.status === 200 ? ', no model list' : ''})`;
267
+ if (differs) { addresses.push({ address, ip, verdict: 'unknown', reason: differs }); continue; }
268
+ const located = await locateAddress(ip, declared, opts);
269
+ addresses.push({ address, ip, serves: true, server_country: located.server.country, ...located });
270
+ }
271
+ const failed = addresses.find((a) => !SERVER_CHECK_PASSES.includes(a.verdict));
272
+ return {
273
+ declared: listed,
274
+ signed,
275
+ front: { status: front.status, models: front.models.length },
276
+ verdict: failed ? failed.verdict : addresses.every((a) => a.verdict === 'match') ? 'match' : 'same_region',
277
+ addresses,
278
+ };
279
+ }
280
+
281
+ /** The card's `endpoints.origin_addresses`, normalised (trimmed, IPv6 brackets removed); [] when none. */
282
+ export function declaredOrigins(card) {
283
+ const listed = card?.endpoints?.origin_addresses;
284
+ return Array.isArray(listed) ? listed.map((a) => String(a).trim().replace(/^\[|\]$/g, '')).filter(Boolean) : [];
285
+ }
286
+
287
+ /**
288
+ * Check one node: resolve its API host, geolocate the first public IPv4, measure RTT from every
289
+ * probe site, and compare with the declared country. Behind a CDN, also check the origin addresses
290
+ * the card declares (`origin`).
291
+ * opts: { selfSite: {site, lat, lon}, agents: [{site, lat, lon, url, token}], fetchImpl, resolve, rtt, probeOrigin,
292
+ * key (the credential the registry probes the node with), signed (whether its card's signature verified) }
293
+ */
294
+ export async function checkNodeLocation(card, opts = {}) {
295
+ let host = null;
296
+ try { host = new URL(card?.endpoints?.openai).hostname; } catch { /* listing without an API */ }
297
+ const declared = card?.node?.operator?.country ? String(card.node.operator.country).toUpperCase() : null;
298
+ const out = { host, declared, checked_at: new Date().toISOString() };
299
+ if (!host) return { ...out, verdict: 'unknown', reason: 'no API endpoint' };
300
+
301
+ const ips = net.isIP(host) ? [host] : await (opts.resolve ?? ((h) => dns.resolve4(h)))(host).catch(() => []);
302
+ const ip = ips.find((a) => !isPrivateHost(a));
303
+ if (!ip) return { ...out, ips, verdict: 'unknown', reason: 'no public IPv4 address' };
304
+
305
+ const front = await locateAddress(ip, declared, opts);
306
+ const origin = front.verdict === 'cdn' ? await checkOrigins(card, host, declared, { ...opts, frontIp: ip }) : null;
307
+ return { ...out, ips, ...front, ...(origin ? { origin } : {}) };
308
+ }
309
+
160
310
  /** Parse "FI Helsinki 60.17 24.93 https://host/onp-probe" (agents) or "DE Nuremberg 49.45 11.08" (self). */
161
311
  export function parseSite(spec) {
162
312
  if (!spec) return null;
package/src/locations.js CHANGED
@@ -7,9 +7,10 @@ import { readFileSync, readdirSync } from 'node:fs';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import {
9
9
  sendJson, problem, regionWithin, countryOf, basisRank, pointFor, distanceKm, parsePoint, precisionRank,
10
- residencyAt, residencyMeets, commitmentRank, scopeCovers, RESIDENCY_COMMITMENTS, lineageAllowed,
10
+ residencyAt, residencyMeets, commitmentRank, scopeCovers, RESIDENCY_COMMITMENTS, lineageAllowed, serverCheckOf,
11
11
  } from '@opennodes/core';
12
12
  import { siteLocation } from './importers.js';
13
+ import { locationSummary } from './search.js';
13
14
 
14
15
  const DATA_DIR = fileURLToPath(new URL('./data/', import.meta.url));
15
16
  const HIDDEN = ['delisted', 'suspended', 'submitted', 'challenged', 'disputed', 'claimed'];
@@ -158,7 +159,8 @@ export async function collectSites(store, seeds = []) {
158
159
  for (const { node, card } of cards) {
159
160
  // The registry's server-location check (location.js, ONP-3 §6.4) covers the node's API host,
160
161
  // not each site: shown beside the declared sites, never turning one into `measured` by itself.
161
- const check = (await store.getObservations(node.id, '_node')).location ?? null;
162
+ // As search carries it: a check made for another API host or declared country reads `unknown`.
163
+ const check = locationSummary((await store.getObservations(node.id, '_node')).location ?? null, card);
162
164
  const via = attached.get(node.id);
163
165
  const holds = via?.primary === node.id;
164
166
  bases.set(node.id, {
@@ -169,8 +171,10 @@ export async function collectSites(store, seeds = []) {
169
171
  tier: node.state === 'indexed' ? 'unverified' : node.state,
170
172
  source: holds ? 'seed' : (node.source ?? 'registration'),
171
173
  server_check: check ? {
172
- verdict: check.verdict, server_country: check.server?.country ?? null,
173
- latency: check.latency?.verdict ?? 'unknown', checked_at: check.checked_at ?? null,
174
+ verdict: check.verdict, server_country: check.server_country ?? null,
175
+ latency: check.latency ?? 'unknown', checked_at: check.checked_at ?? null,
176
+ level: serverCheckOf({ jurisdiction: { location: check } }), // §6.4 evidence level, as search's jurisdiction.server_check
177
+ ...(check.origin ? { origin: check.origin.verdict } : {}),
174
178
  } : null,
175
179
  commitments: card.node?.residency ?? residencyOf.get(node.id) ?? null,
176
180
  });
package/src/mcp.js CHANGED
@@ -3,8 +3,8 @@
3
3
  // MCP host gets ONP discovery (recommend, search_offerings, get_offering, get_node, estimate,
4
4
  // find_locations, find_residency) for free.
5
5
  import { readFileSync } from 'node:fs';
6
- import { readJson, sendJson, problem, estimateBounds, round6, extractFeatures, recommend, MCP_TOOLS, MCP_INSTRUCTIONS, summarizeNode } from '@opennodes/core';
7
- import { searchOfferingsPaged, searchOfferings, collectOfferings, pricePublished } from './search.js';
6
+ import { readJson, sendJson, problem, estimateBounds, round6, extractFeatures, recommend, MCP_TOOLS, MCP_INSTRUCTIONS, summarizeNode, serverCheckOf } from '@opennodes/core';
7
+ import { searchOfferingsPaged, searchOfferings, collectOfferings, pricePublished, locationSummary } from './search.js';
8
8
  import { buildLocations, buildResidency } from './locations.js';
9
9
  import { nodeIdsIn } from './counts.js';
10
10
  import { verificationOf } from './probes.js';
@@ -65,12 +65,16 @@ async function runTool(store, seeds, name, args = {}, trusted = undefined) {
65
65
  const node = await store.getNode(args.node_id);
66
66
  if (!node) throw new Error(`unknown node: ${args.node_id} (node ids come from search_offerings or recommend results)`);
67
67
  const card = await store.latestCard(node.id);
68
+ const nodeObs = await store.getObservations(node.id, '_node');
68
69
  return summarizeNode({
69
70
  ...node,
70
71
  card,
71
72
  probes: (await store.probesFor(node.id)).slice(0, 20),
72
73
  history: await store.transitionsFor(node.id),
73
- verification: verificationOf(card, await store.getObservations(node.id, '_node')),
74
+ verification: verificationOf(card, nodeObs),
75
+ // the server-location check, as GET /v0/nodes/{id} gives it (ONP-3 §6.4)
76
+ location: nodeObs.location ?? null,
77
+ server_check: serverCheckOf({ jurisdiction: { location: locationSummary(nodeObs.location ?? null, card) } }),
74
78
  }, args.offering_limit ?? 25);
75
79
  }
76
80
  case 'estimate': {