@opennodes/registry 0.1.52 → 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/src/server.js CHANGED
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
3
3
  import {
4
4
  createApp, listen, closeApp, sendJson, problem, readJson,
5
5
  validateCard, verifyCardSignature, keyFromJwk, estimateBounds,
6
- extractFeatures, recommend, trustedView, DEFAULT_TRUSTED_JURISDICTIONS,
6
+ extractFeatures, recommend, trustedView, DEFAULT_TRUSTED_JURISDICTIONS, serverCheckOf,
7
7
  } from '@opennodes/core';
8
8
  import { resolveTxt } from 'node:dns/promises';
9
9
  import { readFileSync, writeFileSync, existsSync } from 'node:fs';
@@ -11,16 +11,19 @@ import { fileURLToPath } from 'node:url';
11
11
  import { generateKeypair, keypairFromPem } from '@opennodes/core';
12
12
  import { createStore } from './store.js';
13
13
  import { runStageA, verificationOf } from './probes.js';
14
- import { runStageB, captureFingerprints } from './stageb.js';
14
+ import { runStageB, captureFingerprints, UNSIGNED_CARD, IDENTITY_CAPTURE, CUSTOMER_ACCESS_NEEDED } from './stageb.js';
15
15
  import { startStageC } from './stagec.js';
16
+ import { loadCorpus } from './corpus.js';
17
+ import { vendorTable, proprietaryVendor, VENDOR_SLUG, NAMESPACE, ARTIFACT } from './vendors.js';
18
+ import { makePlanner, startScheduler } from './schedule.js';
16
19
  import { startReimport } from './reimport.js';
17
20
  import { makeSafeFetch } from './safefetch.js';
18
- import { searchOfferings, searchOfferingsPaged, collectOfferings, watchStoreWrites, setSeedPlacements, setTrustedView, RANK_COMPONENTS, pricePublished } from './search.js';
21
+ import { searchOfferings, searchOfferingsPaged, collectOfferings, watchStoreWrites, setSeedPlacements, setTrustedView, RANK_COMPONENTS, pricePublished, ROUTER_HOSTS, locationSummary } from './search.js';
19
22
  import { mcpRoutes } from './mcp.js';
20
23
  import { hostControlsNamespace, isPrivateHost, makeRateLimiter } from './namespace.js';
21
24
  import { exportRoutes } from './export.js';
22
25
  import { collapseFlaps } from './feed.js';
