blun-king-cli 9.1.486 → 9.1.489
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 +14 -0
- package/LIESMICH.txt +28 -7
- package/README.md +16 -3
- package/agent-spine-plugin/.claude-plugin/marketplace.json +20 -0
- package/agent-spine-plugin/.claude-plugin/plugin.json +14 -0
- package/agent-spine-plugin/.codex-plugin/plugin.json +34 -0
- package/agent-spine-plugin/.mcp.json +8 -0
- package/agent-spine-plugin/CHANGELOG.md +277 -0
- package/agent-spine-plugin/LICENSE +186 -0
- package/agent-spine-plugin/README.md +342 -0
- package/agent-spine-plugin/assets/agentspine-banner.svg +32 -0
- package/agent-spine-plugin/bin/agentspine-mcp.js +4 -0
- package/agent-spine-plugin/bin/agentspine.js +7 -0
- package/agent-spine-plugin/blun.plugin.json +33 -0
- package/agent-spine-plugin/docs/acceptance.md +61 -0
- package/agent-spine-plugin/docs/architecture.md +183 -0
- package/agent-spine-plugin/docs/attention.md +121 -0
- package/agent-spine-plugin/docs/automatic-continuity.md +79 -0
- package/agent-spine-plugin/docs/channel-runtime.md +92 -0
- package/agent-spine-plugin/docs/coordination.md +138 -0
- package/agent-spine-plugin/docs/feed-transport.md +99 -0
- package/agent-spine-plugin/docs/gateway-runtime.md +109 -0
- package/agent-spine-plugin/docs/harness-reference.md +45 -0
- package/agent-spine-plugin/docs/host-integration.md +129 -0
- package/agent-spine-plugin/docs/https-transport.md +116 -0
- package/agent-spine-plugin/docs/learning.md +98 -0
- package/agent-spine-plugin/docs/object-transport.md +93 -0
- package/agent-spine-plugin/docs/peer-transport.md +88 -0
- package/agent-spine-plugin/docs/preservation-contract.md +53 -0
- package/agent-spine-plugin/docs/quality-gates.md +50 -0
- package/agent-spine-plugin/docs/relationships.md +67 -0
- package/agent-spine-plugin/docs/releasing.md +83 -0
- package/agent-spine-plugin/docs/roadmap.md +307 -0
- package/agent-spine-plugin/docs/selfstarter.md +88 -0
- package/agent-spine-plugin/docs/session-briefing.md +74 -0
- package/agent-spine-plugin/docs/shared-memory.md +259 -0
- package/agent-spine-plugin/docs/source-roots.md +86 -0
- package/agent-spine-plugin/docs/sqlite-transport.md +76 -0
- package/agent-spine-plugin/hooks/hooks.json +95 -0
- package/agent-spine-plugin/hooks/version.json +5 -0
- package/agent-spine-plugin/package.json +69 -0
- package/agent-spine-plugin/scripts/check-hosts.js +193 -0
- package/agent-spine-plugin/scripts/check-install.js +551 -0
- package/agent-spine-plugin/scripts/check-syntax.js +29 -0
- package/agent-spine-plugin/scripts/github-actions.js +11 -0
- package/agent-spine-plugin/scripts/release-check.js +127 -0
- package/agent-spine-plugin/scripts/run-acceptance.js +19 -0
- package/agent-spine-plugin/scripts/run-checks.js +46 -0
- package/agent-spine-plugin/scripts/run-tests-hermetic.js +73 -0
- package/agent-spine-plugin/skill/SKILL.md +76 -0
- package/agent-spine-plugin/skills/agent-spine/SKILL.md +84 -0
- package/agent-spine-plugin/spine-example/1-identity.md +12 -0
- package/agent-spine-plugin/spine-example/2-voice.md +6 -0
- package/agent-spine-plugin/spine-example/3-conduct.md +8 -0
- package/agent-spine-plugin/spine-example/4-history.md +4 -0
- package/agent-spine-plugin/src/cli.js +950 -0
- package/agent-spine-plugin/src/hook.js +646 -0
- package/agent-spine-plugin/src/index.js +84 -0
- package/agent-spine-plugin/src/lib/acceptance.js +294 -0
- package/agent-spine-plugin/src/lib/attention.js +755 -0
- package/agent-spine-plugin/src/lib/audit.js +308 -0
- package/agent-spine-plugin/src/lib/authentication.js +513 -0
- package/agent-spine-plugin/src/lib/briefing.js +305 -0
- package/agent-spine-plugin/src/lib/catalog.js +142 -0
- package/agent-spine-plugin/src/lib/channel-runtime.js +665 -0
- package/agent-spine-plugin/src/lib/context.js +154 -0
- package/agent-spine-plugin/src/lib/continuity.js +333 -0
- package/agent-spine-plugin/src/lib/coordination.js +577 -0
- package/agent-spine-plugin/src/lib/documents.js +199 -0
- package/agent-spine-plugin/src/lib/feed-transport.js +497 -0
- package/agent-spine-plugin/src/lib/filesystem-retry.js +27 -0
- package/agent-spine-plugin/src/lib/gateway-runtime.js +760 -0
- package/agent-spine-plugin/src/lib/graph.js +284 -0
- package/agent-spine-plugin/src/lib/https-transport.js +392 -0
- package/agent-spine-plugin/src/lib/indexed-memory-offline.js +40 -0
- package/agent-spine-plugin/src/lib/indexed-memory.js +281 -0
- package/agent-spine-plugin/src/lib/learning.js +645 -0
- package/agent-spine-plugin/src/lib/object-transport.js +206 -0
- package/agent-spine-plugin/src/lib/paths.js +60 -0
- package/agent-spine-plugin/src/lib/peer-transport.js +283 -0
- package/agent-spine-plugin/src/lib/persona-runtime.js +503 -0
- package/agent-spine-plugin/src/lib/runtime.js +13 -0
- package/agent-spine-plugin/src/lib/selfstarter.js +819 -0
- package/agent-spine-plugin/src/lib/sharing.js +969 -0
- package/agent-spine-plugin/src/lib/source-roots.js +451 -0
- package/agent-spine-plugin/src/lib/sqlite-transport.js +501 -0
- package/agent-spine-plugin/src/lib/telegram-adapter.js +119 -0
- package/agent-spine-plugin/src/lib/voice-runtime.js +39 -0
- package/agent-spine-plugin/src/mcp.js +526 -0
- package/agent-spine-plugin/src/version.js +1 -0
- package/agent-spine-plugin/src/worker.js +178 -0
- package/bin/identity-context-policy.cjs +51 -1
- package/bin/launcher-runtime.js +42 -1
- package/bin/plugin-bootstrap.js +68 -27
- package/bin/repeated-user-message-projection.cjs +6 -0
- package/bin/turn-thinking-policy.cjs +5 -4
- package/bin/turn-tool-performance-policy.cjs +16 -2
- package/blun.mjs +187 -35
- package/package.json +3 -1
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
2
|
+
import { request as httpsRequest } from "node:https";
|
|
3
|
+
import { isIP } from "node:net";
|
|
4
|
+
import {
|
|
5
|
+
buildHttpsSnapshot, fetchHttpsSnapshot, resolveHttpsEndpoint, validateHttpsSnapshot
|
|
6
|
+
} from "./https-transport.js";
|
|
7
|
+
|
|
8
|
+
const CONFIRMATION = "local-share-confirmed";
|
|
9
|
+
const MAX_TOKEN_BYTES = 8192;
|
|
10
|
+
const MAX_RESPONSE_BYTES = 16 * 1024;
|
|
11
|
+
const TOKEN_ENV_RE = /^[A-Z_][A-Z0-9_]{0,127}$/;
|
|
12
|
+
const DIGEST_RE = /^[a-f0-9]{64}$/;
|
|
13
|
+
|
|
14
|
+
function bearerToken(tokenEnv, environment) {
|
|
15
|
+
if (tokenEnv === null || tokenEnv === undefined) return null;
|
|
16
|
+
if (!TOKEN_ENV_RE.test(tokenEnv)) throw new Error("tokenEnv must be an uppercase environment variable name");
|
|
17
|
+
const value = environment[tokenEnv];
|
|
18
|
+
if (typeof value !== "string" || !value) {
|
|
19
|
+
throw new Error(`HTTPS object token environment variable is missing: ${tokenEnv}`);
|
|
20
|
+
}
|
|
21
|
+
if (Buffer.byteLength(value) > MAX_TOKEN_BYTES || /[\0-\x1f\x7f]/.test(value)) {
|
|
22
|
+
throw new Error("HTTPS object bearer token is invalid");
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function timeout(value) {
|
|
28
|
+
if (!Number.isInteger(value) || value < 1000 || value > 30000) {
|
|
29
|
+
throw new Error("HTTPS object timeout must be between 1000 and 30000 milliseconds");
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function within(promise, milliseconds, message) {
|
|
35
|
+
let timer;
|
|
36
|
+
try {
|
|
37
|
+
return await Promise.race([
|
|
38
|
+
promise,
|
|
39
|
+
new Promise((_resolve, reject) => {
|
|
40
|
+
timer = setTimeout(() => reject(new Error(message)), milliseconds);
|
|
41
|
+
})
|
|
42
|
+
]);
|
|
43
|
+
} finally {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function validateHttpsObjectBase(value) {
|
|
49
|
+
let endpoint;
|
|
50
|
+
try {
|
|
51
|
+
endpoint = new URL(value);
|
|
52
|
+
} catch {
|
|
53
|
+
throw new Error("HTTPS object base URL is invalid");
|
|
54
|
+
}
|
|
55
|
+
if (endpoint.protocol !== "https:") throw new Error("HTTPS object publishing requires an https:// URL");
|
|
56
|
+
if (endpoint.username || endpoint.password) {
|
|
57
|
+
throw new Error("credentials must not be embedded in an HTTPS object base URL");
|
|
58
|
+
}
|
|
59
|
+
if (endpoint.search || endpoint.hash) {
|
|
60
|
+
throw new Error("HTTPS object base URLs cannot contain a query or fragment");
|
|
61
|
+
}
|
|
62
|
+
if (!endpoint.hostname || /%(?:2f|5c)/i.test(endpoint.pathname)) {
|
|
63
|
+
throw new Error("HTTPS object base URL contains an ambiguous path");
|
|
64
|
+
}
|
|
65
|
+
endpoint.pathname = endpoint.pathname.replace(/\/+$/, "");
|
|
66
|
+
return endpoint;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function httpsObjectUrl(baseUrl, snapshotDigest) {
|
|
70
|
+
if (!DIGEST_RE.test(snapshotDigest || "")) throw new Error("snapshot digest is invalid");
|
|
71
|
+
const endpoint = validateHttpsObjectBase(baseUrl);
|
|
72
|
+
endpoint.pathname = `${endpoint.pathname}/objects/${snapshotDigest}.json`;
|
|
73
|
+
return endpoint.toString();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function upload({
|
|
77
|
+
url, body, digest, token, timeoutMs, allowPrivateNetwork, lookup, request
|
|
78
|
+
}) {
|
|
79
|
+
const resolved = await within(
|
|
80
|
+
resolveHttpsEndpoint(url, { allowPrivateNetwork, lookup }),
|
|
81
|
+
timeoutMs,
|
|
82
|
+
"HTTPS object DNS resolution timed out"
|
|
83
|
+
);
|
|
84
|
+
const selected = resolved.addresses[0];
|
|
85
|
+
const headers = {
|
|
86
|
+
accept: "application/json",
|
|
87
|
+
"accept-encoding": "identity",
|
|
88
|
+
"content-length": String(body.length),
|
|
89
|
+
"content-type": "application/vnd.agentspine.snapshot+json",
|
|
90
|
+
"if-none-match": "*",
|
|
91
|
+
"user-agent": "AgentSpine/0.1 HTTPS object transport",
|
|
92
|
+
"x-agentspine-digest": `sha256:${digest}`
|
|
93
|
+
};
|
|
94
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
95
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
96
|
+
let deadline;
|
|
97
|
+
let settled = false;
|
|
98
|
+
const reject = (error) => {
|
|
99
|
+
if (settled) return;
|
|
100
|
+
settled = true;
|
|
101
|
+
clearTimeout(deadline);
|
|
102
|
+
rejectPromise(error);
|
|
103
|
+
};
|
|
104
|
+
const resolve = (value) => {
|
|
105
|
+
if (settled) return;
|
|
106
|
+
settled = true;
|
|
107
|
+
clearTimeout(deadline);
|
|
108
|
+
resolvePromise(value);
|
|
109
|
+
};
|
|
110
|
+
const options = {
|
|
111
|
+
protocol: "https:", hostname: resolved.lookupHostname,
|
|
112
|
+
port: resolved.endpoint.port || 443,
|
|
113
|
+
path: resolved.endpoint.pathname, method: "PUT", headers,
|
|
114
|
+
agent: false, autoSelectFamily: false,
|
|
115
|
+
servername: isIP(resolved.lookupHostname) ? undefined : resolved.lookupHostname,
|
|
116
|
+
lookup: (_hostname, lookupOptions, callback) => {
|
|
117
|
+
const family = typeof lookupOptions === "object" && lookupOptions.family
|
|
118
|
+
? Number(lookupOptions.family) : 0;
|
|
119
|
+
const usable = family
|
|
120
|
+
? resolved.addresses.find((item) => item.family === family)
|
|
121
|
+
: selected;
|
|
122
|
+
if (!usable) return callback(new Error("no vetted DNS address matches the requested family"));
|
|
123
|
+
return callback(null, usable.address, usable.family);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const active = request(options, (response) => {
|
|
127
|
+
const status = Number(response.statusCode || 0);
|
|
128
|
+
if (status >= 300 && status < 400 && status !== 412) {
|
|
129
|
+
response.resume();
|
|
130
|
+
reject(new Error("HTTPS object redirects are not followed"));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const chunks = [];
|
|
134
|
+
let bytes = 0;
|
|
135
|
+
response.on("data", (chunk) => {
|
|
136
|
+
bytes += chunk.length;
|
|
137
|
+
if (bytes > MAX_RESPONSE_BYTES) {
|
|
138
|
+
active.destroy(new Error("HTTPS object response exceeds the 16 KiB limit"));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
chunks.push(chunk);
|
|
142
|
+
});
|
|
143
|
+
response.on("end", () => {
|
|
144
|
+
if (![201, 204, 412].includes(status)) {
|
|
145
|
+
reject(new Error(`HTTPS object publish failed with status ${status}`));
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
resolve({ status, responseBytes: bytes });
|
|
149
|
+
});
|
|
150
|
+
response.on("error", reject);
|
|
151
|
+
});
|
|
152
|
+
active.setTimeout(timeoutMs, () => active.destroy(new Error("HTTPS object publish timed out")));
|
|
153
|
+
deadline = setTimeout(() => active.destroy(new Error("HTTPS object publish timed out")), timeoutMs);
|
|
154
|
+
active.on("error", reject);
|
|
155
|
+
active.end(body);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function putHttpsSnapshot({
|
|
160
|
+
baseUrl, snapshot, tokenEnv = null, timeoutMs = 10000,
|
|
161
|
+
allowPrivateNetwork = false, confirmation = null,
|
|
162
|
+
environment = process.env, lookup = dnsLookup, request = httpsRequest
|
|
163
|
+
}) {
|
|
164
|
+
if (confirmation !== CONFIRMATION) {
|
|
165
|
+
throw new Error("HTTPS object publishing requires explicit local owner confirmation");
|
|
166
|
+
}
|
|
167
|
+
timeout(timeoutMs);
|
|
168
|
+
const validated = validateHttpsSnapshot(structuredClone(snapshot));
|
|
169
|
+
const objectUrl = httpsObjectUrl(baseUrl, validated.digest);
|
|
170
|
+
const token = bearerToken(tokenEnv, environment);
|
|
171
|
+
const body = Buffer.from(JSON.stringify(validated));
|
|
172
|
+
const result = await upload({
|
|
173
|
+
url: objectUrl, body, digest: validated.digest, token, timeoutMs,
|
|
174
|
+
allowPrivateNetwork, lookup, request
|
|
175
|
+
});
|
|
176
|
+
const fetched = await fetchHttpsSnapshot({
|
|
177
|
+
url: objectUrl, tokenEnv, timeoutMs, allowPrivateNetwork,
|
|
178
|
+
confirmation, environment, lookup, request
|
|
179
|
+
});
|
|
180
|
+
if (fetched.snapshot.digest !== validated.digest) {
|
|
181
|
+
throw new Error("HTTPS object read-back does not match the published snapshot");
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
created: result.status !== 412,
|
|
185
|
+
alreadyExisted: result.status === 412,
|
|
186
|
+
verified: true,
|
|
187
|
+
objectUrl,
|
|
188
|
+
snapshotId: validated.snapshotId,
|
|
189
|
+
snapshotDigest: validated.digest,
|
|
190
|
+
scopeId: validated.scopeId,
|
|
191
|
+
adapterId: validated.adapterId,
|
|
192
|
+
events: validated.events.length,
|
|
193
|
+
authenticatedWrite: Boolean(token),
|
|
194
|
+
authority: "context-only"
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function publishHttpsSnapshot({
|
|
199
|
+
root = process.cwd(), directory, baseUrl, snapshotId, now = new Date(), ...options
|
|
200
|
+
}) {
|
|
201
|
+
if (options.confirmation !== CONFIRMATION) {
|
|
202
|
+
throw new Error("HTTPS object publishing requires explicit local owner confirmation");
|
|
203
|
+
}
|
|
204
|
+
const snapshot = await buildHttpsSnapshot({ root, directory, snapshotId, now });
|
|
205
|
+
return putHttpsSnapshot({ baseUrl, snapshot, ...options });
|
|
206
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { lstat, mkdir, realpath } from "node:fs/promises";
|
|
5
|
+
|
|
6
|
+
export async function canonicalPath(input = process.cwd()) {
|
|
7
|
+
return realpath(resolve(input));
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export async function findProjectRoot(input = process.cwd()) {
|
|
11
|
+
if (process.env.AGENTSPINE_ROOT) return canonicalPath(process.env.AGENTSPINE_ROOT);
|
|
12
|
+
let cursor = await canonicalPath(input);
|
|
13
|
+
while (true) {
|
|
14
|
+
try {
|
|
15
|
+
await lstat(join(cursor, ".git"));
|
|
16
|
+
return cursor;
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error.code !== "ENOENT") throw error;
|
|
19
|
+
}
|
|
20
|
+
const parent = dirname(cursor);
|
|
21
|
+
if (parent === cursor) return canonicalPath(input);
|
|
22
|
+
cursor = parent;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function isInside(parent, child, pathApi = { relative, isAbsolute, sep }) {
|
|
27
|
+
const value = pathApi.relative(parent, child);
|
|
28
|
+
return value === "" || (!pathApi.isAbsolute(value) && !value.startsWith(`..${pathApi.sep}`) && value !== "..");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function ancestorsBetween(root, cwd) {
|
|
32
|
+
const result = [];
|
|
33
|
+
let cursor = resolve(cwd);
|
|
34
|
+
while (isInside(root, cursor)) {
|
|
35
|
+
result.push(cursor);
|
|
36
|
+
if (cursor === root) break;
|
|
37
|
+
const next = dirname(cursor);
|
|
38
|
+
if (next === cursor) break;
|
|
39
|
+
cursor = next;
|
|
40
|
+
}
|
|
41
|
+
return result.reverse();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function stateRoot(env = process.env) {
|
|
45
|
+
if (env.AGENTSPINE_STATE_DIR) return resolve(env.AGENTSPINE_STATE_DIR);
|
|
46
|
+
if (process.platform === "win32") {
|
|
47
|
+
return join(env.LOCALAPPDATA || env.APPDATA || homedir(), "AgentSpine");
|
|
48
|
+
}
|
|
49
|
+
return join(env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "agentspine");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function projectId(root) {
|
|
53
|
+
return createHash("sha256").update(root).digest("hex").slice(0, 20);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function projectStateDir(root) {
|
|
57
|
+
const target = join(stateRoot(), "projects", projectId(root));
|
|
58
|
+
await mkdir(target, { recursive: true, mode: 0o700 });
|
|
59
|
+
return target;
|
|
60
|
+
}
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { randomBytes, randomUUID, createHash } from "node:crypto";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import {
|
|
4
|
+
assertTrustedIdentity, loadTrust, signEnvelope, verifyEnvelope
|
|
5
|
+
} from "./authentication.js";
|
|
6
|
+
import {
|
|
7
|
+
buildHttpsSnapshot, importHttpsSnapshot, validateHttpsSnapshot
|
|
8
|
+
} from "./https-transport.js";
|
|
9
|
+
|
|
10
|
+
const REQUEST_SCHEMA = "agentspine.peer-request/v1";
|
|
11
|
+
const RESPONSE_SCHEMA = "agentspine.peer-response/v1";
|
|
12
|
+
const CONFIRMATION = "local-share-confirmed";
|
|
13
|
+
const DEFAULT_MAX_BYTES = 22 * 1024 * 1024;
|
|
14
|
+
const MIN_MAX_BYTES = 1024 * 1024;
|
|
15
|
+
const MAX_MAX_BYTES = 22 * 1024 * 1024;
|
|
16
|
+
const MAX_REQUEST_BYTES = 4096;
|
|
17
|
+
const MAX_COMMAND_BYTES = 32768;
|
|
18
|
+
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_.@/-]{0,127}$/;
|
|
19
|
+
const DIGEST_RE = /^[a-f0-9]{64}$/;
|
|
20
|
+
const CHALLENGE_RE = /^[a-f0-9]{64}$/;
|
|
21
|
+
|
|
22
|
+
function canonical(value) {
|
|
23
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
24
|
+
if (value && typeof value === "object") {
|
|
25
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
|
|
26
|
+
}
|
|
27
|
+
return JSON.stringify(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function digest(value) {
|
|
31
|
+
return createHash("sha256").update(canonical(value)).digest("hex");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function exactKeys(value, expected) {
|
|
35
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
36
|
+
const actual = Object.keys(value).sort();
|
|
37
|
+
const wanted = [...expected].sort();
|
|
38
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validDate(value) {
|
|
42
|
+
return typeof value === "string" && Number.isFinite(new Date(value).getTime());
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isoDate(value, field = "date") {
|
|
46
|
+
const parsed = value instanceof Date ? value : new Date(value);
|
|
47
|
+
if (!Number.isFinite(parsed.getTime())) throw new Error(`${field} must be a valid date`);
|
|
48
|
+
return parsed.toISOString();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function byteLimit(value) {
|
|
52
|
+
if (!Number.isInteger(value) || value < MIN_MAX_BYTES || value > MAX_MAX_BYTES) {
|
|
53
|
+
throw new Error("peer maxBytes must be an integer between 1 MiB and 22 MiB");
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function timeout(value) {
|
|
59
|
+
if (!Number.isInteger(value) || value < 1000 || value > 30000) {
|
|
60
|
+
throw new Error("peer timeout must be between 1000 and 30000 milliseconds");
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function createPeerRequest({
|
|
66
|
+
requestId = `request:${randomUUID()}`, challenge = randomBytes(32).toString("hex"),
|
|
67
|
+
maxBytes = DEFAULT_MAX_BYTES
|
|
68
|
+
} = {}) {
|
|
69
|
+
byteLimit(maxBytes);
|
|
70
|
+
if (!ID_RE.test(requestId || "")) throw new Error("peer requestId must be a stable, whitespace-free identifier");
|
|
71
|
+
if (!CHALLENGE_RE.test(challenge || "")) throw new Error("peer challenge must be 32 random bytes encoded as lowercase hex");
|
|
72
|
+
return {
|
|
73
|
+
schema: REQUEST_SCHEMA, requestId, challenge, maxBytes, authority: "context-only"
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function validatePeerRequest(request) {
|
|
78
|
+
if (!exactKeys(request, ["schema", "requestId", "challenge", "maxBytes", "authority"])
|
|
79
|
+
|| request.schema !== REQUEST_SCHEMA || !ID_RE.test(request.requestId || "")
|
|
80
|
+
|| !CHALLENGE_RE.test(request.challenge || "") || request.authority !== "context-only") {
|
|
81
|
+
throw new Error("peer request is invalid");
|
|
82
|
+
}
|
|
83
|
+
byteLimit(request.maxBytes);
|
|
84
|
+
if (Buffer.byteLength(JSON.stringify(request)) > MAX_REQUEST_BYTES) throw new Error("peer request exceeds 4 KiB");
|
|
85
|
+
return request;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function buildPeerResponse({
|
|
89
|
+
root = process.cwd(), directory, signerId, request, now = new Date(),
|
|
90
|
+
snapshotId = `snapshot:peer:${randomUUID()}`
|
|
91
|
+
}) {
|
|
92
|
+
const validatedRequest = validatePeerRequest(structuredClone(request));
|
|
93
|
+
if (!ID_RE.test(signerId || "")) throw new Error("signerId is required for peer responses");
|
|
94
|
+
const snapshot = await buildHttpsSnapshot({ root, directory, snapshotId, now });
|
|
95
|
+
const body = {
|
|
96
|
+
schema: RESPONSE_SCHEMA,
|
|
97
|
+
requestId: validatedRequest.requestId,
|
|
98
|
+
challenge: validatedRequest.challenge,
|
|
99
|
+
snapshot,
|
|
100
|
+
createdAt: isoDate(now, "now"),
|
|
101
|
+
authority: "context-only"
|
|
102
|
+
};
|
|
103
|
+
const payload = { ...body, digest: digest(body) };
|
|
104
|
+
const envelope = await signEnvelope({ root, signerId, kind: "manifest", payload, now });
|
|
105
|
+
const manifest = verifyEnvelope(snapshot.manifest, "manifest");
|
|
106
|
+
if (manifest.publicIdentity.keyId !== envelope.signer.keyId) {
|
|
107
|
+
throw new Error("peer response signer must match the snapshot manifest signer");
|
|
108
|
+
}
|
|
109
|
+
if (Buffer.byteLength(JSON.stringify(envelope)) > validatedRequest.maxBytes) {
|
|
110
|
+
throw new Error("peer response exceeds the request byte limit");
|
|
111
|
+
}
|
|
112
|
+
return envelope;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function validatePeerResponse(envelope, request) {
|
|
116
|
+
const validatedRequest = validatePeerRequest(structuredClone(request));
|
|
117
|
+
const verified = verifyEnvelope(envelope, "manifest");
|
|
118
|
+
const response = verified.payload;
|
|
119
|
+
if (!exactKeys(response, [
|
|
120
|
+
"schema", "requestId", "challenge", "snapshot", "createdAt", "authority", "digest"
|
|
121
|
+
]) || response.schema !== RESPONSE_SCHEMA || response.requestId !== validatedRequest.requestId
|
|
122
|
+
|| response.challenge !== validatedRequest.challenge || !validDate(response.createdAt)
|
|
123
|
+
|| response.authority !== "context-only" || !DIGEST_RE.test(response.digest || "")) {
|
|
124
|
+
throw new Error("peer response does not match the live request");
|
|
125
|
+
}
|
|
126
|
+
const { digest: _digest, ...body } = response;
|
|
127
|
+
if (digest(body) !== response.digest) throw new Error("peer response failed its integrity check");
|
|
128
|
+
const snapshot = validateHttpsSnapshot(structuredClone(response.snapshot));
|
|
129
|
+
const manifest = verifyEnvelope(snapshot.manifest, "manifest");
|
|
130
|
+
if (manifest.publicIdentity.keyId !== verified.publicIdentity.keyId) {
|
|
131
|
+
throw new Error("peer response signer does not match the snapshot manifest signer");
|
|
132
|
+
}
|
|
133
|
+
if (Buffer.byteLength(JSON.stringify(envelope)) > validatedRequest.maxBytes) {
|
|
134
|
+
throw new Error("peer response exceeds the request byte limit");
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
envelope, response, snapshot,
|
|
138
|
+
authentication: verified.authentication,
|
|
139
|
+
publicIdentity: verified.publicIdentity
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function readJsonLine(input, { maxBytes, timeoutMs, label }) {
|
|
144
|
+
let timer;
|
|
145
|
+
const chunks = [];
|
|
146
|
+
let bytes = 0;
|
|
147
|
+
let complete = false;
|
|
148
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
149
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
|
|
150
|
+
});
|
|
151
|
+
const reading = (async () => {
|
|
152
|
+
for await (const chunkValue of input) {
|
|
153
|
+
const chunk = Buffer.isBuffer(chunkValue) ? chunkValue : Buffer.from(chunkValue);
|
|
154
|
+
bytes += chunk.length;
|
|
155
|
+
if (bytes > maxBytes + 1) throw new Error(`${label} exceeds its byte limit`);
|
|
156
|
+
chunks.push(chunk);
|
|
157
|
+
if (chunk.includes(0x0a)) { complete = true; break; }
|
|
158
|
+
}
|
|
159
|
+
if (!complete) throw new Error(`${label} ended before one complete JSON line`);
|
|
160
|
+
const content = Buffer.concat(chunks);
|
|
161
|
+
const newline = content.indexOf(0x0a);
|
|
162
|
+
if (newline > maxBytes) throw new Error(`${label} exceeds its byte limit`);
|
|
163
|
+
if (content.subarray(newline + 1).toString("utf8").trim()) {
|
|
164
|
+
throw new Error(`${label} contains unexpected output after the JSON frame`);
|
|
165
|
+
}
|
|
166
|
+
try { return JSON.parse(content.subarray(0, newline).toString("utf8")); } catch {
|
|
167
|
+
throw new Error(`${label} is not valid JSON`);
|
|
168
|
+
}
|
|
169
|
+
})();
|
|
170
|
+
try { return await Promise.race([reading, deadline]); } finally { clearTimeout(timer); }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function servePeerOnce({
|
|
174
|
+
root = process.cwd(), directory, signerId, input = process.stdin, output = process.stdout,
|
|
175
|
+
confirmation = null, timeoutMs = 10000, now = new Date()
|
|
176
|
+
}) {
|
|
177
|
+
if (confirmation !== CONFIRMATION) throw new Error("peer serving requires explicit local owner confirmation");
|
|
178
|
+
timeout(timeoutMs);
|
|
179
|
+
const request = validatePeerRequest(await readJsonLine(input, {
|
|
180
|
+
maxBytes: MAX_REQUEST_BYTES, timeoutMs, label: "peer request"
|
|
181
|
+
}));
|
|
182
|
+
const envelope = await buildPeerResponse({ root, directory, signerId, request, now });
|
|
183
|
+
const frame = `${JSON.stringify(envelope)}\n`;
|
|
184
|
+
if (Buffer.byteLength(frame) > request.maxBytes + 1) throw new Error("peer response exceeds the request byte limit");
|
|
185
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
186
|
+
output.write(frame, (error) => error ? rejectPromise(error) : resolvePromise());
|
|
187
|
+
});
|
|
188
|
+
return {
|
|
189
|
+
served: true, requestId: request.requestId,
|
|
190
|
+
snapshotId: envelope.payload.snapshot.snapshotId,
|
|
191
|
+
snapshotDigest: envelope.payload.snapshot.digest,
|
|
192
|
+
bytes: Buffer.byteLength(frame) - 1,
|
|
193
|
+
authority: "context-only"
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function parseCommand(commandJson) {
|
|
198
|
+
let command;
|
|
199
|
+
try { command = typeof commandJson === "string" ? JSON.parse(commandJson) : structuredClone(commandJson); } catch {
|
|
200
|
+
throw new Error("peer command must be a JSON array of an executable and arguments");
|
|
201
|
+
}
|
|
202
|
+
if (!Array.isArray(command) || command.length < 1 || command.length > 64
|
|
203
|
+
|| command.some((item) => typeof item !== "string" || !item || item.length > 8192 || item.includes("\0"))
|
|
204
|
+
|| Buffer.byteLength(JSON.stringify(command)) > MAX_COMMAND_BYTES) {
|
|
205
|
+
throw new Error("peer command must contain 1 to 64 bounded strings");
|
|
206
|
+
}
|
|
207
|
+
return command;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function processEnvironment(environment = process.env) {
|
|
211
|
+
const allowed = new Set([
|
|
212
|
+
"PATH", "Path", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "WINDIR",
|
|
213
|
+
"TMP", "TEMP", "TMPDIR", "LANG", "LC_ALL", "SSH_AUTH_SOCK", "SSH_AGENT_PID",
|
|
214
|
+
"AGENTSPINE_STATE_DIR", "XDG_STATE_HOME", "LOCALAPPDATA", "APPDATA"
|
|
215
|
+
]);
|
|
216
|
+
return Object.fromEntries(Object.entries(environment).filter(([key]) => allowed.has(key)));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function exchangeCommand({ command, request, timeoutMs, spawnProcess }) {
|
|
220
|
+
const [executable, ...args] = command;
|
|
221
|
+
const child = spawnProcess(executable, args, {
|
|
222
|
+
shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"],
|
|
223
|
+
env: processEnvironment()
|
|
224
|
+
});
|
|
225
|
+
const processError = new Promise((_resolve, reject) => {
|
|
226
|
+
child.once("error", () => reject(new Error("peer command could not be started")));
|
|
227
|
+
});
|
|
228
|
+
let stderrBytes = 0;
|
|
229
|
+
child.stderr?.on("data", (chunk) => {
|
|
230
|
+
stderrBytes += chunk.length;
|
|
231
|
+
if (stderrBytes > 64 * 1024) child.kill();
|
|
232
|
+
});
|
|
233
|
+
child.stdin.on("error", () => {});
|
|
234
|
+
child.stdin.end(`${JSON.stringify(request)}\n`);
|
|
235
|
+
try {
|
|
236
|
+
return await Promise.race([
|
|
237
|
+
readJsonLine(child.stdout, {
|
|
238
|
+
maxBytes: request.maxBytes, timeoutMs, label: "peer response"
|
|
239
|
+
}),
|
|
240
|
+
processError
|
|
241
|
+
]);
|
|
242
|
+
} finally {
|
|
243
|
+
if (child.exitCode === null && child.signalCode === null) child.kill();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export async function importPeerResponse({
|
|
248
|
+
root = process.cwd(), envelope, request, now = new Date()
|
|
249
|
+
}) {
|
|
250
|
+
const validated = validatePeerResponse(structuredClone(envelope), request);
|
|
251
|
+
const { trust } = await loadTrust(root);
|
|
252
|
+
assertTrustedIdentity(validated.publicIdentity, trust);
|
|
253
|
+
const imported = await importHttpsSnapshot({ root, snapshot: validated.snapshot, now });
|
|
254
|
+
return {
|
|
255
|
+
...imported,
|
|
256
|
+
transport: "peer-stdio",
|
|
257
|
+
requestId: validated.response.requestId,
|
|
258
|
+
snapshotId: validated.snapshot.snapshotId,
|
|
259
|
+
snapshotDigest: validated.snapshot.digest,
|
|
260
|
+
peerSignerId: validated.publicIdentity.signerId,
|
|
261
|
+
peerKeyId: validated.publicIdentity.keyId,
|
|
262
|
+
authority: "context-only"
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export async function pullPeerCommand({
|
|
267
|
+
root = process.cwd(), commandJson, confirmation = null,
|
|
268
|
+
timeoutMs = 10000, maxBytes = DEFAULT_MAX_BYTES,
|
|
269
|
+
now = new Date(), spawnProcess = spawn
|
|
270
|
+
}) {
|
|
271
|
+
if (confirmation !== CONFIRMATION) throw new Error("peer command execution requires explicit local owner confirmation");
|
|
272
|
+
timeout(timeoutMs);
|
|
273
|
+
const command = parseCommand(commandJson);
|
|
274
|
+
const request = createPeerRequest({ maxBytes });
|
|
275
|
+
const envelope = await exchangeCommand({ command, request, timeoutMs, spawnProcess });
|
|
276
|
+
const imported = await importPeerResponse({ root, envelope, request, now });
|
|
277
|
+
return {
|
|
278
|
+
...imported,
|
|
279
|
+
executable: command[0],
|
|
280
|
+
commandArguments: command.length - 1,
|
|
281
|
+
authority: "context-only"
|
|
282
|
+
};
|
|
283
|
+
}
|