@quolu/lattice 0.114.4 → 0.116.0
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/bin/lattice.mjs +22 -3
- package/package.json +1 -1
- package/src/chart-cli.mjs +50 -7
- package/src/cli-help.mjs +6 -3
- package/src/runtime-error-reporting.mjs +119 -105
- package/src/runtime-errors.mjs +37 -9
- package/src/todo-cli.mjs +87 -15
- package/src/todo-external.mjs +6 -1
- package/src/todo-gantt-html-shared.mjs +3 -2
- package/src/todo-note-store.mjs +195 -113
- package/src/todo-readiness.mjs +4 -8
- package/src/todo-store-view.mjs +47 -13
- package/src/todo-store.mjs +172 -3
- package/src/todo-waiters.mjs +62 -0
package/bin/lattice.mjs
CHANGED
|
@@ -344,10 +344,27 @@ function workingDirectory() {
|
|
|
344
344
|
}
|
|
345
345
|
}
|
|
346
346
|
|
|
347
|
+
// `enable`の署名者の指定: `--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <署名者argv...>`。key-idとargvは対で、
|
|
348
|
+
// どちらも無ければ今の署名者を引き継ぐ。形の違いは null(usage)。
|
|
349
|
+
function reportingChange(flags) {
|
|
350
|
+
const dash = flags.indexOf('--');
|
|
351
|
+
const head = dash < 0 ? flags : flags.slice(0, dash);
|
|
352
|
+
const command = dash < 0 ? [] : flags.slice(dash + 1);
|
|
353
|
+
const values = {};
|
|
354
|
+
for (let index = 0; index < head.length; index += 2) {
|
|
355
|
+
if (head[index + 1] === undefined || !['--key-id', '--signer-cwd', '--url'].includes(head[index])) return null;
|
|
356
|
+
values[head[index]] = head[index + 1];
|
|
357
|
+
}
|
|
358
|
+
if ((values['--key-id'] === undefined) !== (command.length === 0)) return null;
|
|
359
|
+
if (values['--key-id'] === undefined && values['--signer-cwd'] !== undefined) return null;
|
|
360
|
+
return { ...(values['--key-id'] !== undefined && { signer: { key_id: values['--key-id'], command, cwd: values['--signer-cwd'] ?? null } }),
|
|
361
|
+
...(values['--url'] !== undefined && { url: values['--url'] }) };
|
|
362
|
+
}
|
|
363
|
+
|
|
347
364
|
async function runRuntimeErrorsCli(rest) {
|
|
348
365
|
const runtimeErrors = await import('../src/runtime-errors.mjs');
|
|
349
366
|
const usage = () => {
|
|
350
|
-
process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: 'usage: lattice runtime-errors <snapshot [--after-cursor N] [--limit N]|ack <cursor>|diagnostics|resolve <fingerprint>|reopen <fingerprint>|compact|report|reporting <status|enable|disable|verify>> --json' })}\n`);
|
|
367
|
+
process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: 'usage: lattice runtime-errors <snapshot [--after-cursor N] [--limit N]|ack <cursor>|diagnostics|resolve <fingerprint>|reopen <fingerprint>|compact|report|reporting <status|enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <signer argv...>]|disable|verify>> --json' })}\n`);
|
|
351
368
|
return 2;
|
|
352
369
|
};
|
|
353
370
|
const options = { version: packageJson.version };
|
|
@@ -382,10 +399,12 @@ async function runRuntimeErrorsCli(rest) {
|
|
|
382
399
|
result = await reporting.verifyRuntimeErrorReporting(options);
|
|
383
400
|
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
384
401
|
return result.outcome === 'verified' ? 0 : 1;
|
|
385
|
-
} else if (words[0] === 'reporting' && words.length === 2 && ['status', '
|
|
402
|
+
} else if (words[0] === 'reporting' && (words[1] === 'enable' || (words.length === 2 && ['status', 'disable'].includes(words[1])))) {
|
|
386
403
|
const reporting = await import('../src/runtime-error-reporting.mjs');
|
|
404
|
+
const change = words[1] === 'enable' ? reportingChange(words.slice(2)) : {};
|
|
405
|
+
if (change === null) return usage();
|
|
387
406
|
result = words[1] === 'status' ? reporting.runtimeErrorReportingStatus(options)
|
|
388
|
-
: reporting.setRuntimeErrorReporting(words[1] === 'enable', options);
|
|
407
|
+
: reporting.setRuntimeErrorReporting(words[1] === 'enable', options, change);
|
|
389
408
|
} else if (words[0] === 'report' && (words.length === 1 || (words.length === 2 && words[1] === '--auto'))) {
|
|
390
409
|
// 送れなかった時も結果は1行で返す。受領まで済んだ時と、送るものが無い時だけexit 0。
|
|
391
410
|
const reporting = await import('../src/runtime-error-reporting.mjs');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.116.0",
|
|
4
4
|
"description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Quo / クオ at kitepon.dev",
|
package/src/chart-cli.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { parseFlagMap } from './todo-authoring-input.mjs';
|
|
|
12
12
|
import { isTodoIdentifier } from './todo-contracts.mjs';
|
|
13
13
|
import { TODO_CHARTS_ROOT_ENV } from './todo-external.mjs';
|
|
14
14
|
import {
|
|
15
|
-
readTodoChartMeta, readTodoStoreDisplaySource, TodoStoreError, writeTodoChartMeta,
|
|
15
|
+
readTodoChartMeta, readTodoOutgoingConnections, readTodoStoreDisplaySource, TodoStoreError, writeTodoChartMeta,
|
|
16
16
|
} from './todo-store.mjs';
|
|
17
17
|
|
|
18
18
|
export const PROJECT_ID_ENV = 'LATTICE_PROJECT_ID';
|
|
@@ -106,11 +106,52 @@ async function readChart(root, id) {
|
|
|
106
106
|
try { display = await readTodoStoreDisplaySource({ repoRoot: dir }); } catch (error) {
|
|
107
107
|
findings.push({ project_id: id, reason: reasonOf(error) });
|
|
108
108
|
}
|
|
109
|
-
return { meta, findings,
|
|
109
|
+
return { meta, findings, display };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The change token of one chart: its display source, its meta, and (n2) the 接続 links that cross its border. */
|
|
113
|
+
const chartToken = ({ meta, display }, links = []) => (meta === null || display === null ? null
|
|
114
|
+
: digest(links.length === 0 ? [display, meta] : [display, meta, links]));
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* n2: the cross-chart 接続 each chart's token also digests, so a host that pulls tokens sees at that moment what it
|
|
118
|
+
* must re-read: `out` = a live 接続 of this chart to a task elsewhere, with that task's plan as its chart shows it
|
|
119
|
+
* (moves when the target is done, retired, reopened, revised or gone); `in` = a 接続 of another chart onto this
|
|
120
|
+
* chart (moves when a waiter appears or goes). Charts with no plan-scoped chain cost no read; the others one cheap
|
|
121
|
+
* Store read. shortcut: the target is digested per plan, not per task (one extra re-read on a sibling's change);
|
|
122
|
+
* upgrade to the task's own last event if a sweep measures it.
|
|
123
|
+
*/
|
|
124
|
+
async function chartLinks(root, observed) {
|
|
125
|
+
const links = new Map([...observed.keys()].map((id) => [id, []]));
|
|
126
|
+
const planOf = (project, planKey) => {
|
|
127
|
+
const member = observed.get(project)?.display?.members?.find((entry) => entry.plan_key === planKey);
|
|
128
|
+
return member === undefined ? null : [member.active_plan_version, member.plan_digest, member.lifecycle_head, member.topology_digest];
|
|
129
|
+
};
|
|
130
|
+
for (const [id, chart] of observed) {
|
|
131
|
+
if (!(chart.display?.members ?? []).some((member) => member.plan_scoped_head !== null)) continue;
|
|
132
|
+
let outgoing;
|
|
133
|
+
try { outgoing = await readTodoOutgoingConnections({ repoRoot: path.join(root, id) }); } catch (error) {
|
|
134
|
+
chart.findings.push({ project_id: id, reason: reasonOf(error) });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
for (const edge of outgoing.edges) {
|
|
138
|
+
links.get(id).push(['out', edge.event_digest, edge.from.project_id, edge.from.plan_key, edge.from.task_id,
|
|
139
|
+
planOf(edge.from.project_id, edge.from.plan_key)]);
|
|
140
|
+
links.get(edge.from.project_id)?.push(['in', edge.event_digest, id, edge.to.plan_key, edge.to.task_id]);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
for (const list of links.values()) list.sort((left, right) => (JSON.stringify(left) < JSON.stringify(right) ? -1 : 1));
|
|
144
|
+
return links;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function observeCharts(root, ids) {
|
|
148
|
+
const observed = new Map();
|
|
149
|
+
for (const id of ids) observed.set(id, await readChart(root, id));
|
|
150
|
+
return { observed, links: await chartLinks(root, observed) };
|
|
110
151
|
}
|
|
111
152
|
|
|
112
153
|
/** Direct children of the root that hold a Store manifest, sorted; a missing root has none. */
|
|
113
|
-
async function chartIds(root) {
|
|
154
|
+
export async function chartIds(root) {
|
|
114
155
|
let entries;
|
|
115
156
|
try { entries = await readdir(root, { withFileTypes: true }); } catch (error) {
|
|
116
157
|
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return [];
|
|
@@ -137,11 +178,11 @@ export async function listCharts(env) {
|
|
|
137
178
|
}
|
|
138
179
|
const charts = [];
|
|
139
180
|
const findings = [];
|
|
140
|
-
|
|
141
|
-
|
|
181
|
+
const { observed, links } = await observeCharts(root, await chartIds(root));
|
|
182
|
+
for (const [id, chart] of observed) {
|
|
142
183
|
findings.push(...chart.findings);
|
|
143
184
|
charts.push({ project_id: id, name: chart.meta?.name ?? null, created_by: chart.meta?.created_by ?? null,
|
|
144
|
-
created_at: chart.meta?.created_at ?? null, source: chart.
|
|
185
|
+
created_at: chart.meta?.created_at ?? null, source: chartToken(chart, links.get(id)) });
|
|
145
186
|
}
|
|
146
187
|
return { schema: 'lattice.charts_list_result.v1', charts_root: root, charts, findings };
|
|
147
188
|
}
|
|
@@ -151,9 +192,11 @@ export async function chartSources(env, ids) {
|
|
|
151
192
|
const root = chartsRoot(env);
|
|
152
193
|
const chosen = ids.length > 0 ? ids : root === null ? [] : await chartIds(root);
|
|
153
194
|
const charts = {};
|
|
195
|
+
// A chart's token also digests links from other charts, so every chart is observed once, then the chosen ones are answered.
|
|
196
|
+
const { observed, links } = root === null ? { observed: new Map(), links: new Map() } : await observeCharts(root, await chartIds(root));
|
|
154
197
|
for (const id of chosen) {
|
|
155
198
|
const present = root !== null && isChartId(id) && await lstatOrNull(path.join(root, id, MANIFEST)) !== null;
|
|
156
|
-
charts[id] = present
|
|
199
|
+
charts[id] = present && observed.has(id) ? chartToken(observed.get(id), links.get(id)) : null;
|
|
157
200
|
}
|
|
158
201
|
return { schema: 'lattice.charts_source_result.v1', charts };
|
|
159
202
|
}
|
package/src/cli-help.mjs
CHANGED
|
@@ -95,6 +95,7 @@ Read commands:
|
|
|
95
95
|
note list --plan <key> [--task <id>] --json # note全履歴の診断面(通常read/startでは不要)
|
|
96
96
|
notice list [--lane <lane>] [--include-acked] [--json] # 着手できるようになった工程の知らせ(既定は未ackだけ。lane省略で全lane)
|
|
97
97
|
blockers [--json] # ブロック中の工程を全部返す(題・担当・理由の全文・ブロックした時刻と者・外すコマンド。読むだけ。外すのは誰でも todo unblock)
|
|
98
|
+
waiters [--plan <key>] [--task <id>] [--open] [--json] # 他の工程表から接続でこの工程表の工程を待っている工程の一覧(読むだけ。--open は今も待っているものだけ。LATTICE_CHARTS_ROOT 配下の他の工程表を読む)
|
|
98
99
|
bindings [--plan <key>] [--json] # compile_binding付きTaskをTODO identityつきで投影する
|
|
99
100
|
display read [--json] [--compact] [--open] # host表示用の工程表読取(lattice.todo_display_read_result.v1)。不整合でも断らずstateで返す。--compact は journal を activity、plan_scoped を cross_plan_dependencies に絞った lattice.todo_display_compact_result.v1(大きさは task と生きた線に比例)。--open は --compact を含み、task ごとの一覧を開いた木の task だけに絞って closed {trees, tasks} を足す lattice.todo_display_open_result.v2(member の revision と、検証済み member の snapshot を持たない。next_ready は state が verified の時だけ todo status と同じ一覧、他は null)
|
|
100
101
|
display history [--json] [--limit <n>] [--before <cursor>] # 閉じた木の task を終了の新しい順に1ページ返す(lattice.todo_display_history_result.v1。limit 既定50・最大500、next_cursor を --before へ渡して次頁)
|
|
@@ -268,8 +269,9 @@ Commands:
|
|
|
268
269
|
reopen <fingerprint>
|
|
269
270
|
compact
|
|
270
271
|
report 未受領の記録をBugHubの受け口へ送る(送信を有効にした端末だけ)
|
|
271
|
-
reporting <status|
|
|
272
|
-
reporting
|
|
272
|
+
reporting <status|disable>
|
|
273
|
+
reporting enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <署名者argv...>] 送信を有効にする(署名者はBugHub-ES256の署名を返すcommand)
|
|
274
|
+
reporting verify 空の報告を1通送り、署名者と受け口までの経路を確かめる(記録には触れない)
|
|
273
275
|
`,
|
|
274
276
|
bridge: `Usage: lattice bridge <command> [options] --json
|
|
275
277
|
|
|
@@ -345,6 +347,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
345
347
|
'todo notice list': 'todo notice list [--lane <lane>] [--include-acked] [--json] # lattice.todo_notice_list_result.v1',
|
|
346
348
|
'todo notice ack': 'todo notice ack --lane <lane> --notice <id>[,<id>...] [--json] # lattice.todo_notice_ack_result.v1 {acked, already, closed}',
|
|
347
349
|
'todo compact': 'todo compact [--plan <key>] [--limit <n>] [--json] # lattice.todo_compact_result.v1 {plans: [{plan_key, compacted, stopped, next_version}]}',
|
|
350
|
+
'todo waiters': 'todo waiters [--plan <key>] [--task <id>] [--open] [--json] # lattice.todo_waiters_result.v1 {tasks: [{plan_key, task_id, waiters: [{project_id, plan_key, task_id, kind, state, state_reason, reason, since, event_digest}]}], unread: [{project_id, reason}]}; project/plan/task name the WAITING task',
|
|
348
351
|
'todo blockers': 'todo blockers [--json] # lattice.todo_blockers_result.v1 {blockers: [{plan_key, task_id, title, lane, reason, blocked_at, blocked_by, unblock_action}]}',
|
|
349
352
|
'todo wait': 'todo wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # 廃止予定の別名: todo connect priority',
|
|
350
353
|
'todo bindings': 'todo bindings [--plan <key>] [--json]',
|
|
@@ -447,7 +450,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
447
450
|
'runtime-errors reopen': 'runtime-errors reopen <fingerprint> --json',
|
|
448
451
|
'runtime-errors compact': 'runtime-errors compact --json',
|
|
449
452
|
'runtime-errors report': 'runtime-errors report --json',
|
|
450
|
-
'runtime-errors reporting': 'runtime-errors reporting <status|enable|disable|verify> --json',
|
|
453
|
+
'runtime-errors reporting': 'runtime-errors reporting <status|enable [--key-id <id> [--signer-cwd <dir>] [--url <url>] -- <signer argv...>]|disable|verify> --json',
|
|
451
454
|
'bridge setup': 'bridge setup --listen <IP> [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--hub <URL>|none] [--allow-host <host>...] --json',
|
|
452
455
|
'bridge reconfigure': 'bridge reconfigure [--listen <IP>] [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--hub <URL>|none] [--allow-host <host>...] --json',
|
|
453
456
|
'bridge status': 'bridge status --json',
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { createHash,
|
|
1
|
+
import { createHash, createPublicKey, randomBytes, randomUUID, verify } from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
2
3
|
import {
|
|
3
|
-
existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync,
|
|
4
|
+
closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync,
|
|
4
5
|
} from 'node:fs';
|
|
5
6
|
import http from 'node:http';
|
|
6
7
|
import https from 'node:https';
|
|
7
|
-
import { homedir, platform as hostPlatform } from 'node:os';
|
|
8
8
|
import { dirname, join } from 'node:path';
|
|
9
9
|
|
|
10
10
|
import {
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
acknowledgeRuntimeErrors,
|
|
13
13
|
ensureSafeDir,
|
|
14
14
|
ensureSafeFile,
|
|
15
|
+
readRuntimeErrorReportingConfig,
|
|
15
16
|
replaceStoreFile,
|
|
16
17
|
runtimeErrorCollectionSupported,
|
|
17
18
|
runtimeErrorReportingConfigPath,
|
|
@@ -19,19 +20,22 @@ import {
|
|
|
19
20
|
runtimeErrorsDiagnostics,
|
|
20
21
|
runtimeErrorsSnapshot,
|
|
21
22
|
runtimeErrorsStatePath,
|
|
22
|
-
|
|
23
|
+
validReportingSigner,
|
|
24
|
+
validReportingUrl,
|
|
23
25
|
} from './runtime-errors.mjs';
|
|
24
26
|
|
|
25
27
|
/**
|
|
26
|
-
* runtime error記録を、Lattice自身がBugHubの製品報告の受け口へ送る(ADR 0193)。
|
|
28
|
+
* runtime error記録を、Lattice自身がBugHubの製品報告の受け口へ送る(ADR 0193・0197)。
|
|
27
29
|
*
|
|
28
|
-
* - 既定では通信しない。端末で`runtime-errors reporting enable
|
|
29
|
-
*
|
|
30
|
-
* -
|
|
31
|
-
* -
|
|
32
|
-
*
|
|
30
|
+
* - 既定では通信しない。端末で`runtime-errors reporting enable`を打ち、署名者(`--key-id`と署名commandの
|
|
31
|
+
* argv)を設定した端末だけが送る。どちらかが欠ければ、networkへ触れない。
|
|
32
|
+
* - 秘密は端末に無い。署名の鍵は認証仲介の中だけにある。Latticeは「ts + LF + 本文SHA-256のhex」を
|
|
33
|
+
* 署名者commandへ渡し、返る生r‖s(ES256)を`Authorization: BugHub-ES256`に付ける。
|
|
34
|
+
* - 受領済みにするのは、200・`accepted: true`・`report_id`一致・応答のES256署名がBugHubの応答用公開鍵で
|
|
35
|
+
* 合うことがそろった時だけ。そろわなければ「届いたか不明」として記録を未受領のまま残し、後から今の累計を送り直す。
|
|
36
|
+
* - 署名できなければ送らない。記録は残り、届かなかった送信と同じく後から送り直す。
|
|
33
37
|
* - 送るのは`runtime-errors snapshot`が出す項目だけ。message本文・path・引数・stackは記録に無い。
|
|
34
|
-
* - `reporting verify`は、記録を載せない空の報告を1
|
|
38
|
+
* - `reporting verify`は、記録を載せない空の報告を1通送って、署名者・署名・受け口までの経路を確かめる。
|
|
35
39
|
* 受け口は受領を記録するだけで、issueも通知も動かない。storeの記録と受領の印には触れない。
|
|
36
40
|
*/
|
|
37
41
|
|
|
@@ -40,6 +44,16 @@ const RESULT_SCHEMA = 'lattice.runtime_error_report_result.v1';
|
|
|
40
44
|
const STATUS_SCHEMA = 'lattice.runtime_error_reporting_status.v1';
|
|
41
45
|
const DELIVERY_SCHEMA = 'lattice.runtime_error_delivery.v1';
|
|
42
46
|
const PRODUCT_ID = 'lattice';
|
|
47
|
+
// BugHubの製品報告の受け口(LAN内。製品共通の1本)。設定の`url`で差し替えられる。
|
|
48
|
+
const DEFAULT_INTAKE_URL = 'http://192.168.1.2:39310/api/products/v1/runtime-errors';
|
|
49
|
+
// BugHubの応答用公開鍵(ES256)。BugHubの応答署名はこの鍵でだけ確かめる。鍵が替わる時は新版を出す。
|
|
50
|
+
const BUGHUB_RESPONSE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
51
|
+
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEX+kilvDhn190l4Z+iR5J4KusmOSJ
|
|
52
|
+
ZVBQjMaLGOshDFzUwB7IxiJsgLMpQzOdoEWM21DCBpL1QyY1COU2cmuE1g==
|
|
53
|
+
-----END PUBLIC KEY-----
|
|
54
|
+
`;
|
|
55
|
+
const SIGNER_TIMEOUT_MS = 30_000;
|
|
56
|
+
const SIGNER_OUTPUT_MAX_BYTES = 1024;
|
|
43
57
|
const REQUEST_TIMEOUT_MS = 10_000;
|
|
44
58
|
const RESPONSE_MAX_BYTES = 64 * 1024;
|
|
45
59
|
const REPORT_MAX_BYTES = 512 * 1024;
|
|
@@ -47,95 +61,85 @@ const REPORT_MAX_RECORDS = 256;
|
|
|
47
61
|
// BugHubは端末×製品ごとに1分に1回まで受ける。届かなかった同じ中身の送り直しは1時間に1回まで。
|
|
48
62
|
const MIN_ATTEMPT_INTERVAL_MS = 60_000;
|
|
49
63
|
const RETRY_INTERVAL_MS = 60 * 60_000;
|
|
50
|
-
const KEY_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
51
64
|
const REJECTION_CODE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
52
|
-
const OUTCOMES = Object.freeze(['delivered', 'nothing_pending', 'disabled', 'unsupported', '
|
|
53
|
-
'
|
|
65
|
+
const OUTCOMES = Object.freeze(['delivered', 'nothing_pending', 'disabled', 'unsupported', 'signer_missing',
|
|
66
|
+
'signer_refused', 'signer_failed', 'throttled', 'rejected', 'unconfirmed', 'store_unavailable']);
|
|
54
67
|
|
|
55
68
|
const plain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
56
69
|
const exact = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
57
70
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
71
|
+
const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
72
|
+
|
|
73
|
+
/** 署名者へ渡す文字列: `ts + "\n" + SHA-256(送るバイト列)の16進`。末尾に改行は付けない。 */
|
|
74
|
+
export function reportSigningText(ts, bodyBytes) {
|
|
75
|
+
return `${ts}\n${sha256Hex(bodyBytes)}`;
|
|
62
76
|
}
|
|
63
77
|
|
|
64
|
-
/**
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
78
|
+
/** 生r‖s(64バイト)か、そのbase64(パディングあり)を、64バイトへ直す。 */
|
|
79
|
+
function signatureBytes(output) {
|
|
80
|
+
if (output.length === 64) return output;
|
|
81
|
+
const text = output.toString('utf8').trim();
|
|
82
|
+
return /^[A-Za-z0-9+/]{86}==$/.test(text) ? Buffer.from(text, 'base64') : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 応答の署名: BugHubの応答用公開鍵で`report_id + "\n" + received_at`へのES256署名を確かめる。別の機器が返した200を受領済みにしない。 */
|
|
86
|
+
export function receiptSignatureValid(publicKeyPem, reportId, receivedAt, sig) {
|
|
87
|
+
if (typeof receivedAt !== 'string' || typeof sig !== 'string' || !/^[A-Za-z0-9+/]{86}==$/.test(sig)) return false;
|
|
70
88
|
try {
|
|
71
|
-
|
|
89
|
+
return verify('sha256', Buffer.from(`${reportId}\n${receivedAt}`, 'utf8'),
|
|
90
|
+
{ key: createPublicKey(publicKeyPem), dsaEncoding: 'ieee-p1363' }, Buffer.from(sig, 'base64'));
|
|
72
91
|
} catch {
|
|
73
|
-
return
|
|
74
|
-
}
|
|
75
|
-
try {
|
|
76
|
-
ensureSafeFile(path, storeDir);
|
|
77
|
-
return null;
|
|
78
|
-
} catch {
|
|
79
|
-
return 'acl_not_owner_only';
|
|
92
|
+
return false;
|
|
80
93
|
}
|
|
81
94
|
}
|
|
82
95
|
|
|
83
96
|
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
97
|
+
* 署名者commandを走らせて署名を得る。入力は、storeの(本人だけの)folderに置いたfileから標準入力へ渡す
|
|
98
|
+
* ——pipeでは、Windowsのsshが固まる。入力fileは必ず消す。exit 1は断られた、それ以外・時間切れ・起動できない
|
|
99
|
+
* ・形の違う出力は失敗。結果に署名者の出力は載せない。
|
|
86
100
|
*/
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
} catch (error) {
|
|
93
|
-
return error?.code === 'ENOENT' ? { status: 'missing' } : { status: 'unsafe', reason: 'unreadable' };
|
|
94
|
-
}
|
|
95
|
-
if (!stats.isFile() || stats.isSymbolicLink()) return { status: 'unsafe', reason: 'not_regular_file' };
|
|
96
|
-
if (hostPlatform() === 'win32') {
|
|
97
|
-
const reason = windowsCredentialUnsafeReason(path, options);
|
|
98
|
-
if (reason !== null) return { status: 'unsafe', reason };
|
|
99
|
-
} else {
|
|
100
|
-
if ((stats.mode & 0o777) !== 0o600) return { status: 'unsafe', reason: 'mode_not_0600' };
|
|
101
|
-
if (typeof process.getuid === 'function' && stats.uid !== process.getuid()) return { status: 'unsafe', reason: 'owner_mismatch' };
|
|
102
|
-
}
|
|
103
|
-
let value;
|
|
101
|
+
async function signWithSigner(signer, signingText, options) {
|
|
102
|
+
const env = options.env ?? process.env;
|
|
103
|
+
const dir = dirname(options.storePath ?? runtimeErrorsStatePath(env));
|
|
104
|
+
const input = join(dir, `.signer-input-${process.pid}-${randomBytes(6).toString('hex')}`);
|
|
105
|
+
let fd = null;
|
|
104
106
|
try {
|
|
105
|
-
|
|
107
|
+
ensureSafeDir(dir);
|
|
108
|
+
writeFileSync(input, signingText, { mode: 0o600, flag: 'wx' });
|
|
109
|
+
fd = openSync(input, 'r');
|
|
106
110
|
} catch {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|| typeof value.url !== 'string' || typeof value.key_id !== 'string' || typeof value.secret !== 'string'
|
|
111
|
-
|| !KEY_ID.test(value.key_id) || value.secret.length < 16 || value.secret.length > 1024) {
|
|
112
|
-
return { status: 'unsafe', reason: 'invalid_shape' };
|
|
111
|
+
if (fd !== null) closeSync(fd);
|
|
112
|
+
rmSync(input, { force: true });
|
|
113
|
+
return { outcome: 'signer_failed', reason: 'input_not_written' };
|
|
113
114
|
}
|
|
114
|
-
let url;
|
|
115
115
|
try {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
116
|
+
const run = await new Promise((resolve) => {
|
|
117
|
+
let child;
|
|
118
|
+
try {
|
|
119
|
+
child = spawn(signer.command[0], signer.command.slice(1), { cwd: signer.cwd ?? undefined,
|
|
120
|
+
stdio: [fd, 'pipe', 'ignore'], windowsHide: true });
|
|
121
|
+
} catch {
|
|
122
|
+
resolve({ reason: 'spawn_failed' });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const chunks = [];
|
|
126
|
+
let size = 0;
|
|
127
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); resolve({ reason: 'timeout' }); }, options.signerTimeoutMs ?? SIGNER_TIMEOUT_MS);
|
|
128
|
+
child.stdout.on('data', (chunk) => {
|
|
129
|
+
size += chunk.length;
|
|
130
|
+
if (size <= SIGNER_OUTPUT_MAX_BYTES) chunks.push(chunk);
|
|
131
|
+
});
|
|
132
|
+
child.once('error', () => { clearTimeout(timer); resolve({ reason: 'spawn_failed' }); });
|
|
133
|
+
child.once('close', (code) => { clearTimeout(timer); resolve({ code, stdout: size > SIGNER_OUTPUT_MAX_BYTES ? null : Buffer.concat(chunks) }); });
|
|
134
|
+
});
|
|
135
|
+
if (run.code === 1) return { outcome: 'signer_refused', reason: 'signer_refused' };
|
|
136
|
+
if (run.code !== 0) return { outcome: 'signer_failed', reason: run.reason ?? 'signer_exit' };
|
|
137
|
+
const sig = run.stdout === null ? null : signatureBytes(run.stdout);
|
|
138
|
+
return sig === null ? { outcome: 'signer_failed', reason: 'signature_malformed' } : { sig };
|
|
139
|
+
} finally {
|
|
140
|
+
closeSync(fd);
|
|
141
|
+
rmSync(input, { force: true });
|
|
122
142
|
}
|
|
123
|
-
return { status: 'ok', credential: { url, keyId: value.key_id, secret: value.secret } };
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
127
|
-
const hmacHex = (secret, text) => createHmac('sha256', Buffer.from(secret, 'utf8')).update(text, 'utf8').digest('hex');
|
|
128
|
-
|
|
129
|
-
/** `sig = HMAC-SHA256(secret, ts + "\n" + SHA-256(送るバイト列の16進))`。秘密は文字列のままUTF-8で鍵にする。 */
|
|
130
|
-
export function signReport(secret, ts, bodyBytes) {
|
|
131
|
-
return hmacHex(secret, `${ts}\n${sha256Hex(bodyBytes)}`);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** 応答の署名: `HMAC-SHA256(secret, report_id + "\n" + received_at)`。別の機器が返した200を受領済みにしない。 */
|
|
135
|
-
export function receiptSignatureMatches(secret, reportId, receivedAt, sig) {
|
|
136
|
-
if (typeof receivedAt !== 'string' || typeof sig !== 'string' || !/^[0-9a-f]{64}$/.test(sig)) return false;
|
|
137
|
-
const expected = Buffer.from(hmacHex(secret, `${reportId}\n${receivedAt}`), 'hex');
|
|
138
|
-
return timingSafeEqual(expected, Buffer.from(sig, 'hex'));
|
|
139
143
|
}
|
|
140
144
|
|
|
141
145
|
/** snapshotの未受領分から、受け口へ送る本文を組む。項目はsnapshotが出すものをそのまま載せる。 */
|
|
@@ -205,14 +209,14 @@ function throttleReason(options, delivery, highWatermark) {
|
|
|
205
209
|
export function runtimeErrorReportingStatus(options = {}) {
|
|
206
210
|
const supported = runtimeErrorCollectionSupported(options);
|
|
207
211
|
const enabled = runtimeErrorReportingEnabled(options);
|
|
208
|
-
const
|
|
212
|
+
const signer = supported ? readRuntimeErrorReportingConfig(options)?.signer ?? null : null;
|
|
209
213
|
const diagnostics = runtimeErrorsDiagnostics(options);
|
|
210
214
|
const delivery = supported ? readDelivery(options) : emptyDelivery();
|
|
211
215
|
return {
|
|
212
216
|
schema: STATUS_SCHEMA,
|
|
213
217
|
reporting: !supported ? 'unsupported' : enabled ? 'enabled' : 'disabled',
|
|
214
|
-
|
|
215
|
-
|
|
218
|
+
signer: signer === null ? 'missing' : 'configured',
|
|
219
|
+
key_id: signer?.key_id ?? null,
|
|
216
220
|
collection: diagnostics.collection,
|
|
217
221
|
store_status: diagnostics.status,
|
|
218
222
|
pending_count: diagnostics.pending_count,
|
|
@@ -221,12 +225,20 @@ export function runtimeErrorReportingStatus(options = {}) {
|
|
|
221
225
|
};
|
|
222
226
|
}
|
|
223
227
|
|
|
224
|
-
/**
|
|
225
|
-
|
|
228
|
+
/**
|
|
229
|
+
* 送信の設定をLattice自身のfileへ書く。dotagentsの設定は読みも書きもしない。
|
|
230
|
+
* `change.signer`・`change.url`を渡した時だけ署名者・宛先を置き換え、渡さなければ今の設定を引き継ぐ。
|
|
231
|
+
*/
|
|
232
|
+
export function setRuntimeErrorReporting(enabled, options = {}, change = {}) {
|
|
226
233
|
if (typeof enabled !== 'boolean') throw Error('invalid_enabled');
|
|
227
234
|
if (!runtimeErrorCollectionSupported(options)) throw Error('reporting_unsupported');
|
|
235
|
+
if (change.signer !== undefined && !validReportingSigner(change.signer)) throw Error('invalid_signer');
|
|
236
|
+
if (change.url !== undefined && !validReportingUrl(change.url)) throw Error('invalid_url');
|
|
228
237
|
const env = options.env ?? process.env;
|
|
229
238
|
const path = options.reportingConfigPath ?? runtimeErrorReportingConfigPath(env);
|
|
239
|
+
const current = readRuntimeErrorReportingConfig({ ...options, reportingConfigPath: path });
|
|
240
|
+
const signer = change.signer ?? current?.signer ?? null;
|
|
241
|
+
const url = change.url ?? current?.url ?? null;
|
|
230
242
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
231
243
|
try {
|
|
232
244
|
if (lstatSync(path).isSymbolicLink()) throw Error('config_unsafe');
|
|
@@ -235,7 +247,8 @@ export function setRuntimeErrorReporting(enabled, options = {}) {
|
|
|
235
247
|
}
|
|
236
248
|
const temporary = join(dirname(path), `.runtime-error-reporting-${process.pid}-${randomBytes(6).toString('hex')}`);
|
|
237
249
|
try {
|
|
238
|
-
|
|
250
|
+
const config = { schema: REPORTING_CONFIG_SCHEMA, enabled, ...(signer && { signer }), ...(url && { url }) };
|
|
251
|
+
writeFileSync(temporary, `${JSON.stringify(config)}\n`, { mode: 0o600, flag: 'wx' });
|
|
239
252
|
replaceStoreFile(temporary, path);
|
|
240
253
|
} finally {
|
|
241
254
|
rmSync(temporary, { force: true });
|
|
@@ -279,9 +292,9 @@ function parseJson(text) {
|
|
|
279
292
|
|
|
280
293
|
/**
|
|
281
294
|
* 報告を1通、署名して送り、受領を確かめる。`accepted`を返すのは、200・`accepted: true`・`report_id`一致・
|
|
282
|
-
*
|
|
295
|
+
* 応答のES256署名一致がそろった時だけ。署名できなければ送らない。戻り値に署名・key_id・宛先は入れない。
|
|
283
296
|
*/
|
|
284
|
-
async function sendReport(
|
|
297
|
+
async function sendReport(config, snapshot, options) {
|
|
285
298
|
const now = nowMs(options);
|
|
286
299
|
const ts = Math.floor(now / 1000);
|
|
287
300
|
// `observed_at`は、載せる記録のどの時刻よりも前にしない(BugHubは観測より後の記録を断る)。秒へ切り捨てると、
|
|
@@ -293,17 +306,21 @@ async function sendReport({ url, keyId, secret }, snapshot, options) {
|
|
|
293
306
|
const bodyBytes = Buffer.from(JSON.stringify(report), 'utf8');
|
|
294
307
|
if (bodyBytes.length > REPORT_MAX_BYTES) return { outcome: 'too_large', reason: 'report_too_large', http_status: null };
|
|
295
308
|
|
|
296
|
-
const
|
|
309
|
+
const signed = await signWithSigner(config.signer, reportSigningText(ts, bodyBytes), options);
|
|
310
|
+
if (signed.sig === undefined) return { outcome: signed.outcome, reason: signed.reason, http_status: null };
|
|
311
|
+
|
|
312
|
+
const response = await post(new URL(options.url ?? config.url ?? DEFAULT_INTAKE_URL), {
|
|
297
313
|
'Content-Type': 'application/json',
|
|
298
314
|
'Content-Length': String(bodyBytes.length),
|
|
299
|
-
Authorization: `BugHub-
|
|
315
|
+
Authorization: `BugHub-ES256 key_id=${config.signer.key_id}, ts=${ts}, sig=${signed.sig.toString('base64')}`,
|
|
300
316
|
}, bodyBytes, options.timeoutMs ?? REQUEST_TIMEOUT_MS);
|
|
301
317
|
|
|
302
318
|
if (response.status === null) return { outcome: 'unconfirmed', reason: response.reason, http_status: null };
|
|
303
319
|
const body = parseJson(response.body);
|
|
304
320
|
if (response.status === 200) {
|
|
305
321
|
if (body === null || body.accepted !== true || body.report_id !== report.report_id
|
|
306
|
-
||
|
|
322
|
+
|| body.sig_alg !== 'ES256'
|
|
323
|
+
|| !receiptSignatureValid(options.responseKeyPem ?? BUGHUB_RESPONSE_PUBLIC_KEY, report.report_id, body.received_at, body.sig)) {
|
|
307
324
|
return { outcome: 'unconfirmed', reason: 'receipt_not_verified', http_status: 200 };
|
|
308
325
|
}
|
|
309
326
|
return { outcome: 'accepted', reason: null, http_status: 200 };
|
|
@@ -319,9 +336,8 @@ async function sendReport({ url, keyId, secret }, snapshot, options) {
|
|
|
319
336
|
export async function reportRuntimeErrors(options = {}) {
|
|
320
337
|
if (!runtimeErrorCollectionSupported(options)) return result('unsupported');
|
|
321
338
|
if (!runtimeErrorReportingEnabled(options)) return result('disabled');
|
|
322
|
-
const
|
|
323
|
-
if (
|
|
324
|
-
if (credential.status !== 'ok') return result('credential_unsafe', { reason: credential.reason });
|
|
339
|
+
const config = readRuntimeErrorReportingConfig(options);
|
|
340
|
+
if (!config?.signer) return result('signer_missing');
|
|
325
341
|
|
|
326
342
|
let pending;
|
|
327
343
|
let delivery;
|
|
@@ -350,7 +366,7 @@ export async function reportRuntimeErrors(options = {}) {
|
|
|
350
366
|
return result(outcome, { sent, acknowledged_through: pending.cursor.acknowledged_through, ...extra });
|
|
351
367
|
};
|
|
352
368
|
|
|
353
|
-
const answer = await sendReport(
|
|
369
|
+
const answer = await sendReport(config, pending, options);
|
|
354
370
|
if (answer.outcome === 'too_large') return result('rejected', { reason: 'report_too_large', sent });
|
|
355
371
|
if (answer.outcome !== 'accepted') return finish(answer.outcome, { reason: answer.reason, http_status: answer.http_status });
|
|
356
372
|
try {
|
|
@@ -363,26 +379,24 @@ export async function reportRuntimeErrors(options = {}) {
|
|
|
363
379
|
}
|
|
364
380
|
|
|
365
381
|
/**
|
|
366
|
-
* 記録を載せない空の報告を1
|
|
367
|
-
* 送る条件は`report
|
|
382
|
+
* 記録を載せない空の報告を1通送り、署名者・署名・受け口までの経路を確かめる(`reporting verify`)。
|
|
383
|
+
* 送る条件は`report`と同じで、送信を有効にしていない端末と署名者の無い端末はnetworkへ触れない。
|
|
368
384
|
* storeの記録・受領の印・送る時機の記録には触れない。受け口は端末×製品ごとに1分に1回まで受けるので、
|
|
369
385
|
* 直前に送っていれば429で断られる。
|
|
370
386
|
*/
|
|
371
387
|
export async function verifyRuntimeErrorReporting(options = {}) {
|
|
372
388
|
if (!runtimeErrorCollectionSupported(options)) return result('unsupported');
|
|
373
389
|
if (!runtimeErrorReportingEnabled(options)) return result('disabled');
|
|
374
|
-
const
|
|
375
|
-
if (
|
|
376
|
-
|
|
377
|
-
const answer = await sendReport(credential.credential, { runtime_errors: [], resolutions: [] }, options);
|
|
390
|
+
const config = readRuntimeErrorReportingConfig(options);
|
|
391
|
+
if (!config?.signer) return result('signer_missing');
|
|
392
|
+
const answer = await sendReport(config, { runtime_errors: [], resolutions: [] }, options);
|
|
378
393
|
if (answer.outcome === 'accepted') return result('verified', { http_status: 200 });
|
|
379
394
|
return result(answer.outcome, { reason: answer.reason, http_status: answer.http_status });
|
|
380
395
|
}
|
|
381
396
|
|
|
382
397
|
/**
|
|
383
398
|
* 自動送信の入口が、子processを起こす前に見る軽い判定。設定が無い端末(外の利用者)では、
|
|
384
|
-
* 設定fileの有無を1
|
|
385
|
-
* 合鍵の確認が外のprogramを起こすので、毎回のCLI実行には載せない。
|
|
399
|
+
* 設定fileの有無を1回見るだけで終わる。署名者commandは、送る時だけ走らせる——毎回のCLI実行には載せない。
|
|
386
400
|
*/
|
|
387
401
|
export function runtimeErrorAutoReportDue(options = {}) {
|
|
388
402
|
if (!runtimeErrorReportingEnabled(options)) return false;
|
|
@@ -390,7 +404,7 @@ export function runtimeErrorAutoReportDue(options = {}) {
|
|
|
390
404
|
const diagnostics = runtimeErrorsDiagnostics(options);
|
|
391
405
|
if (diagnostics.status !== 'ready' || diagnostics.pending_count === 0) return false;
|
|
392
406
|
if (throttleReason(options, readDelivery(options), diagnostics.high_watermark) !== null) return false;
|
|
393
|
-
return
|
|
407
|
+
return readRuntimeErrorReportingConfig(options)?.signer != null;
|
|
394
408
|
} catch {
|
|
395
409
|
return false;
|
|
396
410
|
}
|