@durableintel/nenya 0.0.0-stage → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +392 -2
- package/bin/nenya.cjs +25 -0
- package/bin/nenya.js +72 -0
- package/bin/start.cjs +9 -0
- package/lib/cli.mjs +305 -0
- package/lib/feedenv.mjs +124 -0
- package/lib/filefeed.mjs +40 -0
- package/lib/install.mjs +579 -0
- package/lib/linux.mjs +156 -0
- package/lib/message.mjs +752 -0
- package/lib/release.mjs +120 -0
- package/lib/tools.mjs +227 -0
- package/lib/verify.mjs +146 -0
- package/lib/windows.mjs +395 -0
- package/package.json +25 -4
- package/release-keys.pub +8 -0
package/lib/release.mjs
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// What the release bucket says the current Nenya is, per channel and platform
|
|
2
|
+
// (scripts/release/feeds/build.mjs and feeds.mjs document the layout and formats):
|
|
3
|
+
//
|
|
4
|
+
// macOS <base>/desktop/<channel>/darwin/<arch>/RELEASES.json Squirrel.Mac JSON feed
|
|
5
|
+
// <base>/desktop/<channel>/darwin/<arch>/Nenya-darwin-<arch>-<v>.zip
|
|
6
|
+
// Windows <base>/desktop/<channel>/win32/<arch>/RELEASES Squirrel.Windows lines
|
|
7
|
+
// <base>/desktop/<channel>/win32/<arch>/Nenya-<v>-Setup.exe (collect.mjs: spaces -> "-")
|
|
8
|
+
//
|
|
9
|
+
// and from the bridge release on (spec 15) the same under desktop/v2/<channel>/..., read first
|
|
10
|
+
// (feedPaths). Every file's signature bundle sits beside it as <file>.sigstore.json
|
|
11
|
+
// (scripts/release/README.md, upload step 2). Downloads are built from the configured base URL,
|
|
12
|
+
// the feed root actually read and the file's name, never from a URL the feed carries, so a feed
|
|
13
|
+
// can only name a file in its own directory under the same base.
|
|
14
|
+
|
|
15
|
+
export const PRODUCT_NAME = "Nenya";
|
|
16
|
+
export const CHANNELS = ["alpha", "beta", "stable"];
|
|
17
|
+
export const VERSION_PATTERN =
|
|
18
|
+
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(alpha|beta)\.(0|[1-9]\d*))?$/;
|
|
19
|
+
// Squirrel.Windows ReleaseEntry: "SHA1 filename size", then an optional "# N%" staging comment.
|
|
20
|
+
const RELEASES_LINE = /^([0-9a-fA-F]{40})\s+(\S+)\s+(\d+)\s*$/;
|
|
21
|
+
// electron-winstaller names the package <squirrelId>-<nugetVersion>-full.nupkg, where the NuGet
|
|
22
|
+
// version drops the pre-release dot (0.12.0-alpha.1 -> 0.12.0-alpha1, feeds.mjs nugetVersion).
|
|
23
|
+
const NUPKG = /^(.+)-(\d+\.\d+\.\d+)(?:-(alpha|beta)(\d+))?-full\.nupkg$/;
|
|
24
|
+
|
|
25
|
+
export function parseVersion(version) {
|
|
26
|
+
const match = VERSION_PATTERN.exec(version);
|
|
27
|
+
if (!match) throw new Error(`not a release version: ${version}`);
|
|
28
|
+
const [, major, minor, patch, label, number] = match;
|
|
29
|
+
return {
|
|
30
|
+
core: [major, minor, patch].map(Number),
|
|
31
|
+
pre: label ? { label, number: Number(number) } : null,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// SemVer precedence over the release grammar (as scripts/release/feeds/feeds.mjs compares).
|
|
36
|
+
export function compareVersions(a, b) {
|
|
37
|
+
const x = parseVersion(a);
|
|
38
|
+
const y = parseVersion(b);
|
|
39
|
+
for (let i = 0; i < 3; i++) {
|
|
40
|
+
if (x.core[i] !== y.core[i]) return x.core[i] - y.core[i];
|
|
41
|
+
}
|
|
42
|
+
if (!x.pre || !y.pre) return (y.pre ? 1 : 0) - (x.pre ? 1 : 0);
|
|
43
|
+
if (x.pre.label !== y.pre.label) return x.pre.label < y.pre.label ? -1 : 1;
|
|
44
|
+
return x.pre.number - y.pre.number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The feed directory under the base: the legacy root desktop/<channel>/<platform>/<arch>, or with
|
|
48
|
+
// `v2` the v2 root desktop/v2/<channel>/<platform>/<arch> (spec 15, signing rotation: the v2 feeds
|
|
49
|
+
// carry only Key Vault-signed releases; the legacy feeds freeze at the bridge release, signed with
|
|
50
|
+
// the Cloud KMS key, so an install from before the bridge still reaches it). The CLI reads the
|
|
51
|
+
// desktop feeds; there is no separate CLI feed.
|
|
52
|
+
export function feedPath(channel, platform, arch, { v2 = false } = {}) {
|
|
53
|
+
return `desktop/${v2 ? "v2/" : ""}${channel}/${platform}/${arch}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The feed directories to read, in order: the v2 root first, then the legacy root, which is read
|
|
57
|
+
// only when the v2 root's release list answers 404 (no v2 feed published yet; lib/install.mjs).
|
|
58
|
+
export function feedPaths(channel, platform, arch) {
|
|
59
|
+
return [
|
|
60
|
+
feedPath(channel, platform, arch, { v2: true }),
|
|
61
|
+
feedPath(channel, platform, arch),
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// The macOS release a RELEASES.json names: its currentRelease, the only entry Squirrel.Mac
|
|
66
|
+
// installs. Returns { version, name, size }: the ZIP's file name and its declared size in bytes,
|
|
67
|
+
// which bounds the download.
|
|
68
|
+
export function parseMacFeed(text) {
|
|
69
|
+
let feed;
|
|
70
|
+
try {
|
|
71
|
+
feed = JSON.parse(text);
|
|
72
|
+
} catch {
|
|
73
|
+
throw new Error("RELEASES.json is not JSON");
|
|
74
|
+
}
|
|
75
|
+
const version = feed?.currentRelease;
|
|
76
|
+
if (typeof version !== "string" || !VERSION_PATTERN.test(version)) {
|
|
77
|
+
throw new Error("RELEASES.json names no current release");
|
|
78
|
+
}
|
|
79
|
+
const entry = (feed.releases ?? []).find((r) => r?.version === version);
|
|
80
|
+
const url = entry?.updateTo?.url;
|
|
81
|
+
if (typeof url !== "string") {
|
|
82
|
+
throw new Error(`RELEASES.json has no download for ${version}`);
|
|
83
|
+
}
|
|
84
|
+
const name = decodeURIComponent(new URL(url).pathname.split("/").pop());
|
|
85
|
+
if (!name.endsWith(`-${version}.zip`)) {
|
|
86
|
+
throw new Error(`RELEASES.json names ${name} for ${version}`);
|
|
87
|
+
}
|
|
88
|
+
const size = entry.updateTo.size;
|
|
89
|
+
if (!Number.isSafeInteger(size) || size <= 0) {
|
|
90
|
+
throw new Error(`RELEASES.json gives no size for ${name}`);
|
|
91
|
+
}
|
|
92
|
+
return { version, name, size };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The Windows release a RELEASES file names: the highest full package listed, which is the one
|
|
96
|
+
// Squirrel.Windows installs. Returns { version, squirrelId, installer } where installer is the
|
|
97
|
+
// Setup.exe name collect.mjs gives it and squirrelId the folder Squirrel installs into under
|
|
98
|
+
// %LOCALAPPDATA%.
|
|
99
|
+
export function parseWindowsReleases(text) {
|
|
100
|
+
let best = null;
|
|
101
|
+
for (const raw of text.replace(/^\uFEFF/, "").split("\n")) {
|
|
102
|
+
const line = raw.replace(/\s*#.*$/, "").trim();
|
|
103
|
+
if (line === "") continue;
|
|
104
|
+
const match = RELEASES_LINE.exec(line);
|
|
105
|
+
if (!match) throw new Error(`RELEASES has an unreadable line: ${raw}`);
|
|
106
|
+
const file = NUPKG.exec(match[2]);
|
|
107
|
+
if (!file) continue; // delta packages are not published; anything else is not a release
|
|
108
|
+
const [, squirrelId, core, label, number] = file;
|
|
109
|
+
const version = label ? `${core}-${label}.${number}` : core;
|
|
110
|
+
if (!best || compareVersions(version, best.version) > 0) {
|
|
111
|
+
best = { version, squirrelId };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (!best) throw new Error("RELEASES names no release");
|
|
115
|
+
return { ...best, installer: `${PRODUCT_NAME}-${best.version}-Setup.exe` };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function macZipName(arch, version) {
|
|
119
|
+
return `${PRODUCT_NAME}-darwin-${arch}-${version}.zip`;
|
|
120
|
+
}
|
package/lib/tools.mjs
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// `nenya tools`: the tools Nenya learned from verified work in this repo (agent-loop-1027 CONTRACT C14,
|
|
2
|
+
// AMEND-LEARNING-1028 §4), for any agent that can run a shell command: the shim agents (Goose, Hermes)
|
|
3
|
+
// and anyone else without MCP. It sends one `tools/call` of Nenya's
|
|
4
|
+
// `tools.list`, `tools.describe` or `tools.run` through Edge's local socket, as `nenya message` does
|
|
5
|
+
// (lib/message.mjs), and prints the answer. Edge tells which session runs the command from its
|
|
6
|
+
// process, never from the arguments: a goal's own new tools reach that goal's members only.
|
|
7
|
+
//
|
|
8
|
+
// `nenya tools run` runs the tool in your worktree, under your rules, and exits with the tool's own
|
|
9
|
+
// exit status.
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { parseArgs } from "node:util";
|
|
12
|
+
import {
|
|
13
|
+
SHIM_PROTOCOL_VERSION,
|
|
14
|
+
WSL_INTEROP,
|
|
15
|
+
edgeConnect,
|
|
16
|
+
edgeEndpoint,
|
|
17
|
+
exchange,
|
|
18
|
+
ulid,
|
|
19
|
+
} from "./message.mjs";
|
|
20
|
+
|
|
21
|
+
/** The event of this command's frames on Edge's socket (apps/desktop mcp/server.ts TOOLS_CLI_EVENT). */
|
|
22
|
+
export const TOOLS_CLI_EVENT = "nenya-tools";
|
|
23
|
+
export const TOOL_KINDS = [
|
|
24
|
+
"test_runner",
|
|
25
|
+
"setup",
|
|
26
|
+
"search",
|
|
27
|
+
"verify",
|
|
28
|
+
"helper",
|
|
29
|
+
];
|
|
30
|
+
/** How long list and describe wait for Nenya's answer. */
|
|
31
|
+
export const TOOLS_BUDGET_MS = 20_000;
|
|
32
|
+
/** How long run waits: a learned tool's own limit is at most 30 minutes (Edge stops it then). */
|
|
33
|
+
export const RUN_BUDGET_MS = 31 * 60_000;
|
|
34
|
+
|
|
35
|
+
export const TOOLS_NOT_RUNNING =
|
|
36
|
+
"Nenya isn't running, so its learned tools can't be reached.";
|
|
37
|
+
export const TOOLS_UNANSWERED =
|
|
38
|
+
"Nenya didn't answer in time; the tool may still be running in Nenya.";
|
|
39
|
+
export const TOOLS_ENDED = "Nenya stopped before it answered.";
|
|
40
|
+
const OLD_NENYA =
|
|
41
|
+
"This copy of Nenya doesn't carry learned tools yet: update Nenya, then try again.";
|
|
42
|
+
|
|
43
|
+
export const TOOLS_USAGE = `Usage: nenya tools [list] [--kind KIND] [WORDS…]
|
|
44
|
+
nenya tools describe NAME
|
|
45
|
+
nenya tools run NAME [-- ARGS…]
|
|
46
|
+
|
|
47
|
+
The tools Nenya learned from verified work in this repo: test runners, setup, search, checks and
|
|
48
|
+
helpers, each proven by work that passed here. In a goal, your teammates' new ones too. Prefer one
|
|
49
|
+
to writing your own.
|
|
50
|
+
|
|
51
|
+
Commands
|
|
52
|
+
list The tools for this repo (at most four at a time; narrow by kind or words).
|
|
53
|
+
nenya tools list --kind test_runner
|
|
54
|
+
nenya tools list migration
|
|
55
|
+
describe One tool whole: when it helps, what it runs, and its script if it is one.
|
|
56
|
+
nenya tools describe run-unit
|
|
57
|
+
run Run one in your worktree, under your rules; extra arguments go after --.
|
|
58
|
+
nenya tools run run-unit -- --filter parser
|
|
59
|
+
|
|
60
|
+
Options
|
|
61
|
+
--kind KIND For list: ${TOOL_KINDS.join(", ")}.
|
|
62
|
+
--help Show this help.
|
|
63
|
+
|
|
64
|
+
Exit status: 0 done; for run, the tool's own exit status; 1 when Nenya couldn't answer or didn't
|
|
65
|
+
run it; 2 when the command line was wrong.`;
|
|
66
|
+
|
|
67
|
+
// Why the request never reached Edge, as one line.
|
|
68
|
+
function unreachable(error) {
|
|
69
|
+
const code = error?.code ?? "";
|
|
70
|
+
if (["ENOENT", "ECONNREFUSED", "EDGE_DOWN"].includes(code))
|
|
71
|
+
return TOOLS_NOT_RUNNING;
|
|
72
|
+
if (code === "EDGE_BUSY") return "Nenya stayed busy. Try again.";
|
|
73
|
+
const why = error?.syscall ? code : (error?.message ?? code);
|
|
74
|
+
return `Nenya couldn't be reached${why ? ` (${why})` : ""}.`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// A parseArgs refusal as one line.
|
|
78
|
+
function optionError(error) {
|
|
79
|
+
const named = /'(-[^' ]*)/.exec(error.message)?.[1];
|
|
80
|
+
if (error.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" && named)
|
|
81
|
+
return `'${named}' isn't an option of nenya tools (nenya tools --help lists them).`;
|
|
82
|
+
return `${error.message.split(/\.(?:\s|$)/)[0]}. nenya tools --help lists the options.`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The tool call a command line asks for, or the line that says what is wrong.
|
|
86
|
+
function toolCall(values, positionals, rest) {
|
|
87
|
+
const words = [...positionals];
|
|
88
|
+
const verb = ["list", "describe", "run"].includes(words[0])
|
|
89
|
+
? words.shift()
|
|
90
|
+
: "list";
|
|
91
|
+
if (verb === "list") {
|
|
92
|
+
const kind = values.kind
|
|
93
|
+
?.trim()
|
|
94
|
+
.toLowerCase()
|
|
95
|
+
.replace(/[\s-]+/g, "_");
|
|
96
|
+
if (kind && !TOOL_KINDS.includes(kind))
|
|
97
|
+
return `'${values.kind}' isn't a kind of learned tool: use ${TOOL_KINDS.join(", ")}.`;
|
|
98
|
+
if (rest.length > 0) return "Arguments after -- go with run.";
|
|
99
|
+
const query = words.join(" ").trim();
|
|
100
|
+
return {
|
|
101
|
+
name: "tools.list",
|
|
102
|
+
arguments: { ...(kind ? { kind } : {}), ...(query ? { query } : {}) },
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
if (values.kind !== undefined) return "--kind goes with list.";
|
|
106
|
+
const name = words.shift()?.trim();
|
|
107
|
+
if (!name)
|
|
108
|
+
return `Say which tool: nenya tools ${verb} NAME (nenya tools list shows them).`;
|
|
109
|
+
if (verb === "describe") {
|
|
110
|
+
if (words.length > 0 || rest.length > 0) return "describe takes one name.";
|
|
111
|
+
return { name: "tools.describe", arguments: { name } };
|
|
112
|
+
}
|
|
113
|
+
// run: words before -- are arguments too, as typed
|
|
114
|
+
const args = [...words, ...rest];
|
|
115
|
+
return {
|
|
116
|
+
name: "tools.run",
|
|
117
|
+
arguments: { name, ...(args.length > 0 ? { args } : {}) },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Runs `nenya tools …` (argv without the word `tools`); resolves to the exit status. context:
|
|
123
|
+
* { platform, env, home, cwd, pid, ppid, uid, connect, out, err, budgetMs?, now?, insideWSL? }.
|
|
124
|
+
*/
|
|
125
|
+
export async function toolsMain(argv, context) {
|
|
126
|
+
const { env, out, err } = context;
|
|
127
|
+
const split = argv.indexOf("--");
|
|
128
|
+
const head = split < 0 ? argv : argv.slice(0, split);
|
|
129
|
+
const rest = split < 0 ? [] : argv.slice(split + 1);
|
|
130
|
+
let values;
|
|
131
|
+
let positionals;
|
|
132
|
+
try {
|
|
133
|
+
({ values, positionals } = parseArgs({
|
|
134
|
+
args: head,
|
|
135
|
+
allowPositionals: true,
|
|
136
|
+
options: { kind: { type: "string" }, help: { type: "boolean" } },
|
|
137
|
+
}));
|
|
138
|
+
} catch (error) {
|
|
139
|
+
err(optionError(error));
|
|
140
|
+
return 2;
|
|
141
|
+
}
|
|
142
|
+
if (values.help) {
|
|
143
|
+
out(TOOLS_USAGE);
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
const call = toolCall(values, positionals, rest);
|
|
147
|
+
if (typeof call === "string") {
|
|
148
|
+
err(call);
|
|
149
|
+
return 2;
|
|
150
|
+
}
|
|
151
|
+
const uid = context.uid ?? -1;
|
|
152
|
+
const insideWSL =
|
|
153
|
+
context.insideWSL ??
|
|
154
|
+
(context.platform === "linux" &&
|
|
155
|
+
(Boolean(env.WSL_DISTRO_NAME) ||
|
|
156
|
+
WSL_INTEROP.some((path) => existsSync(path))));
|
|
157
|
+
const endpoint = edgeEndpoint({ ...context, uid, insideWSL });
|
|
158
|
+
const budgetMs =
|
|
159
|
+
context.budgetMs ??
|
|
160
|
+
(call.name === "tools.run" ? RUN_BUDGET_MS : TOOLS_BUDGET_MS);
|
|
161
|
+
const sentAt = (context.now ?? Date.now)();
|
|
162
|
+
const request = {
|
|
163
|
+
v: SHIM_PROTOCOL_VERSION,
|
|
164
|
+
id: ulid(sentAt),
|
|
165
|
+
kind: "mcp",
|
|
166
|
+
assistant: env.NENYA_AGENT?.trim() || "unknown",
|
|
167
|
+
event: TOOLS_CLI_EVENT,
|
|
168
|
+
sent_at_ms: sentAt,
|
|
169
|
+
budget_ms: budgetMs,
|
|
170
|
+
pid: context.pid,
|
|
171
|
+
ppid: context.ppid,
|
|
172
|
+
cwd: context.cwd,
|
|
173
|
+
payload: {
|
|
174
|
+
jsonrpc: "2.0",
|
|
175
|
+
id: 1,
|
|
176
|
+
method: "tools/call",
|
|
177
|
+
params: call,
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
const outcome = await exchange(
|
|
181
|
+
context.connect ?? edgeConnect,
|
|
182
|
+
endpoint,
|
|
183
|
+
request,
|
|
184
|
+
{ budgetMs, env, uid },
|
|
185
|
+
);
|
|
186
|
+
if (outcome.unanswered) {
|
|
187
|
+
err(TOOLS_UNANSWERED);
|
|
188
|
+
return 1;
|
|
189
|
+
}
|
|
190
|
+
if (outcome.ended) {
|
|
191
|
+
err(TOOLS_ENDED);
|
|
192
|
+
return 1;
|
|
193
|
+
}
|
|
194
|
+
if (outcome.failed) {
|
|
195
|
+
err(unreachable(outcome.failed));
|
|
196
|
+
return 1;
|
|
197
|
+
}
|
|
198
|
+
const { answer } = outcome;
|
|
199
|
+
if (answer.error) {
|
|
200
|
+
// an Edge from before `nenya tools` answers its event as no method it knows
|
|
201
|
+
if (answer.error.code === -32601) err(OLD_NENYA);
|
|
202
|
+
else
|
|
203
|
+
err(
|
|
204
|
+
`Nenya couldn't answer${answer.error.message ? `: ${String(answer.error.message).replace(/\.$/, "")}` : ""}.`,
|
|
205
|
+
);
|
|
206
|
+
return 1;
|
|
207
|
+
}
|
|
208
|
+
const text = (answer.result?.content ?? [])
|
|
209
|
+
.filter((item) => item?.type === "text" && typeof item.text === "string")
|
|
210
|
+
.map((item) => item.text.trimEnd())
|
|
211
|
+
.filter(Boolean)
|
|
212
|
+
.join("\n");
|
|
213
|
+
const structured = answer.result?.structuredContent;
|
|
214
|
+
if (call.name === "tools.run" && structured?.ran === true) {
|
|
215
|
+
// the tool ran: its own words and its own exit status, whatever it was
|
|
216
|
+
(structured.exit_code === 0 ? out : err)(text);
|
|
217
|
+
const code = Number(structured.exit_code);
|
|
218
|
+
return Number.isInteger(code) && code >= 0 && code <= 255 ? code : 1;
|
|
219
|
+
}
|
|
220
|
+
if (answer.result?.isError) {
|
|
221
|
+
if (/^Unknown tool: tools\./.test(text)) err(OLD_NENYA);
|
|
222
|
+
else err(text || "Nenya couldn't answer.");
|
|
223
|
+
return 1;
|
|
224
|
+
}
|
|
225
|
+
out(text);
|
|
226
|
+
return 0;
|
|
227
|
+
}
|
package/lib/verify.mjs
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Verifies a release download against the Sigstore bundle `release:sign` publishes beside it
|
|
2
|
+
// (scripts/release/sign/sign.mjs: `cosign sign-blob --key <KMS P-256 key> --bundle <file>.sigstore.json <file>`
|
|
3
|
+
// with a signing config that names no transparency log or timestamp service). cosign 3.1.3
|
|
4
|
+
// writes, for a key-based signature:
|
|
5
|
+
//
|
|
6
|
+
// { "mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json",
|
|
7
|
+
// "verificationMaterial": { "publicKey": { "hint": base64(sha256(public key, SPKI DER)) } },
|
|
8
|
+
// "messageSignature": { "messageDigest": { "algorithm": "SHA2_256", "digest": base64(sha256(file)) },
|
|
9
|
+
// "signature": base64(ECDSA P-256 signature, DER, over sha256(file)) } }
|
|
10
|
+
//
|
|
11
|
+
// Trust is a list of release public keys (spec 15, signing rotation: release-keys.pub holds the
|
|
12
|
+
// Cloud KMS key and its Key Vault successor), and a download is accepted when any listed key
|
|
13
|
+
// verifies it. What is checked, with node:crypto and the listed keys only (no cosign, no network):
|
|
14
|
+
// 1. the bundle is a Sigstore bundle carrying a messageSignature with a SHA2_256 digest;
|
|
15
|
+
// 2. that digest equals the SHA-256 of the bytes that were downloaded;
|
|
16
|
+
// 3. the key hint, when present, names one of the listed keys, and selects it (a hint that names
|
|
17
|
+
// none is refused); with no hint every listed key is a candidate;
|
|
18
|
+
// 4. the ECDSA signature verifies over those bytes with a candidate key.
|
|
19
|
+
// For one key that is what `cosign verify-blob --key cosign.pub --insecure-ignore-tlog --bundle`
|
|
20
|
+
// checks for such a bundle (VERIFY.md): no certificate, log entry or timestamp exists to check.
|
|
21
|
+
import { createHash, createPublicKey, createVerify } from "node:crypto";
|
|
22
|
+
|
|
23
|
+
const BUNDLE_MEDIA_TYPE =
|
|
24
|
+
/^application\/vnd\.dev\.sigstore\.bundle(?:\.v0\.[2-9])?\+json/;
|
|
25
|
+
// One PEM block (RFC 7468): its label, its base64 body, the same label to close it.
|
|
26
|
+
const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+)-----[\s\S]*?-----END \1-----/g;
|
|
27
|
+
|
|
28
|
+
// Each release key is an EC P-256 key (CONTRACTS: Cloud KMS EC_SIGN_P256_SHA256; Key Vault
|
|
29
|
+
// EC-HSM P-256, ES256).
|
|
30
|
+
export function loadPublicKey(pem) {
|
|
31
|
+
const key = createPublicKey(pem);
|
|
32
|
+
const { namedCurve } = key.asymmetricKeyDetails ?? {};
|
|
33
|
+
if (key.asymmetricKeyType !== "ec" || namedCurve !== "prime256v1") {
|
|
34
|
+
throw new Error("the release public key is not an EC P-256 key");
|
|
35
|
+
}
|
|
36
|
+
return key;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The PEM blocks of a key list: a text holding one or more PEM blocks (release-keys.pub, or the
|
|
40
|
+
// file NENYA_RELEASE_PUBLIC_KEY names), or an array of such texts, in order. A text with no PEM
|
|
41
|
+
// block is kept whole, so loadPublicKey refuses it with its own reason.
|
|
42
|
+
export function pemBlocks(pems) {
|
|
43
|
+
return (Array.isArray(pems) ? pems : [pems]).flatMap((text) => {
|
|
44
|
+
if (typeof text !== "string") {
|
|
45
|
+
throw new Error("the release public key is not an EC P-256 key");
|
|
46
|
+
}
|
|
47
|
+
return text.match(PEM_BLOCK) ?? [text];
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Every listed key, each held to the EC P-256 rule; an empty list is refused.
|
|
52
|
+
export function loadPublicKeys(pems) {
|
|
53
|
+
const keys = pemBlocks(pems).map(loadPublicKey);
|
|
54
|
+
if (keys.length === 0) throw new Error("there is no release public key");
|
|
55
|
+
return keys;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// cosign's hint for a raw public key: the SHA-256 of its SPKI DER encoding, base64.
|
|
59
|
+
export function publicKeyHint(key) {
|
|
60
|
+
const der = key.export({ type: "spki", format: "der" });
|
|
61
|
+
return createHash("sha256").update(der).digest("base64");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// A streaming check against the listed keys (`publicKeyPems`, as pemBlocks takes them): feed the
|
|
65
|
+
// downloaded bytes to update(), then finish() with the bundle text. The keys are given up front
|
|
66
|
+
// because each listed key needs its own Verify fed the same bytes as they arrive (a Verify checks
|
|
67
|
+
// one signature with one key, once), so a download is read once whatever the list's length. Both
|
|
68
|
+
// the CLI (bytes as they arrive) and the tests (bytes in memory) use it. A key that isn't an EC
|
|
69
|
+
// P-256 public key throws here, before a byte is read.
|
|
70
|
+
export function createChecker(publicKeyPems) {
|
|
71
|
+
const candidates = loadPublicKeys(publicKeyPems).map((key) => ({
|
|
72
|
+
key,
|
|
73
|
+
hint: publicKeyHint(key),
|
|
74
|
+
verifier: createVerify("SHA256"),
|
|
75
|
+
}));
|
|
76
|
+
const hash = createHash("sha256");
|
|
77
|
+
return {
|
|
78
|
+
update(chunk) {
|
|
79
|
+
hash.update(chunk);
|
|
80
|
+
for (const { verifier } of candidates) verifier.update(chunk);
|
|
81
|
+
},
|
|
82
|
+
// { ok: true, digest } or { ok: false, reason, digest }; digest is the hex SHA-256 of the bytes.
|
|
83
|
+
finish(bundleText) {
|
|
84
|
+
const digest = hash.digest();
|
|
85
|
+
const fail = (reason) => ({
|
|
86
|
+
ok: false,
|
|
87
|
+
reason,
|
|
88
|
+
digest: digest.toString("hex"),
|
|
89
|
+
});
|
|
90
|
+
let bundle;
|
|
91
|
+
try {
|
|
92
|
+
bundle = JSON.parse(bundleText);
|
|
93
|
+
} catch {
|
|
94
|
+
return fail("the signature file is not a Sigstore bundle");
|
|
95
|
+
}
|
|
96
|
+
if (
|
|
97
|
+
typeof bundle?.mediaType !== "string" ||
|
|
98
|
+
!BUNDLE_MEDIA_TYPE.test(bundle.mediaType)
|
|
99
|
+
) {
|
|
100
|
+
return fail("the signature file is not a Sigstore bundle");
|
|
101
|
+
}
|
|
102
|
+
const message = bundle.messageSignature;
|
|
103
|
+
const signed = message?.messageDigest;
|
|
104
|
+
if (
|
|
105
|
+
signed?.algorithm !== "SHA2_256" ||
|
|
106
|
+
typeof signed.digest !== "string"
|
|
107
|
+
) {
|
|
108
|
+
return fail("the bundle carries no SHA-256 message signature");
|
|
109
|
+
}
|
|
110
|
+
if (!Buffer.from(signed.digest, "base64").equals(digest)) {
|
|
111
|
+
return fail("the download's SHA-256 is not the one that was signed");
|
|
112
|
+
}
|
|
113
|
+
// The hint, when there is one, picks the listed key(s) it names; with none, every key is tried.
|
|
114
|
+
const hint = bundle.verificationMaterial?.publicKey?.hint;
|
|
115
|
+
const tried =
|
|
116
|
+
hint === undefined
|
|
117
|
+
? candidates
|
|
118
|
+
: candidates.filter((candidate) => candidate.hint === hint);
|
|
119
|
+
if (tried.length === 0) {
|
|
120
|
+
return fail(
|
|
121
|
+
"the bundle was signed with a key other than the release keys",
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
if (typeof message.signature !== "string") {
|
|
125
|
+
return fail("the bundle carries no signature");
|
|
126
|
+
}
|
|
127
|
+
const signature = Buffer.from(message.signature, "base64");
|
|
128
|
+
const verified = tried.some(({ key, verifier }) => {
|
|
129
|
+
try {
|
|
130
|
+
return verifier.verify(key, signature);
|
|
131
|
+
} catch {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
return verified
|
|
136
|
+
? { ok: true, digest: digest.toString("hex") }
|
|
137
|
+
: fail("the signature does not verify with the release keys");
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function verifyBytes(bytes, bundleText, publicKeyPems) {
|
|
143
|
+
const checker = createChecker(publicKeyPems);
|
|
144
|
+
checker.update(bytes);
|
|
145
|
+
return checker.finish(bundleText);
|
|
146
|
+
}
|