@jini-ai/registry 0.5.2 → 0.6.10

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/CHANGELOG.md CHANGED
@@ -1,3 +1,18 @@
1
+ ## 0.6.10
2
+
3
+ ### Patch Changes
4
+
5
+ - Updated dependencies [22f0619]
6
+ - Updated dependencies [82ed2d3]
7
+ - Updated dependencies [3fe4d14]
8
+ - Updated dependencies [5a3de86]
9
+ - @jini-ai/core@0.6.10
10
+ - @jini-ai/protocol@0.6.10
11
+
12
+ ## 0.5.3 — 2026-10-22
13
+
14
+ - 2026-10-22: Model-facing tool errors keep diagnostic codes, complexity refactors, coverage.
15
+
1
16
  ## 0.5.2 — 2026-10-08
2
17
 
3
18
  - Tovu clean-up release: code Tovu moved into Jini, plus the Jini clean-up (see the commit log).
@@ -138,21 +138,28 @@ export class GithubRegistryBackend extends StaticRegistryBackend {
138
138
  return { ok: true, dryRun: false, name, version, reason, pullRequestUrl: pr.url, warnings: [] };
139
139
  }
140
140
  }
141
+ /**
142
+ * Render the publish PR body. Empty parts (no description, no changelog) are
143
+ * dropped by `filter(Boolean)`, so the body carries no blank separator lines
144
+ * apart from the ones embedded in the changelog section.
145
+ */
141
146
  function renderPublishBody(request) {
147
+ const { entry } = request;
142
148
  return [
143
- `Publish ${request.entry.name}@${request.entry.version}`,
144
- '',
145
- request.entry.description ?? '',
146
- '',
149
+ `Publish ${entry.name}@${entry.version}`,
150
+ entry.description,
147
151
  '## Registry metadata',
148
- '',
149
- `- source: ${request.entry.source}`,
150
- `- integrity: ${request.entry.integrity ?? request.entry.dist?.integrity ?? '(pending)'}`,
151
- `- manifestDigest: ${request.entry.manifestDigest ?? request.entry.dist?.manifestDigest ?? '(pending)'}`,
152
- `- capabilities: ${(request.entry.capabilitiesSummary ?? []).join(', ') || '(none declared)'}`,
153
- request.changelog ? `\n## Changelog\n\n${request.changelog}` : '',
152
+ `- source: ${entry.source}`,
153
+ `- integrity: ${digestField(entry, 'integrity')}`,
154
+ `- manifestDigest: ${digestField(entry, 'manifestDigest')}`,
155
+ `- capabilities: ${(entry.capabilitiesSummary ?? []).join(', ') || '(none declared)'}`,
156
+ request.changelog && `\n## Changelog\n\n${request.changelog}`,
154
157
  ]
155
158
  .filter(Boolean)
156
159
  .join('\n');
157
160
  }
161
+ /** A top-level digest wins over the `dist` one; neither yet means the publish pipeline has not computed it. */
162
+ function digestField(entry, key) {
163
+ return entry[key] ?? entry.dist?.[key] ?? '(pending)';
164
+ }
158
165
  //# sourceMappingURL=github-backend.js.map
@@ -101,5 +101,11 @@ export declare class GithubApiRegistryClient implements GithubRegistryClient {
101
101
  */
102
102
  private ensurePullRequest;
103
103
  private findOpenPullRequest;
104
+ /**
105
+ * The single request builder: every call goes to `apiUrl` with the GitHub
106
+ * headers (bearer auth only when a token is configured) and the QUICK
107
+ * idle/total bounds. A JSON `body` adds the JSON content type.
108
+ */
109
+ private send;
104
110
  }
105
111
  //# sourceMappingURL=github-client.d.ts.map
