@quolu/lattice 0.115.0 → 0.117.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.
@@ -1,10 +1,10 @@
1
- import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
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
- windowsLocalAppData,
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`を打ち、BugHubの持ち主が合鍵のfileを
29
- * 置いた端末だけが送る。どちらかが欠ければ、networkへ触れない。
30
- * - 秘密は通信に載せない。本文のSHA-256と時刻へのHMAC-SHA256署名だけを`Authorization`に付ける。
31
- * - 受領済みにするのは、200・`accepted: true`・`report_id`一致・応答の署名一致がそろった時だけ。
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', 'credential_missing',
53
- 'credential_unsafe', 'throttled', 'rejected', 'unconfirmed', 'store_unavailable']);
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
- /** 合鍵の置き場(BugHubの契約)。Windowsは`%LOCALAPPDATA%\bughub\product-credentials\`。 */
59
- export function productCredentialPath(env = process.env, platform = hostPlatform()) {
60
- const base = platform === 'win32' ? join(windowsLocalAppData(env), 'bughub') : join(env.HOME || homedir(), '.config', 'bughub');
61
- return join(base, 'product-credentials', `${PRODUCT_ID}.json`);
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
- * Windowsの合鍵が本人・SYSTEM・Administratorsだけのものか。DACLの読み取りは出力fileを置く場所が要るので、
66
- * 絞ったstoreのフォルダを使う(無ければ作る)。合鍵のフォルダへは何も書かない。
67
- */
68
- function windowsCredentialUnsafeReason(path, options) {
69
- const storeDir = dirname(options.storePath ?? runtimeErrorsStatePath(options.env ?? process.env));
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
- ensureSafeDir(storeDir);
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 'acl_unverifiable';
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
- * 合鍵のfileを読む。BugHubの持ち主が置く形(symlinkでなく、POSIXは本人所有・0600、Windowsは
85
- * 本人・SYSTEM・Administratorsだけに権限)以外は使わない。秘密は戻り値の中だけに留め、結果や記録へ写さない。
97
+ * 署名者commandを走らせて署名を得る。入力は、storeの(本人だけの)folderに置いたfileから標準入力へ渡す
98
+ * ——pipeでは、Windowsのsshが固まる。入力fileは必ず消す。exit 1は断られた、それ以外・時間切れ・起動できない
99
+ * ・形の違う出力は失敗。結果に署名者の出力は載せない。
86
100
  */
87
- export function readProductCredential(options = {}) {
88
- const path = options.credentialPath ?? productCredentialPath(options.env ?? process.env);
89
- let stats;
90
- try {
91
- stats = lstatSync(path);
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
- value = JSON.parse(readFileSync(path, 'utf8'));
107
+ ensureSafeDir(dir);
108
+ writeFileSync(input, signingText, { mode: 0o600, flag: 'wx' });
109
+ fd = openSync(input, 'r');
106
110
  } catch {
107
- return { status: 'unsafe', reason: 'not_json' };
108
- }
109
- if (!plain(value) || !exact(value, ['url', 'key_id', 'secret'])
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
- url = new URL(value.url);
117
- } catch {
118
- return { status: 'unsafe', reason: 'invalid_url' };
119
- }
120
- if (!['http:', 'https:'].includes(url.protocol) || url.username !== '' || url.password !== '') {
121
- return { status: 'unsafe', reason: 'invalid_url' };
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 credential = supported ? readProductCredential(options) : { status: 'missing' };
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
- credential: credential.status === 'ok' ? 'present' : credential.status,
215
- credential_reason: credential.status === 'unsafe' ? credential.reason : null,
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
- /** 送信の設定をLattice自身のfileへ書く。dotagentsの設定は読みも書きもしない。 */
225
- export function setRuntimeErrorReporting(enabled, options = {}) {
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
- writeFileSync(temporary, `${JSON.stringify({ schema: REPORTING_CONFIG_SCHEMA, enabled })}\n`, { mode: 0o600, flag: 'wx' });
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
- * 応答の署名一致がそろった時だけ。戻り値に秘密・key_id・宛先は入れない。
295
+ * 応答のES256署名一致がそろった時だけ。署名できなければ送らない。戻り値に署名・key_id・宛先は入れない。
283
296
  */
284
- async function sendReport({ url, keyId, secret }, snapshot, options) {
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 response = await post(url, {
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-HMAC-SHA256 key_id=${keyId}, ts=${ts}, sig=${signReport(secret, String(ts), bodyBytes)}`,
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
- || !receiptSignatureMatches(secret, report.report_id, body.received_at, body.sig)) {
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 credential = readProductCredential(options);
323
- if (credential.status === 'missing') return result('credential_missing');
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(credential.credential, pending, options);
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通送り、合鍵・署名・受け口までの経路を確かめる(`reporting verify`)。
367
- * 送る条件は`report`と同じで、送信を有効にしていない端末と合鍵の無い端末はnetworkへ触れない。
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 credential = readProductCredential(options);
375
- if (credential.status === 'missing') return result('credential_missing');
376
- if (credential.status !== 'ok') return result('credential_unsafe', { reason: credential.reason });
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回見るだけで終わる。合鍵は、送るものがある時だけ確かめる——Windowsでは
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 readProductCredential(options).status === 'ok';
407
+ return readRuntimeErrorReportingConfig(options)?.signer != null;
394
408
  } catch {
395
409
  return false;
396
410
  }