23
- import { checkNodeLocation } from './location.js';
26
+ import { checkNodeLocation, declaredOrigins } from './location.js';
24
27
  import {
25
28
  importModelsDev, importHuggingFace, importOpenRouter,
26
29
  importOllamaLibrary, parseOllamaLibrary,
@@ -47,8 +50,9 @@ export async function startRegistry({
47
50
  adminToken = null, // bearer for admin routes; without it, loopback-only
48
51
  keyPath = null, // PEM file for a persistent signing identity; null = ephemeral
49
52
  enforceNamespace = null, // null = enforce except for private hosts in dev mode; true/false to force
50
- registerPerHour = 0, // per-client cap on register/verify calls (0 = unlimited; set in production)
51
- admitCooldownMs = 0, // minimum gap between Stage B runs per node (0 = none; set in production)
53
+ registerPerHour = 0, // per-client cap on register/verify/ping calls (0 = unlimited; set in production)
54
+ schedule = null, // {} (or overrides of SCHEDULE_DEFAULTS) to run Stage A and B on the registry's timetable
55
+ probeCorpus = null, // private probe prompts: a JSON file path or an object (corpus.js); null = public built-in
52
56
  trustProxy = false, // read the client address from X-Forwarded-For (behind Caddy / a CDN)
53
57
  location = null, // { selfSite, agents, intervalMs, fetchImpl, resolve, rtt } to check server locations
54
58
  locationSeeds = false, // import the bundled curated location seeds (src/data/locations-*.json) at start
@@ -56,7 +60,23 @@ export async function startRegistry({
56
60
  requestCountFlushMs = 60_000, // how often request counts move from memory to the store (reads flush first)
57
61
  trustedJurisdictions = DEFAULT_TRUSTED_JURISDICTIONS, // the trusted pool's operator jurisdictions (ONP_TRUSTED_JURISDICTIONS)
58
62
  } = {}) {
63
+ const corpus = loadCorpus(probeCorpus); // before the store: a broken corpus file stops the start
59
64
  const store = watchStoreWrites(await createStore(dbPath)); // sqlite path/:memory: or postgres:// URL; writes refresh the cached catalog
65
+ const planner = makePlanner(store, schedule ?? {});
66
+ // Vendor-namespace table: built-in pins, admin entries, and the vendor slugs imports already use,
67
+ // each bound to the API hosts of those imports (routers excluded).
68
+ const vendors = async () => {
69
+ const catalog = new Map();
70
+ for (const o of await collectOfferings(store)) {
71
+ const vendor = o.source === 'import' ? proprietaryVendor(o.model?.artifact) : null;
72
+ if (!vendor) continue;
73
+ if (!catalog.has(vendor)) catalog.set(vendor, new Set());
74
+ let host = null;
75
+ try { host = new URL(o.endpoints?.openai).hostname.toLowerCase(); } catch { /* listing-only */ }
76
+ if (host && !ROUTER_HOSTS.has(host)) catalog.get(vendor).add(host);
77
+ }
78
+ return vendorTable(await store.vendorNamespaces(), catalog);
79
+ };
60
80
  const requests = makeRequestCounter(store, { flushMs: requestCountFlushMs }); // node ids + counts only
61
81
  const safeFetch = makeSafeFetch({ allowPrivate: allowPrivateTargets });
62
82
  const seeds = locationSeeds ? loadLocationSeeds() : [];
@@ -67,6 +87,8 @@ export async function startRegistry({
67
87
  setSeedPlacements(store, seedPlacements(seeds));
68
88
  const trusted = trustedView(trustedJurisdictions); // pool labels, trust=trusted, sensitive recommend
69
89
  if (!trusted.countries.length) console.warn(`trusted jurisdictions "${trustedJurisdictions}" name no country: no hosted offering is trusted`);
90
+ // The trusted pool needs a passing server-location check (ONP-3 §5e): without checks it holds no hosted offering.
91
+ if (!location && !allowPrivateTargets) console.warn('server-location checks are off (ONP_LOCATION): no hosted offering can pass the server check, so the trusted pool holds none');
70
92
  setTrustedView(store, trusted);
71
93
  const webApp = readFileSync(fileURLToPath(new URL('./web/index.html', import.meta.url)), 'utf8');
72
94
  let registryKeys;
@@ -95,14 +117,26 @@ export async function startRegistry({
95
117
  return res.json();
96
118
  }
97
119
 
98
- async function verifySignatureFromOrigin(card, origin) {
99
- const res = await safeFetch(`${origin}/.well-known/jwks.json`, {}, 10_000);
100
- if (!res.ok) throw new Error('jwks fetch failed');
101
- const jwks = await res.json();
102
- const kid = card.signatures?.[0]?.kid;
103
- const jwk = jwks.keys.find((k) => !kid || k.kid === kid) ?? jwks.keys[0];
104
- if (!jwk) throw new Error('no key in jwks');
105
- verifyCardSignature(card, keyFromJwk(jwk));
120
+ /**
121
+ * Check the card's signature against the origin's JWKS. `definite: false` when the JWKS could not
122
+ * be fetched (an outage says nothing about the card); `definite: true` when the card is unsigned
123
+ * or the signature does not verify.
124
+ */
125
+ async function checkSignature(card, origin) {
126
+ if (!card.signatures?.length) return { ok: false, definite: true, error: 'card has no signatures' };
127
+ let jwks;
128
+ try {
129
+ const res = await safeFetch(`${origin}/.well-known/jwks.json`, {}, 10_000);
130
+ if (!res.ok) return { ok: false, definite: false, error: `jwks fetch failed: ${res.status}` };
131
+ jwks = await res.json();
132
+ } catch (err) { return { ok: false, definite: false, error: `jwks fetch failed: ${err.message}` }; }
133
+ try {
134
+ const kid = card.signatures[0].kid;
135
+ const jwk = (jwks.keys ?? []).find((k) => !kid || k.kid === kid) ?? jwks.keys?.[0];
136
+ if (!jwk) return { ok: false, definite: true, error: 'no key in jwks' };
137
+ verifyCardSignature(card, keyFromJwk(jwk));
138
+ return { ok: true };
139
+ } catch (err) { return { ok: false, definite: true, error: String(err.message ?? err) }; }
106
140
  }
107
141
 
108
142
  /** node.id is reverse-DNS: org.opennodes.fixture -> fixture.opennodes.org */
@@ -117,14 +151,14 @@ export async function startRegistry({
117
151
  };
118
152
  const registerLimiter = makeRateLimiter(registerPerHour);
119
153
  const clientOf = (req) => (trustProxy && req.headers['x-forwarded-for']?.split(',')[0].trim()) || req.socket.remoteAddress || 'unknown';
120
- const isAdmin = (req) => Boolean(adminToken) && req.headers.authorization === `Bearer ${adminToken}`;
121
154
 
122
155
  /**
123
- * Fetch for probing one node: carries the operator's probe key (card-only listings of
124
- * keyed APIs), and only toward the card's own endpoint origins — never to anything else.
156
+ * Fetch for probing one node: carries the customer access the registry bought for it, else the
157
+ * operator's probe key (card-only listings of keyed APIs), and only toward the card's own
158
+ * endpoint origins — never to anything else.
125
159
  */
126
160
  async function authFetch(nodeId, card) {
127
- const key = await store.getProbeKey(nodeId);
161
+ const key = (await store.getCustomerKey(nodeId)) ?? (await store.getProbeKey(nodeId));
128
162
  if (!key || !card?.endpoints) return safeFetch;
129
163
  const origins = new Set([card.endpoints.openai, card.endpoints.health].filter(Boolean).map((u) => new URL(u).origin));
130
164
  return (url, opts = {}, timeoutMs) => safeFetch(url,
@@ -173,9 +207,19 @@ export async function startRegistry({
173
207
  if (errors.length) throw new Error('card invalid: ' + errors.slice(0, 5).join('; '));
174
208
  const origin = new URL(cardUrl).origin;
175
209
  if (card.node.id !== nodeId) throw new Error(`card node.id ${card.node.id} != registered ${nodeId}`);
176
- let sigOk = false;
177
- try { await verifySignatureFromOrigin(card, origin); sigOk = true; } catch { /* accepted but labeled */ }
210
+ // Unsigned cards are accepted but labeled below `verified`, and never at `verified` or above (ONP-2 §8).
211
+ const sig = await checkSignature(card, origin);
212
+ let sigOk = sig.ok;
213
+ if (!sig.ok && !sig.definite) {
214
+ // JWKS unreachable: the same bytes verified before still count; a new revision waits for a check.
215
+ const prev = await store.latestRevision(nodeId);
216
+ if (prev?.sig_ok && prev.revision === card.revision && JSON.stringify(await store.latestCard(nodeId)) === JSON.stringify(card)) sigOk = true;
217
+ }
178
218
  await store.saveRevision(nodeId, card.revision, card, sigOk);
219
+ if (!sigOk && sig.definite) {
220
+ const node = await store.getNode(nodeId);
221
+ if (['verified', 'attested'].includes(node?.state)) await store.setState(nodeId, 'community', `${UNSIGNED_CARD}: ${sig.error}`);
222
+ }
179
223
  return { card, sigOk };
180
224
  }
181
225
 
@@ -188,13 +232,110 @@ export async function startRegistry({
188
232
  try {
189
233
  const node = await store.getNode(nodeId);
190
234
  if (!node?.card_url || node.source === 'import') return;
191
- const current = await store.latestCard(nodeId);
235
+ const current = await store.latestRevision(nodeId);
192
236
  const fresh = await fetchCard(node.card_url);
193
- if (current && fresh.revision === current.revision) return;
237
+ // Same revision: nothing to do, unless its signature could not be checked yet.
238
+ if (current && fresh.revision === current.revision && current.sig_ok) return;
194
239
  await indexCard(nodeId, node.card_url);
195
240
  } catch { /* unreachable or invalid: probes will record the failure themselves */ }
196
241
  }
197
242
 
243
+ // ---- admission runs shared by /verify, /ping, /admit, dispute resolution and the scheduler ----
244
+ const LISTED = ['community', 'verified', 'attested'];
245
+
246
+ /**
247
+ * Stage A on the node's latest card, and what it means for the tier (ONP-3 §4a): `indexed` that
248
+ * passes goes to `community`; a listed node that fails a structural check (STRUCTURAL_KINDS) goes
249
+ * back to `indexed`; health and blind-call failures are left to Stage C. A dispute is never
250
+ * touched. `recordFailure` writes a failed run on an `indexed` node into the history (/verify);
251
+ * `refresh` re-fetches the card first (scheduled runs: ONP-3 §1, at least every 6 h).
252
+ */
253
+ async function stageAFor(nodeId, { recordFailure = false, refresh = false } = {}) {
254
+ if (refresh) await refreshCard(nodeId);
255
+ const card = await store.latestCard(nodeId);
256
+ const stageA = await runStageA(store, nodeId, card, { safeFetch: await authFetch(nodeId, card), corpus, vendors: await vendors() });
257
+ const node = await store.getNode(nodeId);
258
+ const failed = stageA.results.filter((r) => !r.ok);
259
+ let claimed = [];
260
+ if (stageA.ok && node.state === 'indexed') {
261
+ await store.setState(nodeId, 'community', 'Stage A passed');
262
+ claimed = await supersedeImports(nodeId);
263
+ await planner.firstStageB(nodeId, card, 'first');
264
+ } else if (!stageA.ok && node.state === 'indexed' && recordFailure) {
265
+ await store.setState(nodeId, 'indexed', 'Stage A failures: ' + failed.map((r) => r.kind).join(','));
266
+ } else if (!stageA.ok && LISTED.includes(node.state)) {
267
+ const structural = failed.filter((r) => r.structural).map((r) => r.kind);
268
+ if (structural.length) await store.setState(nodeId, 'indexed', 'Stage A failures: ' + structural.join(','));
269
+ }
270
+ await planner.afterStageA(nodeId, card, stageA.ok);
271
+ return { stageA, claimed };
272
+ }
273
+
274
+ /** Stage B runs one at a time per node: the admin route and the scheduler never overlap. */
275
+ const stageBRunning = new Set();
276
+
277
+ /**
278
+ * A card-only listing (ONP-3 §4) is probed with the operator's own probe key, which marks every
279
+ * probe: it reaches `verified` only on probes sent with customer access the registry bought.
280
+ */
281
+ const cardOnlyHeld = async (nodeId) => Boolean(await store.getProbeKey(nodeId)) && !(await store.getCustomerKey(nodeId));
282
+ /**
283
+ * A verified or attested card-only listing without customer access goes back to community at once
284
+ * (after a probe key is activated, or customer access removed). The reason never says which.
285
+ */
286
+ async function holdCardOnly(nodeId) {
287
+ const node = await store.getNode(nodeId);
288
+ if (['verified', 'attested'].includes(node?.state) && await cardOnlyHeld(nodeId)) await store.setState(nodeId, 'community', CUSTOMER_ACCESS_NEEDED);
289
+ }
290
+
291
+ /**
292
+ * Stage B on the node's freshly fetched card, and its effect: a reference mismatch disputes the
293
+ * node; a pass promotes `community` to `verified`; anything else (no identity reference, unsigned
294
+ * card, capacity) keeps `community` or demotes `verified` to `community`. Returns null when a
295
+ * run is already in progress for the node.
296
+ */
297
+ async function stageBFor(nodeId) {
298
+ if (stageBRunning.has(nodeId)) return null;
299
+ stageBRunning.add(nodeId);
300
+ try {
301
+ await refreshCard(nodeId);
302
+ const card = await store.latestCard(nodeId);
303
+ const revision = await store.latestRevision(nodeId);
304
+ // Decided before anything is sent: what counts is the key this run's probes carry.
305
+ const held = await cardOnlyHeld(nodeId);
306
+ // A 409 excuses nothing unless a re-fetch shows the card really moved (stageb.js makeOn409).
307
+ const revisionMoved = async () => {
308
+ await refreshCard(nodeId);
309
+ const now = await store.latestRevision(nodeId);
310
+ return now && now.revision !== card.revision ? now.revision : null;
311
+ };
312
+ const stageB = await runStageB(store, nodeId, card, {
313
+ safeFetch: await authFetch(nodeId, card), capacity: stageBCapacity, corpus, vendors: await vendors(), signed: Boolean(revision?.sig_ok), revisionMoved,
314
+ });
315
+ const node = await store.getNode(nodeId);
316
+ if (!stageB.stale && LISTED.includes(node.state)) {
317
+ if (stageB.identityFailed) {
318
+ await store.setState(nodeId, 'disputed', 'Stage B identity fingerprint mismatch');
319
+ } else if (stageB.ok && held) {
320
+ // Passed, but on probes the operator could tell apart: it stays at (or returns to) community.
321
+ stageB.held = CUSTOMER_ACCESS_NEEDED;
322
+ await store.recordProbe(nodeId, null, 'B', 'customer-access', false, CUSTOMER_ACCESS_NEEDED);
323
+ if (node.state !== 'community') await store.setState(nodeId, 'community', `Stage B passed; ${CUSTOMER_ACCESS_NEEDED}`);
324
+ await supersedeImports(nodeId);
325
+ } else if (stageB.ok) {
326
+ if (node.state === 'community') await store.setState(nodeId, 'verified', 'Stage B passed');
327
+ await supersedeImports(nodeId);
328
+ } else if (node.state !== 'community') {
329
+ await store.setState(nodeId, 'community', `Stage B failed: ${stageB.reason}`);
330
+ }
331
+ }
332
+ await planner.afterStageB(nodeId, card, stageB);
333
+ return stageB;
334
+ } finally {
335
+ stageBRunning.delete(nodeId);
336
+ }
337
+ }
338
+
198
339
  const app = createApp([
199
340
  ['POST', '/v0/nodes', async (req, res) => {
200
341
  if (!registerLimiter(clientOf(req))) return problem(res, 429, 'rate-limited', 'too many registration attempts from this address; try again later');
@@ -230,7 +371,7 @@ export async function startRegistry({
230
371
  challenge: {
231
372
  methods: {
232
373
  http: `${origin}/.well-known/onp-challenge/${token}`,
233
- dns: `_onp-challenge.${nodeId.split('.').slice(0, 2).reverse().join('.')} TXT "${token}"`,
374
+ dns: `_onp-challenge.${domainForNodeId(nodeId)} TXT "${token}"`, // the whole id, as the check resolves it
234
375
  },
235
376
  token,
236
377
  verify: `/v0/nodes/${nodeId}/verify`,
@@ -251,11 +392,21 @@ export async function startRegistry({
251
392
  try { indexed = await indexCard(params.id, node.card_url); }
252
393
  catch (err) { return problem(res, 422, 'card-invalid', String(err.message)); }
253
394
 
254
- await store.setState(params.id, 'indexed', `namespace verified via ${check.method}`);
255
- const stageA = await runStageA(store, params.id, indexed.card, { safeFetch: await authFetch(params.id, indexed.card) });
256
- await store.setState(params.id, stageA.ok ? 'community' : 'indexed',
257
- stageA.ok ? 'Stage A passed' : 'Stage A failures: ' + stageA.results.filter((r) => !r.ok).map((r) => r.kind).join(','));
258
- const claimed = stageA.ok ? await supersedeImports(params.id) : [];
395
+ // A dispute survives registering again: only a resolution recorded by the registry ends it
396
+ // (POST /v0/admin/nodes/{id}/resolve). The fresh card is indexed so it can be reviewed.
397
+ const current = (await store.getNode(params.id)).state;
398
+ if (current === 'disputed') {
399
+ const since = [...await store.transitionsFor(params.id)].reverse().find((t) => t.to_state === 'disputed');
400
+ return problem(res, 409, 'disputed',
401
+ `${params.id} is disputed${since ? ` since ${since.at} (${since.reason})` : ''}. Registering again does not end a dispute; the registry records a resolution after review. The card was re-indexed at revision ${indexed.card.revision}.`);
402
+ }
403
+ // A listed or suspended node keeps its state: registering again re-indexes the card and runs
404
+ // Stage A under the listed-node rules, but neither resets the tier nor moves Stage B's schedule
405
+ // (a changed model, serving block or endpoint makes Stage B due on its own, schedule.js).
406
+ if (![...LISTED, 'suspended'].includes(current)) await store.setState(params.id, 'indexed', `namespace verified via ${check.method}`);
407
+ // A probe key handed over now makes a verified node card-only: no verified without customer access.
408
+ await holdCardOnly(params.id);
409
+ const { stageA, claimed } = await stageAFor(params.id, { recordFailure: true });
259
410
  if (location) locateNode(params.id).catch(() => {}); // background: never delays registration
260
411
  sendJson(res, 200, {
261
412
  node_id: params.id,
@@ -267,58 +418,119 @@ export async function startRegistry({
267
418
  }],
268
419
 
269
420
  ['PUT', '/v0/nodes/:id/ping', async (req, res, { params }) => {
421
+ if (!registerLimiter(clientOf(req))) return problem(res, 429, 'rate-limited', 'too many refresh requests from this address; try again later');
270
422
  const node = await store.getNode(params.id);
271
423
  if (!node) return problem(res, 404, 'unknown-node', params.id);
272
424
  try {
273
425
  const { card } = await indexCard(params.id, node.card_url);
274
- const stageA = await runStageA(store, params.id, card, { safeFetch: await authFetch(params.id, card) });
275
- sendJson(res, 200, { node_id: params.id, revision: card.revision, stage_a_ok: stageA.ok });
426
+ if (location) relocateIfStale(params.id, card).catch(() => {}); // background: a new API host is checked again now
427
+ const { stageA } = await stageAFor(params.id);
428
+ sendJson(res, 200, { node_id: params.id, revision: card.revision, stage_a_ok: stageA.ok, state: (await store.getNode(params.id)).state });
276
429
  } catch (err) {
277
430
  problem(res, 422, 'refresh-failed', String(err.message));
278
431
  }
279
432
  }],
280
433
 
281
- // Stage B admission: identity + context + capacity; promotes community -> verified,
282
- // or marks the node disputed on an identity failure (DS-ADM-02..04).
434
+ // Stage B admission (admin): identity + context + capacity; promotes community -> verified,
435
+ // or marks the node disputed on an identity failure (DS-ADM-02..04). Otherwise Stage B runs
436
+ // only on the registry's own schedule (schedule.js): neither the operator nor a third party
437
+ // chooses when it happens.
283
438
  ['POST', '/v0/nodes/:id/admit', async (req, res, { params }) => {
439
+ if (!adminOk(req, res)) return;
284
440
  const node = await store.getNode(params.id);
285
441
  if (!node) return problem(res, 404, 'unknown-node', params.id);
286
- if (node.state !== 'community' && node.state !== 'verified') {
442
+ if (!LISTED.includes(node.state)) {
287
443
  return problem(res, 409, 'wrong-state', `Stage B requires community tier, node is ${node.state}`);
288
444
  }
289
- if (admitCooldownMs > 0 && !isAdmin(req)) {
290
- const lastB = (await store.probesFor(params.id)).find((p) => p.stage === 'B');
291
- const age = lastB ? Date.now() - Date.parse(lastB.at) : Infinity;
292
- if (age < admitCooldownMs) {
293
- return problem(res, 429, 'admission-cooldown', `Stage B ran ${Math.round(age / 60000)} min ago; next run allowed in ${Math.ceil((admitCooldownMs - age) / 60000)} min`);
294
- }
295
- }
296
- await refreshCard(params.id);
297
- const card = await store.latestCard(params.id);
298
- const stageB = await runStageB(store, params.id, card, { safeFetch: await authFetch(params.id, card), capacity: stageBCapacity });
445
+ const stageB = await stageBFor(params.id);
446
+ if (!stageB) return problem(res, 409, 'stage-b-running', `Stage B is already running for ${params.id}`);
299
447
  if (stageB.stale) {
300
448
  return problem(res, 409, 'stale-card', 'the node changed its card revision during the battery; retry');
301
449
  }
302
- if (stageB.identityFailed) {
303
- await store.setState(params.id, 'disputed', 'Stage B identity fingerprint mismatch');
304
- } else if (stageB.ok) {
305
- await store.setState(params.id, 'verified', 'Stage B passed');
306
- await supersedeImports(params.id);
307
- }
308
450
  sendJson(res, 200, { node_id: params.id, state: (await store.getNode(params.id)).state, stage_b: stageB });
309
451
  }],
310
452
 
311
- // Operator-trusted reference capture (admin surface, MVP: unauthenticated local only):
312
- // runs the fingerprint battery against a KNOWN-GOOD deployment and stores references.
453
+ // Operator-trusted reference capture (admin): asks a KNOWN-GOOD deployment of the weights
454
+ // IDENTITY_CAPTURE prompts drawn from the private corpus and stores the answers' hashes as the
455
+ // artefact's references, replacing earlier ones unless {"replace": false}. Body {node_id,
456
+ // offering_id} names the deployment; optional {artifact} stores them under another artefact
457
+ // (e.g. the public name a node is about to switch to). The prompts never leave the registry.
313
458
  ['POST', '/v0/fingerprints/capture', async (req, res) => {
314
459
  if (!adminOk(req, res)) return;
315
- const { node_id, offering_id } = await readJson(req);
460
+ const { node_id, offering_id, artifact, replace = true } = await readJson(req);
316
461
  const card = await store.latestCard(node_id);
317
462
  const offering = card?.offerings.find((o) => o.offering_id === offering_id);
318
463
  if (!offering) return problem(res, 404, 'unknown-offering', `${node_id}/${offering_id}`);
319
- const refs = await captureFingerprints(await authFetch(node_id, card), card, offering);
320
- await store.addFingerprints(offering.model.artifact, refs);
321
- sendJson(res, 200, { artifact: offering.model.artifact, references: refs.length });
464
+ const target = artifact ?? offering.model.artifact;
465
+ if (typeof target !== 'string' || !ARTIFACT.test(target)) return problem(res, 400, 'bad-artifact', 'artifact must be hf:{org}/{repo}, ollama:{name}[:{tag}] or urn:proprietary:{vendor}:{model}');
466
+ let refs;
467
+ try { refs = await captureFingerprints(await authFetch(node_id, card), card, offering, corpus.identityPrompts(IDENTITY_CAPTURE)); }
468
+ catch (err) { return problem(res, 502, 'capture-failed', String(err.message)); }
469
+ if (replace) await store.clearFingerprints(target);
470
+ await store.addFingerprints(target, refs);
471
+ sendJson(res, 200, { artifact: target, references: refs.length, corpus: corpus.private ? 'private' : 'built-in' });
472
+ }],
473
+
474
+ // Dispute resolution (admin): the only way out of `disputed`. Body {"resolution": "..."}: what
475
+ // was found and done, recorded in the listing history. The node returns to `indexed`, runs
476
+ // Stage A at once, and Stage B again on the registry's schedule.
477
+ ['POST', '/v0/admin/nodes/:id/resolve', async (req, res, { params }) => {
478
+ if (!adminOk(req, res)) return;
479
+ const node = await store.getNode(params.id);
480
+ if (!node) return problem(res, 404, 'unknown-node', params.id);
481
+ if (node.state !== 'disputed') return problem(res, 409, 'not-disputed', `${node.id} is ${node.state}`);
482
+ const { resolution } = await readJson(req);
483
+ if (typeof resolution !== 'string' || !resolution.trim() || resolution.length > 2000) {
484
+ return problem(res, 400, 'missing-resolution', 'body must be {"resolution": "what was found and what was done"}');
485
+ }
486
+ await store.setState(node.id, 'indexed', `dispute resolved: ${resolution.trim()}`);
487
+ await refreshCard(node.id);
488
+ const { stageA } = await stageAFor(node.id, { recordFailure: true });
489
+ sendJson(res, 200, { id: node.id, state: (await store.getNode(node.id)).state, stage_a: stageA });
490
+ }],
491
+
492
+ // Customer access (admin, ONP-3 §4): body {"key": "..."} records a key the registry bought as an
493
+ // ordinary customer of the node's API; from then on every probe carries it instead of the
494
+ // operator's probe key, and a card-only listing can reach verified at its next Stage B, which
495
+ // the registry schedules (an earlier pass never counts). {"key": null} removes it. The key is
496
+ // never returned, logged or published, and no public record says it was recorded.
497
+ ['POST', '/v0/admin/nodes/:id/customer-access', async (req, res, { params }) => {
498
+ if (!adminOk(req, res)) return;
499
+ const node = await store.getNode(params.id);
500
+ if (!node) return problem(res, 404, 'unknown-node', params.id);
501
+ if (node.source === 'import') return problem(res, 409, 'imported-listing', `${node.id} is an imported catalog listing; the registry does not probe it`);
502
+ const { key } = await readJson(req);
503
+ if (key !== null && (typeof key !== 'string' || !key.trim() || key.length > 4096)) {
504
+ return problem(res, 400, 'bad-customer-key', 'body must be {"key": "<the API key>"}, or {"key": null} to remove it');
505
+ }
506
+ await store.setCustomerKey(node.id, key);
507
+ if (key && LISTED.includes(node.state)) await planner.firstStageB(node.id, await store.latestCard(node.id), 'first');
508
+ if (location) locateNode(node.id).catch(() => {}); // behind a CDN the origin check asks with this key
509
+ if (!key) await holdCardOnly(node.id);
510
+ sendJson(res, 200, { node_id: node.id, customer_access: Boolean(key), state: (await store.getNode(node.id)).state });
511
+ }],
512
+
513
+ // The vendor-namespace table (ONP-3 §6.3): who may claim urn:proprietary:{vendor}:* artefacts.
514
+ ['GET', '/v0/vendors', async (req, res) => {
515
+ const table = await vendors();
516
+ sendJson(res, 200, {
517
+ rule: 'urn:proprietary:{vendor}:{model} is admitted only from a node id inside one of the vendor\'s namespaces listed here; for a vendor known from imported listings (source "catalog"), only from a node whose own domain contains one of the hosts those listings are served from; for any other vendor, only from the node\'s own namespace (the second label of its id)',
518
+ vendors: [...table].map(([vendor, v]) => ({ vendor, namespaces: v.namespaces, source: v.source, ...(v.hosts ? { hosts: v.hosts } : {}) }))
519
+ .sort((a, b) => a.vendor.localeCompare(b.vendor)),
520
+ });
521
+ }],
522
+ // Admin: body {"namespaces": ["com.example"]} sets a vendor's namespaces; {"namespaces": null}
523
+ // removes the admin entry (a built-in pin applies again).
524
+ ['POST', '/v0/admin/vendors/:vendor', async (req, res, { params }) => {
525
+ if (!adminOk(req, res)) return;
526
+ if (!VENDOR_SLUG.test(params.vendor)) return problem(res, 400, 'bad-vendor', 'vendor must match [a-z0-9-]+');
527
+ const { namespaces } = await readJson(req);
528
+ if (namespaces !== null && !(Array.isArray(namespaces) && namespaces.length && namespaces.every((n) => typeof n === 'string' && NAMESPACE.test(n)))) {
529
+ return problem(res, 400, 'bad-namespaces', 'body must be {"namespaces": ["com.example", ...]} (reverse-DNS, lower case) or {"namespaces": null}');
530
+ }
531
+ await store.setVendorNamespaces(params.vendor, namespaces);
532
+ const entry = (await vendors()).get(params.vendor);
533
+ sendJson(res, 200, { vendor: params.vendor, namespaces: entry?.namespaces ?? null, source: entry?.source ?? null });
322
534
  }],
323
535
 
324
536
  // Node directory: every listed node with tier, source, offering count, availability.
@@ -375,9 +587,13 @@ export async function startRegistry({
375
587
  institutional: Boolean(node.institutional),
376
588
  founding: Boolean(node.founding),
377
589
  card,
590
+ // Whether the latest card's signature verified against the origin's JWKS (ONP-2 §8).
591
+ signature_verified: Boolean((await store.latestRevision(params.id))?.sig_ok),
378
592
  probes: (await store.probesFor(params.id)).slice(0, 20),
379
593
  history: await store.transitionsFor(params.id),
380
594
  location: nodeObs.location ?? null,
595
+ // The check's evidence level for the current card (ONP-3 §6.4; `unchecked` when it was made for another host).
596
+ server_check: serverCheckOf({ jurisdiction: { location: locationSummary(nodeObs.location ?? null, card) } }),
381
597
  // What the tier covers (ONP-3 §4a): the offerings the tests could not call, and whether
382
598
  // Stage C has had to skip blind probes because none could be called.
383
599
  verification: verificationOf(card, nodeObs),
@@ -603,8 +819,19 @@ export async function startRegistry({
603
819
  map: mapTiles,
604
820
  signing_key: { ...registryKeys.publicJwk, kid: 'registry-1' },
605
821
  stage_c: Boolean(stageC),
822
+ // How admission runs here (ONP-3 §4a). The schedule's next run times are never published.
823
+ admission: {
824
+ stage_b: 'registry schedule; POST /v0/nodes/{id}/admit is admin-only',
825
+ schedule: schedule ? {
826
+ stage_a_max_hours: Math.round(planner.options.stageAIntervalMs / 3_600_000 * 10) / 10,
827
+ stage_b_max_days: Math.round(planner.options.stageBIntervalMs / 86_400_000),
828
+ } : null,
829
+ probe_corpus: corpus.summary(),
830
+ proprietary_vendors: '/v0/vendors',
831
+ },
606
832
  // What trust=trusted, policy.sensitive and each result's `pool` mean here (ONP-3 §5e).
607
- trust: { pools: ['trusted', 'open'], trusted },
833
+ // server_location_checks: whether this registry runs them (§6.4); without them nothing hosted passes trusted.server_check.
834
+ trust: { pools: ['trusted', 'open'], trusted, server_location_checks: Boolean(location) },
608
835
  });
609
836
  }],
610
837
 
@@ -623,10 +850,24 @@ export async function startRegistry({
623
850
  const asHolders = new Map();
624
851
  async function locateNode(nodeId) {
625
852
  const card = await store.latestCard(nodeId);
626
- const result = await checkNodeLocation(card, { ...location, asHolders });
853
+ // Behind a CDN the origin check asks the API for its model list with the key the probes carry
854
+ // (authFetch), and counts declared origins only in a signed card.
855
+ const key = (await store.getCustomerKey(nodeId)) ?? (await store.getProbeKey(nodeId));
856
+ const signed = Boolean((await store.latestRevision(nodeId))?.sig_ok);
857
+ const result = await checkNodeLocation(card, { ...location, asHolders, key, signed });
627
858
  await store.setObservation(nodeId, '_node', 'location', result);
628
859
  return result;
629
860
  }
861
+ // A check covers only the card it was made for (search.js locationSummary): when the card now names
862
+ // another API host, declared country or origin addresses, check again rather than wait for the sweep.
863
+ async function relocateIfStale(nodeId, card) {
864
+ const loc = (await store.getObservations(nodeId, '_node')).location;
865
+ const host = (() => { try { return new URL(card?.endpoints?.openai).hostname; } catch { return null; } })();
866
+ const declared = card?.node?.operator?.country ? String(card.node.operator.country).toUpperCase() : null;
867
+ const originsChanged = JSON.stringify(declaredOrigins(card)) !== JSON.stringify(loc?.origin?.declared ?? []);
868
+ const signedChanged = Boolean(loc?.origin) && (loc.origin.signed ?? true) !== Boolean((await store.latestRevision(nodeId))?.sig_ok);
869
+ if (!loc || loc.host !== host || (loc.declared ?? null) !== declared || (loc.verdict === 'cdn' && (originsChanged || signedChanged))) await locateNode(nodeId);
870
+ }
630
871
  // Daily sweep over registered nodes and imports that carry a country (the ones jurisdiction
631
872
  // filters can select), one at a time so the lookup service is never hammered.
632
873
  function startLocationSweep() {
@@ -647,7 +888,11 @@ export async function startRegistry({
647
888
  return { stop: () => { stopped = true; clearTimeout(timer); } };
648
889
  }
649
890
 
650
- const stageCHandle = stageC ? startStageC(store, { safeFetch, fetchFor: authFetch, refreshCard, ...stageC }) : null;
891
+ // A confirmed mismatch in a blind identity check makes Stage B due within the hour, on the timetable;
892
+ // without one (ONP_SCHEDULE=0) Stage B runs only on admin request, so the mismatch is only recorded.
893
+ const requestStageB = schedule ? (nodeId, card) => planner.stageBSoon(nodeId, card) : null;
894
+ const stageCHandle = stageC ? startStageC(store, { safeFetch, fetchFor: authFetch, refreshCard, requestStageB, corpus, ...stageC }) : null;
895
+ const scheduleHandle = schedule ? startScheduler(store, planner, { stageA: (id) => stageAFor(id, { refresh: true }), stageB: (id) => stageBFor(id) }) : null;
651
896
  const reimportHandle = reimport ? startReimport(store, { safeFetch, ...reimport }) : null;
652
897
  const locationHandle = location ? startLocationSweep() : null;
653
898
  const actualPort = await listen(app, port, host);
@@ -656,8 +901,14 @@ export async function startRegistry({
656
901
  origin: `http://${host}:${actualPort}`,
657
902
  store,
658
903
  registryKeys,
904
+ /** Run one scheduler pass now (tests); null when the schedule is off. */
905
+ scheduleTick: scheduleHandle ? () => scheduleHandle.tick() : null,
906
+ /** Run one Stage C blind sweep, or one look for due follow-ups, now (tests); null when Stage C is off. */
907
+ blindSweep: stageCHandle ? () => stageCHandle.blindSweep() : null,
908
+ followUpTick: stageCHandle ? () => stageCHandle.followUpTick() : null,
659
909
  close: async () => {
660
910
  stageCHandle?.stop();
911
+ scheduleHandle?.stop();
661
912
  reimportHandle?.stop();
662
913
  locationHandle?.stop();
663
914
  await closeApp(app);