@@ -67,35 +67,16 @@ export class GithubApiRegistryClient {
67
67
  * this endpoint's inline-content response, or is not valid JSON.
68
68
  */
69
69
  async readManifest({ owner, repo, ref, path }) {
70
- const url = `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(path)}?${new URLSearchParams({ ref }).toString()}`;
71
- const resp = await this.http.send({ request: { url, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
70
+ const where = `${owner}/${repo}@${ref}:${path}`;
71
+ const resp = await this.send('GET', `${repoPath(owner, repo)}/contents/${encPath(path)}?${new URLSearchParams({ ref }).toString()}`);
72
72
  if (resp.status === 404) {
73
- throw new Error(`Registry manifest not found: ${owner}/${repo}@${ref}:${path}`);
73
+ throw new Error(`Registry manifest not found: ${where}`);
74
74
  }
75
75
  const json = await readGithubJson(resp);
76
- if (!(resp.status >= 200 && resp.status < 300)) {
77
- throw githubError(Array.isArray(json) ? {} : json, resp.status, `Failed to read registry manifest ${owner}/${repo}@${ref}:${path}.`);
76
+ if (!isOk(resp.status)) {
77
+ throw githubError(Array.isArray(json) ? {} : json, resp.status, `Failed to read registry manifest ${where}.`);
78
78
  }
79
- if (Array.isArray(json)) {
80
- throw new Error(`Registry manifest path is a directory, not a file: ${owner}/${repo}@${ref}:${path}`);
81
- }
82
- if (json.type !== 'file') {
83
- throw new Error(`Registry manifest path is not a file (type: ${String(json.type)}): ${owner}/${repo}@${ref}:${path}`);
84
- }
85
- if (json.encoding !== 'base64' || typeof json.content !== 'string') {
86
- throw new Error(`Registry manifest at ${owner}/${repo}@${ref}:${path} is too large for the Contents API's inline response ` +
87
- `(size: ${typeof json.size === 'number' ? json.size : 'unknown'} bytes, encoding: ${String(json.encoding)}); ` +
88
- 'split the manifest into a smaller file or fetch it via the Git Trees/raw-media-type API instead.');
89
- }
90
- const decoded = Buffer.from(json.content.replace(/\n/g, ''), 'base64').toString('utf8');
91
- let parsed;
92
- try {
93
- parsed = JSON.parse(decoded);
94
- }
95
- catch (cause) {
96
- throw new Error(`Registry manifest at ${owner}/${repo}@${ref}:${path} is not valid JSON.`, { cause });
97
- }
98
- return parsed;
79
+ return parseManifest(inlineFileContent(json, where), where);
99
80
  }
100
81
  /**
101
82
  * Pushes `request.files` as a new commit on a fresh branch (created off
@@ -127,36 +108,23 @@ export class GithubApiRegistryClient {
127
108
  return this.ensurePullRequest(owner, repo, request);
128
109
  }
129
110
  async getRefSha(owner, repo, branch) {
130
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/ref/heads/${enc(branch)}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
111
+ const resp = await this.send('GET', `${repoPath(owner, repo)}/git/ref/heads/${enc(branch)}`);
131
112
  if (resp.status === 404)
132
113
  return undefined;
133
- const json = await readGithubJson(resp);
134
- if (!(resp.status >= 200 && resp.status < 300))
135
- throw githubError(json, resp.status, 'GitHub ref lookup failed.');
114
+ const json = await okJson(resp, 'GitHub ref lookup failed.');
136
115
  const object = json.object;
137
116
  return typeof object?.sha === 'string' ? object.sha : undefined;
138
117
  }
139
118
  /** `GET /repos/{owner}/{repo}/git/commits/{sha}` (Git Data API) — the tree API's `base_tree` param needs a *tree* sha, not the commit sha `getRefSha` returns. */
140
119
  async getCommitTreeSha(owner, repo, commitSha) {
141
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits/${enc(commitSha)}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
142
- const json = await readGithubJson(resp);
143
- if (!(resp.status >= 200 && resp.status < 300))
144
- throw githubError(json, resp.status, 'GitHub base commit lookup failed.');
120
+ const json = await okJson(await this.send('GET', `${repoPath(owner, repo)}/git/commits/${enc(commitSha)}`), 'GitHub base commit lookup failed.');
145
121
  const tree = json.tree;
146
- const sha = typeof tree?.sha === 'string' ? tree.sha : '';
147
- if (!sha)
148
- throw new Error('GitHub base commit response did not include a tree sha.');
149
- return sha;
122
+ return requireString(tree?.sha, 'GitHub base commit response did not include a tree sha.');
150
123
  }
151
124
  async createBlob(owner, repo, content) {
152
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/blobs`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ content: Buffer.from(content, 'utf8').toString('base64'), encoding: 'base64' }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
153
- const json = await readGithubJson(resp);
154
- if (!(resp.status >= 200 && resp.status < 300))
155
- throw githubError(json, resp.status, 'GitHub blob creation failed.');
156
- const sha = typeof json.sha === 'string' ? json.sha : '';
157
- if (!sha)
158
- throw new Error('GitHub blob response did not include a sha.');
159
- return sha;
125
+ const body = { content: Buffer.from(content, 'utf8').toString('base64'), encoding: 'base64' };
126
+ const json = await okJson(await this.send('POST', `${repoPath(owner, repo)}/git/blobs`, body), 'GitHub blob creation failed.');
127
+ return requireString(json.sha, 'GitHub blob response did not include a sha.');
160
128
  }
161
129
  async createTree(owner, repo, baseTreeSha, files) {
162
130
  const tree = [];
@@ -164,24 +132,12 @@ export class GithubApiRegistryClient {
164
132
  const blobSha = await this.createBlob(owner, repo, file.content);
165
133
  tree.push({ path: file.path, mode: '100644', type: 'blob', sha: blobSha });
166
134
  }
167
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/trees`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ base_tree: baseTreeSha, tree }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
168
- const json = await readGithubJson(resp);
169
- if (!(resp.status >= 200 && resp.status < 300))
170
- throw githubError(json, resp.status, 'GitHub tree creation failed.');
171
- const sha = typeof json.sha === 'string' ? json.sha : '';
172
- if (!sha)
173
- throw new Error('GitHub tree response did not include a sha.');
174
- return sha;
135
+ const json = await okJson(await this.send('POST', `${repoPath(owner, repo)}/git/trees`, { base_tree: baseTreeSha, tree }), 'GitHub tree creation failed.');
136
+ return requireString(json.sha, 'GitHub tree response did not include a sha.');
175
137
  }
176
138
  async createCommit(owner, repo, message, treeSha, parents) {
177
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ message, tree: treeSha, parents }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
178
- const json = await readGithubJson(resp);
179
- if (!(resp.status >= 200 && resp.status < 300))
180
- throw githubError(json, resp.status, 'GitHub commit creation failed.');
181
- const sha = typeof json.sha === 'string' ? json.sha : '';
182
- if (!sha)
183
- throw new Error('GitHub commit response did not include a sha.');
184
- return sha;
139
+ const json = await okJson(await this.send('POST', `${repoPath(owner, repo)}/git/commits`, { message, tree: treeSha, parents }), 'GitHub commit creation failed.');
140
+ return requireString(json.sha, 'GitHub commit response did not include a sha.');
185
141
  }
186
142
  /**
187
143
  * Creates `refs/heads/{branch}` pointing at `sha`, or (if it already
@@ -193,17 +149,15 @@ export class GithubApiRegistryClient {
193
149
  * `@jini-ai/deploy`'s `github-pages.ts` already documents for its own ref update.
194
150
  */
195
151
  async ensureBranch(owner, repo, branch, sha) {
196
- const createResp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ ref: `refs/heads/${branch}`, sha }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
197
- if ((createResp.status >= 200 && createResp.status < 300))
152
+ const createResp = await this.send('POST', `${repoPath(owner, repo)}/git/refs`, { ref: `refs/heads/${branch}`, sha });
153
+ if (isOk(createResp.status))
198
154
  return;
199
155
  if (createResp.status !== 409 && createResp.status !== 422) {
200
156
  const json = await readGithubJson(createResp);
201
157
  throw githubError(json, createResp.status, 'GitHub branch creation failed.');
202
158
  }
203
- const updateResp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs/heads/${enc(branch)}`, method: 'PATCH', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ sha, force: true }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
204
- const json = await readGithubJson(updateResp);
205
- if (!(updateResp.status >= 200 && updateResp.status < 300))
206
- throw githubError(json, updateResp.status, 'GitHub branch update failed.');
159
+ const updateResp = await this.send('PATCH', `${repoPath(owner, repo)}/git/refs/heads/${enc(branch)}`, { sha, force: true });
160
+ await okJson(updateResp, 'GitHub branch update failed.');
207
161
  }
208
162
  /**
209
163
  * Opens `POST /repos/{owner}/{repo}/pulls`, or — if GitHub rejects it
@@ -215,16 +169,13 @@ export class GithubApiRegistryClient {
215
169
  * analogous "create-or-find" race.
216
170
  */
217
171
  async ensurePullRequest(owner, repo, request) {
218
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ title: request.title, body: request.body, head: request.branchName, base: request.baseRef }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
172
+ const body = { title: request.title, body: request.body, head: request.branchName, base: request.baseRef };
173
+ const resp = await this.send('POST', `${repoPath(owner, repo)}/pulls`, body);
219
174
  const json = await readGithubJson(resp);
220
- if ((resp.status >= 200 && resp.status < 300)) {
221
- const url = typeof json.html_url === 'string' ? json.html_url : '';
222
- if (!url)
223
- throw new Error('GitHub pull request response did not include an html_url.');
224
- return { url };
175
+ if (isOk(resp.status)) {
176
+ return { url: requireString(json.html_url, 'GitHub pull request response did not include an html_url.') };
225
177
  }
226
- const message = typeof json.message === 'string' ? json.message : '';
227
- if (resp.status === 422 && /already exists/i.test(message)) {
178
+ if (isExistingPullRequestConflict(resp.status, json)) {
228
179
  const existing = await this.findOpenPullRequest(owner, repo, request.baseRef, request.branchName);
229
180
  if (existing)
230
181
  return { url: existing };
@@ -233,17 +184,87 @@ export class GithubApiRegistryClient {
233
184
  }
234
185
  async findOpenPullRequest(owner, repo, base, branch) {
235
186
  const query = new URLSearchParams({ head: `${owner}:${branch}`, base, state: 'open' });
236
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls?${query.toString()}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
187
+ const resp = await this.send('GET', `${repoPath(owner, repo)}/pulls?${query.toString()}`);
237
188
  const json = await readGithubJson(resp);
238
- if (!(resp.status >= 200 && resp.status < 300) || !Array.isArray(json))
189
+ if (!isOk(resp.status) || !Array.isArray(json))
239
190
  return undefined;
240
191
  const first = json[0];
241
192
  return first && typeof first.html_url === 'string' ? first.html_url : undefined;
242
193
  }
194
+ /**
195
+ * The single request builder: every call goes to `apiUrl` with the GitHub
196
+ * headers (bearer auth only when a token is configured) and the QUICK
197
+ * idle/total bounds. A JSON `body` adds the JSON content type.
198
+ */
199
+ send(method, path, body) {
200
+ const json = body === undefined ? undefined : JSON.stringify(body);
201
+ const headers = githubHeaders(this.token, json === undefined ? {} : { 'Content-Type': 'application/json' });
202
+ const request = { url: `${this.apiUrl}${path}`, method, headers, idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK, ...(json === undefined ? {} : { body: json }) };
203
+ return this.http.send({ request });
204
+ }
243
205
  }
244
206
  function enc(value) {
245
207
  return encodeURIComponent(value);
246
208
  }
209
+ function repoPath(owner, repo) {
210
+ return `/repos/${enc(owner)}/${enc(repo)}`;
211
+ }
212
+ function isOk(status) {
213
+ return status >= 200 && status < 300;
214
+ }
215
+ /** Parse the body (a non-JSON body fails first, as before), then reject a non-2xx status with GitHub's own message. */
216
+ async function okJson(resp, failure) {
217
+ const json = await readGithubJson(resp);
218
+ if (!isOk(resp.status))
219
+ throw githubError(json, resp.status, failure);
220
+ return json;
221
+ }
222
+ /** A required non-empty string field of a GitHub response; anything else is a malformed response. */
223
+ function requireString(value, missing) {
224
+ if (typeof value !== 'string' || !value)
225
+ throw new Error(missing);
226
+ return value;
227
+ }
228
+ /** GitHub's documented "a pull request already exists for this head/base" failure: a 422 whose message says so. */
229
+ function isExistingPullRequestConflict(status, json) {
230
+ // `message` is read before the status test on purpose: it keeps the exact
231
+ // pre-refactor behaviour for a non-2xx JSON `null` body (a TypeError here).
232
+ const message = typeof json.message === 'string' ? json.message : '';
233
+ return status === 422 && /already exists/i.test(message);
234
+ }
235
+ /**
236
+ * The Contents API's inline base64 content, or a clear, attributable error
237
+ * for a directory listing, a non-file entry, or the 1-100 MB shape that
238
+ * carries no inline content (see `readManifest`'s doc comment).
239
+ */
240
+ function inlineFileContent(json, where) {
241
+ if (Array.isArray(json)) {
242
+ throw new Error(`Registry manifest path is a directory, not a file: ${where}`);
243
+ }
244
+ if (json.type !== 'file') {
245
+ throw new Error(`Registry manifest path is not a file (type: ${String(json.type)}): ${where}`);
246
+ }
247
+ if (json.encoding !== 'base64' || typeof json.content !== 'string') {
248
+ throw new Error(`Registry manifest at ${where} is too large for the Contents API's inline response ` +
249
+ `(size: ${typeof json.size === 'number' ? json.size : 'unknown'} bytes, encoding: ${String(json.encoding)}); ` +
250
+ 'split the manifest into a smaller file or fetch it via the Git Trees/raw-media-type API instead.');
251
+ }
252
+ return json.content;
253
+ }
254
+ /**
255
+ * Decode GitHub's newline-wrapped base64 and JSON-parse it (not schema-validated
256
+ * here; see `readManifest`). Node's base64 decoder already skips the embedded
257
+ * newlines, so no pre-stripping is needed (pinned by the newline-wrapped test).
258
+ */
259
+ function parseManifest(content, where) {
260
+ const decoded = Buffer.from(content, 'base64').toString('utf8');
261
+ try {
262
+ return JSON.parse(decoded);
263
+ }
264
+ catch (cause) {
265
+ throw new Error(`Registry manifest at ${where} is not valid JSON.`, { cause });
266
+ }
267
+ }
247
268
  /** URL-encodes each path segment individually so directory separators survive but special characters within a segment don't. */