@@ -114,27 +114,55 @@ export function runtimeErrorReportingConfigPath(env = process.env, platform = ho
114
114
  return join(env.HOME || homedir(), '.config', 'lattice', 'runtime-error-reporting.json');
115
115
  }
116
116
 
117
+ /** 署名者の設定(秘密なし)。key_idはBugHubの発行名、commandはargv(shellを通さない)、cwdは認証仲介が呼び出し元として見るfolder。 */
118
+ const SIGNER_KEY_ID = /^[A-Za-z0-9._:-]{1,128}$/;
119
+ const text = (value) => typeof value === 'string' && value.length >= 1 && value.length <= 4096 && !value.includes('\0');
120
+ export function validReportingSigner(value) {
121
+ return plain(value) && exact(value, ['key_id', 'command', 'cwd'])
122
+ && typeof value.key_id === 'string' && SIGNER_KEY_ID.test(value.key_id)
123
+ && Array.isArray(value.command) && value.command.length >= 1 && value.command.length <= 64 && value.command.every(text)
124
+ && (value.cwd === null || text(value.cwd));
125
+ }
126
+
127
+ export function validReportingUrl(value) {
128
+ try {
129
+ const url = new URL(value);
130
+ return typeof value === 'string' && value.length <= 2048 && ['http:', 'https:'].includes(url.protocol) && url.username === '' && url.password === '';
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
117
136
  /**
118
- * Lattice自身の送信設定(ADR 0193)。端末で`runtime-errors reporting enable`を打った時だけ有効になる。
137
+ * Lattice自身の送信設定(ADR 0193・0197)。端末で`runtime-errors reporting enable`を打った時だけ有効になる。
138
+ * `signer`(BugHub-ES256の署名者)と`url`(既定の受け口の差し替え)は任意。形の違う`signer`・`url`は無いものとして読む。
119
139
  * `LATTICE_RUNTIME_ERROR_REPORTING=0`は既定の置き場を読まない——試験と自動化が、その端末の本物の設定を
120
140
  * 拾って送信しないための口。`options.reportingConfigPath`を明示した呼び出しはそのfileを読む。
141
+ * 設定が無い・読めない・形が違う時は`null`。
121
142
  */
122
- export function runtimeErrorReportingEnabled(options = {}) {
123
- if (!collectionSupported(options)) return false;
143
+ export function readRuntimeErrorReportingConfig(options = {}) {
144
+ if (!collectionSupported(options)) return null;
124
145
  const env = options.env ?? process.env;
125
- if (options.reportingConfigPath === undefined && env.LATTICE_RUNTIME_ERROR_REPORTING === '0') return false;
146
+ if (options.reportingConfigPath === undefined && env.LATTICE_RUNTIME_ERROR_REPORTING === '0') return null;
126
147
  try {
127
148
  const path = options.reportingConfigPath ?? runtimeErrorReportingConfigPath(env);
128
149
  const stats = lstatSync(path);
129
- if (!stats.isFile() || stats.isSymbolicLink()) return false;
150
+ if (!stats.isFile() || stats.isSymbolicLink()) return null;
130
151
  const config = JSON.parse(readFileSync(path, 'utf8'));
131
- return plain(config) && exact(config, ['schema', 'enabled'])
132
- && config.schema === REPORTING_CONFIG_SCHEMA && config.enabled === true;
152
+ if (!plain(config) || !Object.keys(config).every((key) => ['schema', 'enabled', 'signer', 'url'].includes(key))
153
+ || config.schema !== REPORTING_CONFIG_SCHEMA || typeof config.enabled !== 'boolean') return null;
154
+ return { enabled: config.enabled,
155
+ signer: validReportingSigner(config.signer) ? config.signer : null,
156
+ url: validReportingUrl(config.url) ? config.url : null };
133
157
  } catch {
134
- return false;
158
+ return null;
135
159
  }
136
160
  }
137
161
 
162
+ export function runtimeErrorReportingEnabled(options = {}) {
163
+ return readRuntimeErrorReportingConfig(options)?.enabled === true;
164
+ }
165
+
138
166
  function collectionEnabled(options = {}) {
139
167
  return factoryCollectionEnabled(options) || runtimeErrorReportingEnabled(options);
140
168
  }
@@ -240,7 +268,7 @@ export function ensureSafeDir(dir) {
240
268
 
241
269
  /**
242
270
  * `scratchDir`はWindowsだけが使う: DACLの読み取りが出力fileを置くフォルダ。既定はそのfileのフォルダ。
243
- * storeの外のfile(合鍵)を確かめる時は、絞ってあるstoreのフォルダを渡す。
271
+ * storeの外のfileを確かめる時は、絞ってあるfolderを渡す。
244
272
  */
245
273
  export function ensureSafeFile(path, scratchDir = dirname(path)) {
246
274
  const stats = lstatSync(path);
package/src/todo-cli.mjs CHANGED
@@ -200,6 +200,7 @@ import {
200
200
  appendTodoNote,
201
201
  readTodoNoteContext,
202
202
  readTodoNoteContextsForPlan,
203
+ readTodoNoteSource,
203
204
  readTodoNoteEvents,
204
205
  readTodoPlanNotesForStatus,
205
206
  } from './todo-note-store.mjs';
@@ -2935,11 +2936,16 @@ async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, s
2935
2936
  const body = inputRef === null ? message : await readNoteTextInput(repoRoot, inputRef);
2936
2937
  // 訂正はscopeを跨げない。plan noteはplan chainの中だけ、task noteは自分のtaskの中だけを
2937
2938
  // 訂正できる。contextはplan noteも載せるので、task側はscopeで絞らないと跨げてしまう。
2938
- const eligibleSupersedes = task === null
2939
- ? (await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' })).events
2940
- .map(({ event_digest: digest }) => digest)
2941
- : (await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id }))
2942
- .history.filter(({ scope }) => scope === 'task').map(({ event_digest: digest }) => digest);
2939
+ // w2: the note chains and the version lineage are read once, before anything is written (a broken history still refuses first),
2940
+ // and the context is projected once, after the append. Only a correction needs the history before it (eligibleSupersedes
2941
+ // is read only when supersedes is set).
2942
+ const source = task === null ? null : await readTodoNoteSource({ repoRoot, store, planKey, taskId: task.task_id });
2943
+ let eligibleSupersedes = [];
2944
+ if (supersedes !== null) {
2945
+ eligibleSupersedes = task === null
2946
+ ? (await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' })).events.map(({ event_digest: digest }) => digest)
2947
+ : source.project().history.filter(({ scope }) => scope === 'task').map(({ event_digest: digest }) => digest);
2948
+ }
2943
2949
  const event = await appendTodoNote({
2944
2950
  repoRoot,
2945
2951
  projectId: store.project_id,
@@ -2954,8 +2960,7 @@ async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, s
2954
2960
  });
2955
2961
  // plan noteはどのtaskのcontextにも載るので、1つを選んで返すと嘘になる。全部読むなら
2956
2962
  // `note list --plan <k>`。書けたことの証拠はeventそのものが持つ。
2957
- const context = task === null
2958
- ? null : (await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id })).context;
2963
+ const context = source === null ? null : source.project([event]).context;
2959
2964
  const result = {
2960
2965
  schema: 'lattice.todo_note_append_result.v2',
2961
2966
  project_id: store.project_id,