248
269
  function encPath(path) {
249
270
  return path.split('/').filter(Boolean).map(encodeURIComponent).join('/');
@@ -28,55 +28,18 @@ export class StaticRegistryBackend {
28
28
  this.clock = options.clock ?? { nowMs: () => Date.now() };
29
29
  }
30
30
  async list(_required, filter = {}) {
31
- const parsedFilter = RegistryListFilterSchema.parse(filter);
32
- let entries = validEntries(this.getManifest());
33
- if (!parsedFilter?.includeYanked) {
34
- entries = entries.filter((entry) => !entry.yanked);
35
- }
36
- if (parsedFilter?.publisher) {
37
- const publisher = parsedFilter.publisher.toLowerCase();
38
- entries = entries.filter((entry) => entry.publisher?.id?.toLowerCase() === publisher || entry.publisher?.github?.toLowerCase() === publisher);
39
- }
40
- if (parsedFilter?.tags && parsedFilter.tags.length > 0) {
41
- const tags = parsedFilter.tags.map((tag) => tag.toLowerCase());
42
- entries = entries.filter((entry) => {
43
- const entryTags = new Set((entry.tags ?? []).map((tag) => tag.toLowerCase()));
44
- return tags.every((tag) => entryTags.has(tag));
45
- });
46
- }
47
- if (parsedFilter?.query) {
48
- const terms = parsedFilter.query.toLowerCase().split(/\s+/g).filter(Boolean);
49
- if (terms.length > 0) {
50
- entries = entries.filter((entry) => terms.some((term) => searchHaystack(entry).includes(term)));
51
- }
52
- }
53
- return entries;
31
+ const parsedFilter = RegistryListFilterSchema.unwrap().parse(filter);
32
+ return validEntries(this.getManifest()).filter(listFilterPredicate(parsedFilter));
54
33
  }
55
34
  async search(required, optional = {}) {
56
35
  const query = RegistrySearchQuerySchema.parse({ ...required, ...optional });
57
- const terms = query.query.toLowerCase().split(/\s+/g).filter(Boolean);
58
- const tags = new Set((query.tags ?? []).map((tag) => tag.toLowerCase()));
36
+ const terms = queryTerms(query.query);
37
+ const tags = lowercased(query.tags);
59
38
  // Pass `includeYanked` through to `list` so search honors the same
60
39
  // filter contract instead of unconditionally dropping yanked entries.
61
40
  const entries = await this.list({}, { includeYanked: query.includeYanked });
62
- const results = [];
63
- for (const entry of entries) {
64
- if (tags.size > 0) {
65
- const entryTags = new Set((entry.tags ?? []).map((tag) => tag.toLowerCase()));
66
- if (![...tags].every((tag) => entryTags.has(tag)))
67
- continue;
68
- }
69
- const haystack = searchHaystack(entry);
70
- const matched = terms.filter((term) => haystack.includes(term));
71
- if (terms.length > 0 && matched.length === 0)
72
- continue;
73
- results.push({
74
- entry,
75
- score: terms.length === 0 ? 0 : matched.length / terms.length,
76
- matched,
77
- });
78
- }
79
- return results
41
+ return entries
42
+ .flatMap((entry) => searchResultFor(entry, terms, tags))
80
43
  .sort((left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name))
81
44
  .slice(0, query.limit ?? 100);
82
45
  }
@@ -121,7 +84,6 @@ export class StaticRegistryBackend {
121
84
  return resolved?.entry ?? null;
122
85
  }
123
86
  async doctor(_required) {
124
- const issues = [];
125
87
  // Deliberately audits the RAW manifest entries (not the `validEntries()`
126
88
  // schema-filtered set `list`/`search`/`resolve` use) — doctor's whole
127
89
  // purpose is to surface malformed data, so silently dropping a bad entry
@@ -139,69 +101,11 @@ export class StaticRegistryBackend {
139
101
  // Report that as one explicit issue instead of letting `for...of` throw
140
102
  // a bare `TypeError` out of a caller-facing diagnostic method.
141
103
  const rawEntries = manifestEntriesRaw(this.getManifest());
142
- if (!Array.isArray(rawEntries)) {
143
- issues.push({
144
- severity: 'error',
145
- code: 'malformed-manifest',
146
- message: 'Registry manifest "entries" is missing or not an array; no entries could be checked.',
147
- });
148
- }
149
104
  const entries = Array.isArray(rawEntries) ? rawEntries : [];
150
- for (const raw of entries) {
151
- const value = raw;
152
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
153
- issues.push({
154
- severity: 'error',
155
- code: 'malformed-entry',
156
- message: 'Registry entry is not a valid object and could not be checked.',
157
- });
158
- continue;
159
- }
160
- const candidate = value;
161
- const name = typeof candidate.name === 'string' ? candidate.name : undefined;
162
- if (!name || !/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(name)) {
163
- issues.push({
164
- severity: 'error',
165
- code: 'invalid-name',
166
- message: 'Registry entry name must be vendor/name.',
167
- pluginName: name,
168
- });
169
- }
170
- const dist = candidate.dist && typeof candidate.dist === 'object' ? candidate.dist : undefined;
171
- if (!candidate.source && !dist?.archive) {
172
- issues.push({
173
- severity: 'error',
174
- code: 'missing-source',
175
- message: 'Registry entry must provide source or dist.archive.',
176
- pluginName: name,
177
- });
178
- }
179
- if (!candidate.license) {
180
- issues.push({
181
- severity: 'warning',
182
- code: 'missing-license',
183
- message: 'Registry entry should declare a license.',
184
- pluginName: name,
185
- });
186
- }
187
- const capabilitiesSummary = Array.isArray(candidate.capabilitiesSummary) ? candidate.capabilitiesSummary : undefined;
188
- if (!capabilitiesSummary || capabilitiesSummary.length === 0) {
189
- issues.push({
190
- severity: 'warning',
191
- code: 'missing-capabilities',
192
- message: 'Registry entry should summarize its capabilities.',
193
- pluginName: name,
194
- });
195
- }
196
- if (candidate.yanked && !candidate.yankReason) {
197
- issues.push({
198
- severity: 'error',
199
- code: 'missing-yank-reason',
200
- message: 'Yanked entries must keep a human-readable reason.',
201
- pluginName: name,
202
- });
203
- }
204
- }
105
+ const issues = [
106
+ ...(Array.isArray(rawEntries) ? [] : [{ ...MALFORMED_MANIFEST_ISSUE }]),
107
+ ...entries.flatMap(doctorEntryIssues),
108
+ ];
205
109
  return {
206
110
  ok: !issues.some((issue) => issue.severity === 'error'),
207
111
  backendId: this.id,
@@ -281,4 +185,100 @@ function searchHaystack(entry) {
281
185
  .join(' ')
282
186
  .toLowerCase();
283
187
  }
188
+ /** @internal Lowercase every string in an optional list. */
189
+ function lowercased(values) {
190
+ return (values ?? []).map((value) => value.toLowerCase());
191
+ }
192
+ /** @internal Whitespace-separated, lowercased, non-empty query terms. */
193
+ function queryTerms(query) {
194
+ return query.toLowerCase().split(/\s+/g).filter(Boolean);
195
+ }
196
+ /** @internal True when the entry carries every one of the (already lowercased) `tags`; an empty list admits every entry. */
197
+ function hasEveryTag(entry, tags) {
198
+ const entryTags = new Set(lowercased(entry.tags));
199
+ return tags.every((tag) => entryTags.has(tag));
200
+ }
201
+ /** @internal `list`'s filter: yanked, publisher id/github handle, every tag, and any query term — all case-insensitive. */
202
+ function listFilterPredicate(filter) {
203
+ const publisher = filter.publisher?.toLowerCase();
204
+ const tags = lowercased(filter.tags);
205
+ const terms = queryTerms(filter.query ?? '');
206
+ return (entry) => (filter.includeYanked === true || !entry.yanked) &&
207
+ (!publisher || publishedBy(entry, publisher)) &&
208
+ hasEveryTag(entry, tags) &&
209
+ (terms.length === 0 || terms.some((term) => searchHaystack(entry).includes(term)));
210
+ }
211
+ /** @internal True when the (already lowercased) `publisher` is the entry's publisher id or GitHub handle. */
212
+ function publishedBy(entry, publisher) {
213
+ return entry.publisher?.id?.toLowerCase() === publisher || entry.publisher?.github?.toLowerCase() === publisher;
214
+ }
215
+ /** @internal `search`'s per-entry result: none when a tag is missing or no term matches, else the matched fraction of terms (0 for an empty query). */
216
+ function searchResultFor(entry, terms, tags) {
217
+ if (!hasEveryTag(entry, tags))
218
+ return [];
219
+ const haystack = searchHaystack(entry);
220
+ const matched = terms.filter((term) => haystack.includes(term));
221
+ if (terms.length > 0 && matched.length === 0)
222
+ return [];
223
+ return [{ entry, score: terms.length === 0 ? 0 : matched.length / terms.length, matched }];
224
+ }
225
+ const MALFORMED_MANIFEST_ISSUE = {
226
+ severity: 'error',
227
+ code: 'malformed-manifest',
228
+ message: 'Registry manifest "entries" is missing or not an array; no entries could be checked.',
229
+ };
230
+ /**
231
+ * @internal The per-entry `doctor` checks, in report order. Each reads a RAW,
232
+ * unvalidated entry, so every field is guarded before it is dereferenced.
233
+ */
234
+ const DOCTOR_ENTRY_CHECKS = [
235
+ {
236
+ severity: 'error',
237
+ code: 'invalid-name',
238
+ message: 'Registry entry name must be vendor/name.',
239
+ // The schema rejects undefined and "" too, so no separate presence check.
240
+ failed: (_candidate, name) => !RegistryEntrySchema.shape.name.safeParse(name).success,
241
+ },
242
+ {
243
+ severity: 'error',
244
+ code: 'missing-source',
245
+ message: 'Registry entry must provide source or dist.archive.',
246
+ failed: (candidate) => {
247
+ const dist = candidate.dist && typeof candidate.dist === 'object' ? candidate.dist : undefined;
248
+ return !candidate.source && !dist?.archive;
249
+ },
250
+ },
251
+ {
252
+ severity: 'warning',
253
+ code: 'missing-license',
254
+ message: 'Registry entry should declare a license.',
255
+ failed: (candidate) => !candidate.license,
256
+ },
257
+ {
258
+ severity: 'warning',
259
+ code: 'missing-capabilities',
260
+ message: 'Registry entry should summarize its capabilities.',
261
+ failed: (candidate) => !Array.isArray(candidate.capabilitiesSummary) || candidate.capabilitiesSummary.length === 0,
262
+ },
263
+ {
264
+ severity: 'error',
265
+ code: 'missing-yank-reason',
266
+ message: 'Yanked entries must keep a human-readable reason.',
267
+ failed: (candidate) => Boolean(candidate.yanked) && !candidate.yankReason,
268
+ },
269
+ ];
270
+ /** @internal `doctor`'s issues for one raw manifest entry; a value that is not a plain object is one `malformed-entry` issue. */
271
+ function doctorEntryIssues(raw) {
272
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
273
+ return [{ severity: 'error', code: 'malformed-entry', message: 'Registry entry is not a valid object and could not be checked.' }];
274
+ }
275
+ const candidate = raw;
276
+ const name = typeof candidate.name === 'string' ? candidate.name : undefined;
277
+ return DOCTOR_ENTRY_CHECKS.filter((check) => check.failed(candidate, name)).map(({ severity, code, message }) => ({
278
+ severity,
279
+ code,
280
+ message,
281
+ pluginName: name,
282
+ }));
283
+ }
284
284
  //# sourceMappingURL=static-backend.js.map
@@ -68,6 +68,6 @@ export declare function searchToolCatalog({ db, query }: {
68
68
  db: SqliteDb;
69
69
  query: string;
70
70
  }, { limit }?: {
71
- limit?: number;
71
+ limit?: number | undefined;
72
72
  }): readonly ToolCatalogSearchHit[];
73
73
  //# sourceMappingURL=sqlite.d.ts.map
@@ -1,8 +1,10 @@
1
1
  import type { Clock } from '@jini-ai/core/primitives';
2
- import type { ToolMetadata } from '@jini-ai/core';
2
+ import type { AgentToolSideEffect, ToolMetadata } from '@jini-ai/core';
3
3
  /** Structural contracts only: callers choose their registry and search backend. */
4
4
  export interface ToolDescriptor {
5
5
  readonly metadata?: ToolMetadata;
6
+ readonly readOnly?: boolean;
7
+ readonly sideEffects?: AgentToolSideEffect;
6
8
  readonly id: string;
7
9
  readonly description?: string | undefined;
8
10
  readonly inputSchema?: unknown;
@@ -11,6 +13,8 @@ export interface ToolDescriptorSource {
11
13
  list(): readonly ToolDescriptor[];
12
14
  }
13
15
  export interface ToolCatalogEntry {
16
+ readonly readOnly?: boolean;
17
+ readonly sideEffects?: AgentToolSideEffect | 'unknown';
14
18
  readonly id: string;
15
19
  readonly source: string;
16
20
  readonly description: string;
@@ -1,3 +1,4 @@
1
+ import { toolDiscoveryMetadata } from '@jini-ai/core';
1
2
  import { nowIso } from '@jini-ai/core/primitives';
2
3
  /** Live overview, preserving registration order; vocabulary and source policy are host-owned. */
3
4
  export function listToolCatalogEntries(required) {
@@ -23,6 +24,7 @@ export function buildToolCatalogQuery(required, optional = {}) {
23
24
  throw new Error('catalog tool IDs must be unique');
24
25
  }
25
26
  const authored = new Map();
27
+ const effects = new Map(descriptors.map(descriptor => [descriptor.id, toolDiscoveryMetadata({ descriptor })]));
26
28
  const entries = descriptors.map(descriptor => {
27
29
  const description = descriptor.description ?? '';
28
30
  authored.set(descriptor.id, required.enricher.authoredDescription({ description }));
@@ -45,11 +47,11 @@ export function buildToolCatalogQuery(required, optional = {}) {
45
47
  search({ query }, { limit = 10 } = {}) {
46
48
  if (!Number.isSafeInteger(limit) || limit < 0)
47
49
  throw new RangeError('catalog limit must be a nonnegative integer');
48
- return store.search({ query }, { limit }).map(hit => ({ ...hit, description: descriptionFor(hit) }));
50
+ return store.search({ query }, { limit }).map(hit => ({ ...hit, ...effects.get(hit.id), description: descriptionFor(hit) }));
49
51
  },
50
52
  describe({ id }) {
51
53
  const entry = store.describe({ id });
52
- return entry === null ? null : { ...entry, description: descriptionFor(entry) };
54
+ return entry === null ? null : { ...entry, ...effects.get(entry.id), description: descriptionFor(entry) };
53
55
  },
54
56
  };
55
57
  }
@@ -7,10 +7,10 @@ export function createSearchEnricher(required, _optional = {}) {
7
7
  throw new Error('search vocabulary marker must not be empty');
8
8
  return {
9
9
  indexedDescription({ id, description, metadata }, { includeDoc2query }) {
10
- const vocabulary = metadata?.search?.keywords ?? (Object.hasOwn(keywords, id) ? keywords[id] : undefined);
11
- const queries = metadata?.search?.queries ?? (Object.hasOwn(questions, id) ? questions[id] : undefined);
12
- const tail = [vocabulary, includeDoc2query ? queries?.join(' ') : undefined]
13
- .filter(part => Boolean(part?.length)).join(' ');
10
+ const search = metadata?.search;
11
+ const vocabulary = search?.keywords ?? ownValue(keywords, id);
12
+ const queries = includeDoc2query ? (search?.queries ?? ownValue(questions, id))?.join(' ') : undefined;
13
+ const tail = [vocabulary, queries].filter(Boolean).join(' ');
14
14
  if (!tail)
15
15
  return description;
16
16
  return description ? `${description}${marker}${tail}` : tail;
@@ -21,6 +21,10 @@ export function createSearchEnricher(required, _optional = {}) {
21
21
  },
22
22
  };
23
23
  }
24
+ /** Own-property lookup: inherited object keys (`toString`, `__proto__`) never count as host vocabulary. */
25
+ function ownValue(record, id) {
26
+ return Object.hasOwn(record, id) ? record[id] : undefined;
27
+ }
24
28
  /** Source naming conventions are supplied by the host, including the orphan-ID fallback. */
25
29
  export function createPrefixSourceClassifier(required) {
26
30
  if (!required.separator || !required.fallbackSource)
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @module trust-certificates
3
+ *
4
+ * X.509 helpers behind `trust.ts`'s `github-oidc` verifier: PEM bundle
5
+ * parsing, the cryptographic chain walk to a host-configured CA, and SAN URI
6
+ * extraction. Internal to this package (not re-exported from the barrel).
7
+ */
8
+ import { X509Certificate } from 'node:crypto';
9
+ /** @internal Split a PEM string that may contain a leaf certificate followed by one or more intermediate certificates into individual parsed certificates, leaf first. */
10
+ export declare function parseCertificateBundle(pem: string): X509Certificate[];
11
+ /**
12
+ * @internal Walk from `chain[0]` (the leaf) through any bundled
13
+ * intermediates toward a certificate in `trustedCas`, checking a genuine
14
+ * cryptographic signature at every hop (`X509Certificate#verify`, not just
15
+ * `checkIssued`'s DN-string comparison). Bounded by `chain.length +
16
+ * trustedCas.length + 1` hops so a malformed/cyclic bundle cannot loop
17
+ * forever.
18
+ */
19
+ export declare function chainToTrustedRoot(chain: X509Certificate[], trustedCas: X509Certificate[]): boolean;
20
+ /**
21
+ * @internal `checkIssued` (DN linkage) AND `verify` (the actual cryptographic
22
+ * signature check) — either alone is insufficient: DN match alone proves
23
+ * nothing cryptographically. The `try`/`catch` is defense-in-depth for this
24
+ * function's own "never throw" contract, not a path this module's test
25
+ * suite demonstrates reachable: empirically, `X509Certificate#verify()`
26
+ * (unlike the standalone `crypto.verify()` function used later in this
27
+ * file, which genuinely does throw for an incompatible key/digest pairing —
28
+ * see `verifyRegistrySignature`'s doc comment on that call) was checked
29
+ * across EC/RSA/Ed25519 issuer-key combinations during this module's
30
+ * construction and consistently returned `false` rather than throwing.
31
+ * Kept anyway in case a future Node/OpenSSL version or an exotic key type
32
+ * behaves differently.
33
+ *
34
+ * **Re-verified 2026-07-22** (audit fix — re-derived independently rather than
35
+ * trusted from this comment's own prior claim): all 9 cross-combinations of
36
+ * {RSA, P-256, Ed25519} signer × tester, plus same-key self-verification for
37
+ * each, plus a P-384 cross-check, all returned a clean `boolean` — zero
38
+ * throws — against this repo's actual Node/OpenSSL (v22.22.2 / OpenSSL
39
+ * 3.0.13). `X509Certificate#verify(publicKey)` *can* throw a `TypeError`,
40
+ * but only for a malformed `publicKey` argument (a non-`KeyObject`, or a
41
+ * private key passed where a public key is required) — neither is reachable
42
+ * through this function's only call site (`chainToTrustedRoot`, which always
43
+ * passes `issuer.publicKey`, a real `X509Certificate`'s own getter, never
44
+ * arbitrary user input). The `catch` here is genuinely unreachable through
45
+ * this module's real call graph, confirmed empirically, not merely asserted.
46
+ */
47
+ export declare function certIssuedAndSignedBy(cert: Pick<X509Certificate, 'checkIssued' | 'verify'>, issuer: X509Certificate): boolean;
48
+ /** @internal Extract `URI:...` entries from an `X509Certificate#subjectAltName` string (e.g. `"URI:https://github.com/acme/example/.github/workflows/build.yml@refs/heads/main"`, comma-separated when multiple SAN entries are present). */
49
+ export declare function parseSanUris(subjectAltName: string | null | undefined): string[];
50
+ //# sourceMappingURL=trust-certificates.d.ts.map
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @module trust-certificates
3
+ *
4
+ * X.509 helpers behind `trust.ts`'s `github-oidc` verifier: PEM bundle
5
+ * parsing, the cryptographic chain walk to a host-configured CA, and SAN URI
6
+ * extraction. Internal to this package (not re-exported from the barrel).
7
+ */
8
+ import { X509Certificate } from 'node:crypto';
9
+ /** @internal Split a PEM string that may contain a leaf certificate followed by one or more intermediate certificates into individual parsed certificates, leaf first. */
10
+ export function parseCertificateBundle(pem) {
11
+ const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? [];
12
+ return blocks.map((block) => new X509Certificate(block));
13
+ }
14
+ /**
15
+ * @internal Walk from `chain[0]` (the leaf) through any bundled
16
+ * intermediates toward a certificate in `trustedCas`, checking a genuine
17
+ * cryptographic signature at every hop (`X509Certificate#verify`, not just
18
+ * `checkIssued`'s DN-string comparison). Bounded by `chain.length +
19
+ * trustedCas.length + 1` hops so a malformed/cyclic bundle cannot loop
20
+ * forever.
21
+ */
22
+ export function chainToTrustedRoot(chain, trustedCas) {
23
+ let current = chain[0];
24
+ if (!current)
25
+ return false;
26
+ const remaining = chain.slice(1);
27
+ const maxHops = chain.length + trustedCas.length + 1;
28
+ for (let hop = 0; hop < maxHops; hop += 1) {
29
+ if (trustedCas.some((ca) => certIssuedAndSignedBy(current, ca)))
30
+ return true;
31
+ const nextIndex = remaining.findIndex((candidate) => certIssuedAndSignedBy(current, candidate));
32
+ if (nextIndex === -1)
33
+ return false;
34
+ current = remaining[nextIndex];
35
+ remaining.splice(nextIndex, 1);
36
+ }
37
+ return false;
38
+ }
39
+ /**
40
+ * @internal `checkIssued` (DN linkage) AND `verify` (the actual cryptographic
41
+ * signature check) — either alone is insufficient: DN match alone proves
42
+ * nothing cryptographically. The `try`/`catch` is defense-in-depth for this
43
+ * function's own "never throw" contract, not a path this module's test
44
+ * suite demonstrates reachable: empirically, `X509Certificate#verify()`
45
+ * (unlike the standalone `crypto.verify()` function used later in this
46
+ * file, which genuinely does throw for an incompatible key/digest pairing —
47
+ * see `verifyRegistrySignature`'s doc comment on that call) was checked
48
+ * across EC/RSA/Ed25519 issuer-key combinations during this module's
49
+ * construction and consistently returned `false` rather than throwing.
50
+ * Kept anyway in case a future Node/OpenSSL version or an exotic key type
51
+ * behaves differently.
52
+ *
53
+ * **Re-verified 2026-07-22** (audit fix — re-derived independently rather than
54
+ * trusted from this comment's own prior claim): all 9 cross-combinations of
55
+ * {RSA, P-256, Ed25519} signer × tester, plus same-key self-verification for
56
+ * each, plus a P-384 cross-check, all returned a clean `boolean` — zero
57
+ * throws — against this repo's actual Node/OpenSSL (v22.22.2 / OpenSSL
58
+ * 3.0.13). `X509Certificate#verify(publicKey)` *can* throw a `TypeError`,
59
+ * but only for a malformed `publicKey` argument (a non-`KeyObject`, or a
60
+ * private key passed where a public key is required) — neither is reachable
61
+ * through this function's only call site (`chainToTrustedRoot`, which always
62
+ * passes `issuer.publicKey`, a real `X509Certificate`'s own getter, never
63
+ * arbitrary user input). The `catch` here is genuinely unreachable through
64
+ * this module's real call graph, confirmed empirically, not merely asserted.
65
+ */
66
+ export function certIssuedAndSignedBy(cert, issuer) {
67
+ try {
68
+ return cert.checkIssued(issuer) && cert.verify(issuer.publicKey);
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ /** @internal Extract `URI:...` entries from an `X509Certificate#subjectAltName` string (e.g. `"URI:https://github.com/acme/example/.github/workflows/build.yml@refs/heads/main"`, comma-separated when multiple SAN entries are present). */
75
+ export function parseSanUris(subjectAltName) {
76
+ if (!subjectAltName)
77
+ return [];
78
+ return subjectAltName
79
+ .split(',')
80
+ .map((part) => part.trim())
81
+ .filter((part) => part.startsWith('URI:'))
82
+ .map((part) => part.slice('URI:'.length));
83
+ }
84
+ //# sourceMappingURL=trust-certificates.js.map
package/dist/trust.js CHANGED
@@ -77,6 +77,7 @@
77
77
  * configured.
78
78
  */
79
79
  import { X509Certificate, verify as nodeVerify } from 'node:crypto';
80
+ import { chainToTrustedRoot, parseCertificateBundle, parseSanUris } from './trust-certificates.js';
80
81
  /** GitHub Actions' own OIDC token issuer — the default {@link GithubOidcTrustRoot.allowedIssuers} entry. */
81
82
  export const GITHUB_ACTIONS_OIDC_ISSUER = 'https://token.actions.githubusercontent.com';
82
83
  /**
@@ -114,68 +115,96 @@ export function verifyRegistrySignature({ entry, signature }, { trustRoot } = {}
114
115
  // report "unsupported", never silently pass and never throw.
115
116
  return { verified: false, kind: signature.kind, reason: `unsupported signature kind: ${signature.kind}` };
116
117
  }
117
- const root = trustRoot?.githubOidc;
118
+ const outcome = verifyGithubOidcSignature(entry, signature, trustRoot?.githubOidc);
119
+ if ('reason' in outcome)
120
+ return { verified: false, kind: signature.kind, reason: outcome.reason };
121
+ return { verified: true, kind: signature.kind, issuer: outcome.issuer, ...(outcome.subject !== undefined ? { subject: outcome.subject } : {}) };
122
+ }
123
+ const fail = (reason) => ({ reason });
124
+ /**
125
+ * The `github-oidc` checks, in their fixed order — the first failing check's
126
+ * reason is the one reported: trust root, signature fields, certificate
127
+ * chain + validity window, identity allowlist, signature bytes.
128
+ */
129
+ function verifyGithubOidcSignature(entry, signature, root) {
118
130
  if (!root || root.caCertificates.length === 0) {
119
131
  // Decision 4: a backend with no configured trust root gets no
120
132
  // verification at all — current (pre-this-task) behavior, unchanged.
121
- return { verified: false, kind: signature.kind, reason: 'no github-oidc trust root configured' };
122
- }
123
- if (!signature.certificate) {
124
- return { verified: false, kind: signature.kind, reason: 'github-oidc signature is missing a certificate' };
125
- }
126
- if (!signature.issuer) {
127
- return { verified: false, kind: signature.kind, reason: 'github-oidc signature is missing an issuer' };
133
+ return fail('no github-oidc trust root configured');
134
+ }
135
+ const fields = checkSignatureFields(signature, root);
136
+ if ('reason' in fields)
137
+ return fields;
138
+ const leaf = checkCertificate(fields.certificate, root, fields.signedAt);
139
+ if ('reason' in leaf)
140
+ return leaf;
141
+ const identities = parseSanUris(leaf.subjectAltName);
142
+ if (!identityAllowed(identities, root.allowedIdentities)) {
143
+ return fail('signer identity is not in the configured allowlist');
128
144
  }
145
+ const signatureFailure = checkSignatureBytes(entry, signature.signature, leaf);
146
+ if (signatureFailure)
147
+ return signatureFailure;
148
+ return { issuer: fields.issuer, subject: signature.subject ?? identities[0] };
149
+ }
150
+ /** Presence of certificate/issuer/signedAt, the issuer allowlist, and a parseable `signedAt`. */
151
+ function checkSignatureFields(signature, root) {
152
+ if (!signature.certificate)
153
+ return fail('github-oidc signature is missing a certificate');
154
+ if (!signature.issuer)
155
+ return fail('github-oidc signature is missing an issuer');
129
156
  const allowedIssuers = root.allowedIssuers ?? [GITHUB_ACTIONS_OIDC_ISSUER];
130
157
  if (!allowedIssuers.includes(signature.issuer)) {
131
- return { verified: false, kind: signature.kind, reason: `issuer ${JSON.stringify(signature.issuer)} is not in the configured allowlist` };
132
- }
133
- if (!signature.signedAt) {
134
- return { verified: false, kind: signature.kind, reason: 'github-oidc signature is missing signedAt' };
158
+ return fail(`issuer ${JSON.stringify(signature.issuer)} is not in the configured allowlist`);
135
159
  }
160
+ if (!signature.signedAt)
161
+ return fail('github-oidc signature is missing signedAt');
136
162
  const signedAt = new Date(signature.signedAt);
137
- if (Number.isNaN(signedAt.getTime())) {
138
- return { verified: false, kind: signature.kind, reason: 'github-oidc signature has an invalid signedAt timestamp' };
139
- }
163
+ if (Number.isNaN(signedAt.getTime()))
164
+ return fail('github-oidc signature has an invalid signedAt timestamp');
165
+ return { certificate: signature.certificate, issuer: signature.issuer, signedAt };
166
+ }
167
+ /** Parse the bundled certificate(s) and the configured CAs, require a chain to a CA, and require `signedAt` inside the leaf's validity window. Returns the leaf. */
168
+ function checkCertificate(pem, root, signedAt) {
140
169
  let chain;
141
170
  try {
142
- chain = parseCertificateBundle(signature.certificate);
171
+ chain = parseCertificateBundle(pem);
143
172
  }
144
173
  catch (cause) {
145
- return { verified: false, kind: signature.kind, reason: `could not parse certificate: ${cause.message}` };
146
- }
147
- if (chain.length === 0) {
148
- return { verified: false, kind: signature.kind, reason: 'no PEM certificate found in signature.certificate' };
174
+ return fail(`could not parse certificate: ${cause.message}`);
149
175
  }
150
176
  const leaf = chain[0];
177
+ if (!leaf)
178
+ return fail('no PEM certificate found in signature.certificate');
151
179
  let trustedCas;
152
180
  try {
153
- trustedCas = root.caCertificates.map((pem) => new X509Certificate(pem));
181
+ trustedCas = root.caCertificates.map((caPem) => new X509Certificate(caPem));
154
182
  }
155
183
  catch (cause) {
156
- return { verified: false, kind: signature.kind, reason: `configured trust root certificate is invalid: ${cause.message}` };
157
- }
158
- if (!chainToTrustedRoot(chain, trustedCas)) {
159
- return { verified: false, kind: signature.kind, reason: 'certificate does not chain to a configured trust root' };
184
+ return fail(`configured trust root certificate is invalid: ${cause.message}`);
160
185
  }
186
+ if (!chainToTrustedRoot(chain, trustedCas))
187
+ return fail('certificate does not chain to a configured trust root');
161
188
  if (signedAt < leaf.validFromDate || signedAt > leaf.validToDate) {
162
- return { verified: false, kind: signature.kind, reason: 'signedAt falls outside the certificate validity window' };
163
- }
164
- const identities = parseSanUris(leaf.subjectAltName);
165
- if (root.allowedIdentities && root.allowedIdentities.length > 0) {
166
- const matched = identities.some((identity) => root.allowedIdentities.some((pattern) => (typeof pattern === 'string' ? pattern === identity : pattern.test(identity))));
167
- if (!matched) {
168
- return { verified: false, kind: signature.kind, reason: 'signer identity is not in the configured allowlist' };
169
- }
189
+ return fail('signedAt falls outside the certificate validity window');
170
190
  }
191
+ return leaf;
192
+ }
193
+ /** No (or an empty) allowlist accepts any identity; otherwise one SAN URI must match one pattern — exact string, or `RegExp#test`. */
194
+ function identityAllowed(identities, allowedIdentities) {
195
+ if (!allowedIdentities || allowedIdentities.length === 0)
196
+ return true;
197
+ return identities.some((identity) => allowedIdentities.some((pattern) => (typeof pattern === 'string' ? pattern === identity : pattern.test(identity))));
198
+ }
199
+ /** Verify `signature` (base64) over {@link canonicalRegistrySigningPayload} with the leaf's public key; `undefined` when it verifies. */
200
+ function checkSignatureBytes(entry, signature, leaf) {
171
201
  // `Buffer.from(str, 'base64')` never throws (Node's base64 decoder is
172
202
  // lenient about invalid input, silently dropping bad characters) — a
173
203
  // malformed encoding surfaces as an empty/garbage buffer that then fails
174
204
  // the signature check below, not as an exception here.
175
- const signatureBytes = Buffer.from(signature.signature, 'base64');
176
- if (signatureBytes.length === 0) {
177
- return { verified: false, kind: signature.kind, reason: 'signature is empty after base64 decoding' };
178
- }
205
+ const signatureBytes = Buffer.from(signature, 'base64');
206
+ if (signatureBytes.length === 0)
207
+ return fail('signature is empty after base64 decoding');
179
208
  const payload = Buffer.from(canonicalRegistrySigningPayload({ entry }), 'utf8');
180
209
  let signatureValid;
181
210
  try {
@@ -188,13 +217,9 @@ export function verifyRegistrySignature({ entry, signature }, { trustRoot } = {}
188
217
  signatureValid = nodeVerify('sha256', payload, leaf.publicKey, signatureBytes);
189
218
  }
190
219
  catch (cause) {
191
- return { verified: false, kind: signature.kind, reason: `signature verification failed: ${cause.message}` };
192
- }
193
- if (!signatureValid) {
194
- return { verified: false, kind: signature.kind, reason: 'signature does not match the certificate public key' };
220
+ return fail(`signature verification failed: ${cause.message}`);
195
221
  }
196
- const subject = signature.subject ?? identities[0];
197
- return { verified: true, kind: signature.kind, issuer: signature.issuer, ...(subject !== undefined ? { subject } : {}) };
222
+ return signatureValid ? undefined : fail('signature does not match the certificate public key');
198
223
  }
199
224
  /**
200
225
  * Verify every signature on `entry` against `trustRoot`, returning the first
@@ -217,79 +242,4 @@ export function verifyRegistryEntrySignatures({ entry }, { trustRoot } = {}) {
217
242
  }
218
243
  return last;
219
244
  }
220
- /** @internal Split a PEM string that may contain a leaf certificate followed by one or more intermediate certificates into individual parsed certificates, leaf first. */
221
- function parseCertificateBundle(pem) {
222
- const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? [];
223
- return blocks.map((block) => new X509Certificate(block));
224
- }
225
- /**
226
- * @internal Walk from `chain[0]` (the leaf) through any bundled
227
- * intermediates toward a certificate in `trustedCas`, checking a genuine
228
- * cryptographic signature at every hop (`X509Certificate#verify`, not just
229
- * `checkIssued`'s DN-string comparison). Bounded by `chain.length +
230
- * trustedCas.length + 1` hops so a malformed/cyclic bundle cannot loop
231
- * forever.
232
- */
233
- function chainToTrustedRoot(chain, trustedCas) {
234
- let current = chain[0];
235
- if (!current)
236
- return false;
237
- const remaining = chain.slice(1);
238
- const maxHops = chain.length + trustedCas.length + 1;
239
- for (let hop = 0; hop < maxHops; hop += 1) {
240
- if (trustedCas.some((ca) => certIssuedAndSignedBy(current, ca)))
241
- return true;
242
- const nextIndex = remaining.findIndex((candidate) => certIssuedAndSignedBy(current, candidate));
243
- if (nextIndex === -1)
244
- return false;
245
- current = remaining[nextIndex];
246
- remaining.splice(nextIndex, 1);
247
- }
248
- return false;
249
- }
250
- /**
251
- * @internal `checkIssued` (DN linkage) AND `verify` (the actual cryptographic
252
- * signature check) — either alone is insufficient: DN match alone proves
253
- * nothing cryptographically. The `try`/`catch` is defense-in-depth for this
254
- * function's own "never throw" contract, not a path this module's test
255
- * suite demonstrates reachable: empirically, `X509Certificate#verify()`
256
- * (unlike the standalone `crypto.verify()` function used later in this
257
- * file, which genuinely does throw for an incompatible key/digest pairing —
258
- * see `verifyRegistrySignature`'s doc comment on that call) was checked
259
- * across EC/RSA/Ed25519 issuer-key combinations during this module's
260
- * construction and consistently returned `false` rather than throwing.
261
- * Kept anyway in case a future Node/OpenSSL version or an exotic key type
262
- * behaves differently.
263
- *
264
- * **Re-verified 2026-07-22** (audit fix — re-derived independently rather than
265
- * trusted from this comment's own prior claim): all 9 cross-combinations of
266
- * {RSA, P-256, Ed25519} signer × tester, plus same-key self-verification for
267
- * each, plus a P-384 cross-check, all returned a clean `boolean` — zero
268
- * throws — against this repo's actual Node/OpenSSL (v22.22.2 / OpenSSL
269
- * 3.0.13). `X509Certificate#verify(publicKey)` *can* throw a `TypeError`,
270
- * but only for a malformed `publicKey` argument (a non-`KeyObject`, or a
271
- * private key passed where a public key is required) — neither is reachable
272
- * through this function's only call site (`chainToTrustedRoot`, which always
273
- * passes `issuer.publicKey`, a real `X509Certificate`'s own getter, never
274
- * arbitrary user input). The `catch` here is genuinely unreachable through
275
- * this module's real call graph, confirmed empirically, not merely asserted.
276
- */
277
- function certIssuedAndSignedBy(cert, issuer) {
278
- try {
279
- return cert.checkIssued(issuer) && cert.verify(issuer.publicKey);
280
- }
281
- catch {
282
- return false;
283
- }
284
- }
285
- /** @internal Extract `URI:...` entries from an `X509Certificate#subjectAltName` string (e.g. `"URI:https://github.com/acme/example/.github/workflows/build.yml@refs/heads/main"`, comma-separated when multiple SAN entries are present). */
286
- function parseSanUris(subjectAltName) {
287
- if (!subjectAltName)
288
- return [];
289
- return subjectAltName
290
- .split(',')
291
- .map((part) => part.trim())
292
- .filter((part) => part.startsWith('URI:'))
293
- .map((part) => part.slice('URI:'.length));
294
- }
295
245
  //# sourceMappingURL=trust.js.map
@@ -33,31 +33,45 @@ export function resolveRegistryEntryVersion({ entry }, { requestedRange } = {})
33
33
  if (entry.yanked)
34
34
  return null;
35
35
  const versions = entry.versions ?? [];
36
- const range = requestedRange?.trim();
37
- const defaultVersion = entry.distTags?.['latest'] ?? entry.version ?? versions.find((version) => !version.yanked)?.version;
38
- const targetVersion = range && range !== 'latest' ? resolveRequestedVersion(entry, range) : defaultVersion;
39
- if (!targetVersion)
40
- return null;
36
+ const targetVersion = pickTargetVersion(entry, versions, requestedRange?.trim());
37
+ return targetVersion ? resolveTargetVersion(entry, versions, targetVersion) : null;
38
+ }
39
+ /** Attach source and optional fields to an already-chosen version; `null` when that version is yanked or has no source. */
40
+ function resolveTargetVersion(entry, versions, targetVersion) {
41
41
  const versionRecord = versions.find((version) => version.version === targetVersion);
42
42
  if (versionRecord?.yanked)
43
43
  return null;
44
44
  const source = versionRecord?.source ?? entry.source;
45
45
  if (!source)
46
46
  return null;
47
- const resolved = { version: targetVersion, source };
48
- const ref = versionRecord?.ref ?? entry.ref;
47
+ return { version: targetVersion, source, ...optionalVersionFields(versionRecord, entry) };
48
+ }
49
+ /** No range (or `latest`) resolves the entry's default version; anything else must be proven by {@link resolveRequestedVersion}. */
50
+ function pickTargetVersion(entry, versions, range) {
51
+ if (range && range !== 'latest')
52
+ return resolveRequestedVersion(entry, range);
53
+ return entry.distTags?.['latest'] ?? entry.version ?? versions.find((version) => !version.yanked)?.version;
54
+ }
55
+ /** The resolved version's ref/digest/integrity/deprecation, preferring the version record over the entry; absent values are omitted. */
56
+ function optionalVersionFields(record, entry) {
57
+ const fields = {};
58
+ const ref = record?.ref ?? entry.ref;
49
59
  if (ref)
50
- resolved.ref = ref;
51
- const manifestDigest = versionRecord?.manifestDigest ?? versionRecord?.dist?.manifestDigest ?? entry.manifestDigest ?? entry.dist?.manifestDigest;
60
+ fields.ref = ref;
61
+ const manifestDigest = distField(record, entry, 'manifestDigest');
52
62
  if (manifestDigest)
53
- resolved.manifestDigest = manifestDigest;
54
- const archiveIntegrity = versionRecord?.integrity ?? versionRecord?.dist?.integrity ?? entry.integrity ?? entry.dist?.integrity;
63
+ fields.manifestDigest = manifestDigest;
64
+ const archiveIntegrity = distField(record, entry, 'integrity');
55
65
  if (archiveIntegrity)
56
- resolved.archiveIntegrity = archiveIntegrity;
57
- const deprecated = versionRecord?.deprecated ?? entry.deprecated;
66
+ fields.archiveIntegrity = archiveIntegrity;
67
+ const deprecated = record?.deprecated ?? entry.deprecated;
58
68
  if (deprecated !== undefined)
59
- resolved.deprecated = deprecated;
60
- return resolved;
69
+ fields.deprecated = deprecated;
70
+ return fields;
71
+ }
72
+ /** First of record field, record `dist` field, entry field, entry `dist` field. */
73
+ function distField(record, entry, key) {
74
+ return record?.[key] ?? record?.dist?.[key] ?? entry[key] ?? entry.dist?.[key];
61
75
  }
62
76
  /**
63
77
  * Resolve an exact-version request or dist-tag lookup to a version string
@@ -88,35 +102,13 @@ function resolveRequestedVersion(entry, range) {
88
102
  const base = parseSemver(range.slice(1));
89
103
  if (!base)
90
104
  return null;
105
+ const caret = range.startsWith('^');
91
106
  const candidates = versions
92
107
  .filter((version) => !version.yanked)
93
108
  .map((version) => version.version)
94
109
  .filter((version) => {
95
110
  const parsed = parseSemver(version);
96
- if (!parsed)
97
- return false;
98
- // npm excludes prerelease candidates from a range unless the range is
99
- // itself a prerelease of the same major.minor.patch tuple (so `^0.2.0`
100
- // never matches `0.2.1-beta.1`, but `^0.2.1-beta.1` matches 0.2.1-beta.2).
101
- if (parsed.prerelease &&
102
- !(base.prerelease && parsed.major === base.major && parsed.minor === base.minor && parsed.patch === base.patch)) {
103
- return false;
104
- }
105
- if (range.startsWith('^')) {
106
- // npm caret locks the leftmost non-zero component: `^1.2.3` allows
107
- // `<2.0.0`, but `^0.2.3` only `<0.3.0` and `^0.0.3` only `<0.0.4`.
108
- // Locking major alone wrongly resolves `^0.2.0` to a breaking `0.3.0`.
109
- if (parsed.major !== base.major)
110
- return false;
111
- if (base.major === 0) {
112
- if (parsed.minor !== base.minor)
113
- return false;
114
- if (base.minor === 0 && parsed.patch !== base.patch)
115
- return false;
116
- }
117
- return compareSemver(parsed, base) >= 0;
118
- }
119
- return parsed.major === base.major && parsed.minor === base.minor && compareSemver(parsed, base) >= 0;
111
+ return parsed !== null && rangeAdmits(parsed, base, caret);
120
112
  })
121
113
  .sort((left, right) => compareSemver(parseSemver(right), parseSemver(left)));
122
114
  return candidates[0] ?? null;
@@ -140,6 +132,33 @@ function versionExists(versions, entry, version) {
140
132
  // version this entry has.
141
133
  return versions.length === 0 && entry.version === version;
142
134
  }
135
+ /** True when `parsed` satisfies the `^`/`~` range whose base is `base`. */
136
+ function rangeAdmits(parsed, base, caret) {
137
+ // npm excludes prerelease candidates from a range unless the range is
138
+ // itself a prerelease of the same major.minor.patch tuple (so `^0.2.0`
139
+ // never matches `0.2.1-beta.1`, but `^0.2.1-beta.1` matches 0.2.1-beta.2).
140
+ if (parsed.prerelease && !(base.prerelease && sameCore(parsed, base)))
141
+ return false;
142
+ const locked = caret ? caretLocked(parsed, base) : parsed.major === base.major && parsed.minor === base.minor;
143
+ return locked && compareSemver(parsed, base) >= 0;
144
+ }
145
+ /**
146
+ * npm caret locks the leftmost non-zero component: `^1.2.3` allows
147
+ * `<2.0.0`, but `^0.2.3` only `<0.3.0` and `^0.0.3` only `<0.0.4`.
148
+ * Locking major alone wrongly resolves `^0.2.0` to a breaking `0.3.0`.
149
+ */
150
+ function caretLocked(parsed, base) {
151
+ if (parsed.major !== base.major)
152
+ return false;
153
+ if (base.major !== 0)
154
+ return true;
155
+ if (parsed.minor !== base.minor)
156
+ return false;
157
+ return base.minor !== 0 || parsed.patch === base.patch;
158
+ }
159
+ function sameCore(left, right) {
160
+ return left.major === right.major && left.minor === right.minor && left.patch === right.patch;
161
+ }
143
162
  function parseSemver(value) {
144
163
  // Capture an optional `-prerelease`; `+build` metadata is ignored for
145
164
  // precedence (semver §10). The prerelease drives npm's caret/tilde exclusion.
@@ -168,38 +187,28 @@ function compareSemver(left, right) {
168
187
  // numeric ones numerically and ranked below alphanumeric, and a longer set of
169
188
  // identifiers wins when all preceding ones are equal.
170
189
  function comparePrerelease(left, right) {
171
- if (!left && !right)
172
- return 0;
173
- if (!left)
174
- return 1;
175
- if (!right)
176
- return -1;
190
+ // A missing prerelease (a normal release) ranks above any prerelease.
191
+ if (!left || !right)
192
+ return Number(!left) - Number(!right);
177
193
  const a = left.split('.');
178
194
  const b = right.split('.');
179
- for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
180
- const x = a[i];
181
- const y = b[i];
182
- if (x === undefined)
183
- return -1;
184
- if (y === undefined)
185
- return 1;
186
- const xNum = /^\d+$/.test(x);
187
- const yNum = /^\d+$/.test(y);
188
- if (xNum && yNum) {
189
- const d = Number(x) - Number(y);
190
- if (d !== 0)
191
- return d < 0 ? -1 : 1;
192
- }
193
- else if (xNum) {
194
- return -1;
195
- }
196
- else if (yNum) {
197
- return 1;
198
- }
199
- else if (x !== y) {
200
- return x < y ? -1 : 1;
201
- }
195
+ const shared = Math.min(a.length, b.length);
196
+ for (let i = 0; i < shared; i += 1) {
197
+ const order = compareIdentifier(a[i], b[i]);
198
+ if (order !== 0)
199
+ return order;
202
200
  }
203
- return 0;
201
+ return Math.sign(a.length - b.length);
202
+ }
203
+ function compareIdentifier(x, y) {
204
+ const xNum = /^\d+$/.test(x);
205
+ const yNum = /^\d+$/.test(y);
206
+ if (xNum && yNum)
207
+ return Math.sign(Number(x) - Number(y));
208
+ if (xNum !== yNum)
209
+ return xNum ? -1 : 1;
210
+ if (x === y)
211
+ return 0;
212
+ return x < y ? -1 : 1;
204
213
  }
205
214
  //# sourceMappingURL=versioning.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/registry",
3
- "version": "0.5.2",
3
+ "version": "0.6.10",
4
4
  "description": "Pluggable content-registry backends (static, GitHub, database) and semver specifier resolution over @jini-ai/protocol’s registry wire types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -74,13 +74,13 @@
74
74
  "registry": "https://registry.npmjs.org"
75
75
  },
76
76
  "dependencies": {
77
- "@jini-ai/protocol": "^0.4.2",
78
- "@jini-ai/core": "^0.4.2"
77
+ "@jini-ai/protocol": "^0.6.10",
78
+ "@jini-ai/core": "^0.6.10"
79
79
  },
80
80
  "peerDependencies": {
81
81
  "better-sqlite3": "^13.0.0",
82
- "@jini-ai/db": "^0.2.0 || ^0.3.0",
83
- "@jini-ai/platform": "^0.5.1"
82
+ "@jini-ai/db": "^0.6.10",
83
+ "@jini-ai/platform": "^0.6.10"
84
84
  },
85
85
  "peerDependenciesMeta": {
86
86
  "better-sqlite3": {
@@ -96,10 +96,10 @@
96
96
  "devDependencies": {
97
97
  "@types/better-sqlite3": "^7.6.11",
98
98
  "better-sqlite3": "^13.0.0",
99
- "@jini-ai/db": "0.3.1",
100
- "@jini-ai/protocol": "^0.4.2",
101
- "@jini-ai/core": "^0.4.2",
102
- "@jini-ai/platform": "^0.5.2"
99
+ "@jini-ai/db": "0.6.10",
100
+ "@jini-ai/platform": "^0.6.10",
101
+ "@jini-ai/protocol": "^0.6.10",
102
+ "@jini-ai/core": "^0.6.10"
103
103
  },
104
104
  "scripts": {
105
105
  "build": "tsc -p tsconfig.json",