session-peer 0.5.2 → 0.6.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.
Files changed (44) hide show
  1. package/PARITY.md +20 -5
  2. package/README.ja.md +8 -8
  3. package/README.ko.md +8 -8
  4. package/README.md +8 -8
  5. package/README.zh-CN.md +8 -8
  6. package/RELEASING.md +73 -0
  7. package/VALIDATION.md +102 -1
  8. package/dist/cli.js +54 -4
  9. package/dist/diagnostics.js +17 -98
  10. package/dist/discovery.d.ts +32 -0
  11. package/dist/discovery.js +405 -68
  12. package/dist/handoff-operations.js +23 -3
  13. package/dist/help.js +18 -2
  14. package/dist/macos-acl.d.ts +10 -0
  15. package/dist/macos-acl.js +75 -0
  16. package/dist/output.js +6 -1
  17. package/dist/protocol.d.ts +2 -2
  18. package/dist/protocol.js +1 -1
  19. package/dist/receipt-collector.d.ts +12 -0
  20. package/dist/receipt-collector.js +283 -0
  21. package/dist/receipt-command.d.ts +10 -0
  22. package/dist/receipt-command.js +246 -0
  23. package/dist/receipt-producer.d.ts +7 -0
  24. package/dist/receipt-producer.js +107 -0
  25. package/dist/receipt-protocol.d.ts +219 -0
  26. package/dist/receipt-protocol.js +374 -0
  27. package/dist/receipt-send.d.ts +26 -0
  28. package/dist/receipt-send.js +375 -0
  29. package/dist/receipt-state.d.ts +89 -0
  30. package/dist/receipt-state.js +503 -0
  31. package/dist/receipt-store.d.ts +32 -0
  32. package/dist/receipt-store.js +286 -0
  33. package/dist/replies.js +3 -1
  34. package/dist/send.d.ts +5 -2
  35. package/dist/send.js +34 -49
  36. package/dist/skill-metadata.js +4 -3
  37. package/docs/api.md +32 -7
  38. package/docs/design/typescript-skill-compatibility.md +29 -0
  39. package/docs/guide.ja.md +41 -15
  40. package/docs/guide.ko.md +43 -17
  41. package/docs/guide.md +42 -16
  42. package/docs/guide.zh-CN.md +41 -15
  43. package/docs/shorthand.md +1 -1
  44. package/package.json +3 -3
@@ -0,0 +1,75 @@
1
+ // Shared bounded macOS ACL metadata. No shell, arbitrary executable or file contents.
2
+ import { spawnSync } from 'node:child_process';
3
+ import { isAbsolute } from 'node:path';
4
+ export const MACOS_ACL_LIMITS = Object.freeze({ paths: 4481, batchPaths: 128, argumentBytes: 32768, batchOutput: 262144, totalOutput: 8388608, batches: 128, timeoutMs: 5000 });
5
+ // Node exposes POSIX mode bits, not macOS extended ACLs. Conservatively reject
6
+ // ANY extended ACL on automatic registries, including owner-only ACLs. The
7
+ // trusted system metadata helper receives only absolute paths and a minimal C
8
+ // locale environment; no shell, PATH lookup, agent binary or filename parsing.
9
+ // -b escapes embedded newlines and -n avoids account-name lookups. ACL entries
10
+ // must also be rejected when an xattr '@' masks the '+' permission suffix.
11
+ export function inspectMacosAcls(input) {
12
+ const paths = [...new Set(input)];
13
+ if (!paths.length)
14
+ return 'clear';
15
+ if (process.platform !== 'darwin' || paths.length > MACOS_ACL_LIMITS.paths)
16
+ return 'unknown';
17
+ const batches = [];
18
+ let batch = [], bytes = 0;
19
+ for (const path of paths) {
20
+ const size = Buffer.byteLength(path, 'utf8') + 1;
21
+ if (!isAbsolute(path) || path.includes('\0') || size > MACOS_ACL_LIMITS.argumentBytes)
22
+ return 'unknown';
23
+ if (batch.length && (batch.length >= MACOS_ACL_LIMITS.batchPaths || bytes + size > MACOS_ACL_LIMITS.argumentBytes)) {
24
+ batches.push(batch);
25
+ batch = [];
26
+ bytes = 0;
27
+ }
28
+ batch.push(path);
29
+ bytes += size;
30
+ }
31
+ if (batch.length)
32
+ batches.push(batch);
33
+ if (batches.length > MACOS_ACL_LIMITS.batches)
34
+ return 'unknown';
35
+ const cutoff = performance.now() + MACOS_ACL_LIMITS.timeoutMs;
36
+ let output = 0;
37
+ for (const entries of batches) {
38
+ const remaining = Math.floor(cutoff - performance.now());
39
+ if (remaining < 1)
40
+ return 'unknown';
41
+ let done;
42
+ try {
43
+ done = spawnSync('/bin/ls', ['-ldebn', '--', ...entries], { encoding: 'utf8',
44
+ env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' }, timeout: remaining,
45
+ maxBuffer: MACOS_ACL_LIMITS.batchOutput, killSignal: 'SIGKILL' });
46
+ }
47
+ catch {
48
+ return 'unknown';
49
+ }
50
+ if (done.error || done.status !== 0 || done.signal || typeof done.stdout !== 'string' ||
51
+ typeof done.stderr !== 'string' || done.stderr.length || performance.now() >= cutoff)
52
+ return 'unknown';
53
+ const size = Buffer.byteLength(done.stdout, 'utf8');
54
+ output += size;
55
+ if (size > MACOS_ACL_LIMITS.batchOutput || output > MACOS_ACL_LIMITS.totalOutput)
56
+ return 'unknown';
57
+ const lines = done.stdout.split('\n');
58
+ if (lines.at(-1) === '')
59
+ lines.pop();
60
+ let records = 0;
61
+ for (const line of lines) {
62
+ if (/^\s+\d+:/.test(line))
63
+ return 'acl';
64
+ const mode = /^[-dlcbps][rwxstST-]{9}([+@]?)\s/.exec(line);
65
+ if (!mode)
66
+ return 'unknown';
67
+ if (mode[1] === '+')
68
+ return 'acl';
69
+ records++;
70
+ }
71
+ if (records !== entries.length)
72
+ return 'unknown';
73
+ }
74
+ return 'clear';
75
+ }
package/dist/output.js CHANGED
@@ -59,7 +59,8 @@ export function renderOutput(value, format) {
59
59
  lines.push(`Codex home: ${safe(value.codexHome)}`);
60
60
  if (value.queueId)
61
61
  lines.push(`Queue ID: ${safe(value.queueId)}`);
62
- lines.push(value.submitted === false ? 'Dry run: nothing submitted.' : 'Submitted; consumption/ACK is not confirmed.');
62
+ lines.push(value.submitted === false ? 'Dry run: nothing submitted.' : value.handoff ?
63
+ 'Submitted; model consumption and completion are not confirmed.' : 'Submitted; consumption/ACK is not confirmed.');
63
64
  }
64
65
  if (value.ok === false) {
65
66
  lines.push(`Error: ${safe(value.error ?? 'operation_failed')}`);
@@ -71,9 +72,13 @@ export function renderOutput(value, format) {
71
72
  if (value.handoff && typeof value.handoff === 'object') {
72
73
  const h = value.handoff;
73
74
  lines.push(`Handoff: ${safe(h.correlationId)} (${safe(h.state)})`);
75
+ if (h.schemaVersion === 2)
76
+ lines.push('Receipt scope: delegated context; native generation and model identity are not established.');
74
77
  for (const key of ['observation', 'ack', 'wait'])
75
78
  lines.push(`${key}: ${safe(JSON.stringify(h[key]))}`);
76
79
  }
80
+ if (value.receiptBootstrap && typeof value.receiptBootstrap === 'object')
81
+ lines.push(`Receipt bootstrap: ${safe(JSON.stringify(value.receiptBootstrap))}`);
77
82
  if (value.sshTransport && typeof value.sshTransport === 'object') {
78
83
  const transport = value.sshTransport;
79
84
  lines.push(`SSH transport: ${safe(transport.status)} (${safe(transport.reason)}); verified remote facts retained.`);
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.5.2";
2
- export declare const VERSION_LINE = "session-peer 0.5.2 (typescript)";
1
+ export declare const VERSION = "0.6.0";
2
+ export declare const VERSION_LINE = "session-peer 0.6.0 (typescript)";
3
3
  export declare function host(value: string): string;
4
4
  export declare function reply(value: string): {
5
5
  to: string;
package/dist/protocol.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isIPv6 } from 'node:net';
2
2
  import { Refusal } from './discovery.js';
3
3
  import { uuid } from './writer.js';
4
- export const VERSION = '0.5.2';
4
+ export const VERSION = '0.6.0';
5
5
  export const VERSION_LINE = `session-peer ${VERSION} (typescript)`;
6
6
  // Return the OpenSSH destination: [user@]name, or an IPv6 literal with any
7
7
  // brackets removed (`ssh` does not strip `[...]` outside ssh:// URIs). Zone IDs
@@ -0,0 +1,12 @@
1
+ import { type ReceiptOperation, type ReceiptRequestBody, type ReceiptResponse } from './receipt-protocol.js';
2
+ export declare function receiptEndpoint(path: string): string;
3
+ export type Collector = {
4
+ contextId: string;
5
+ ledgerEpoch: string;
6
+ socketPath: string;
7
+ close: () => Promise<{
8
+ cleanup: 'confirmed' | 'unconfirmed';
9
+ }>;
10
+ };
11
+ export declare function startReceiptCollector(stateDir: string, socketPath: string): Promise<Collector>;
12
+ export declare function receiptExchange<K extends ReceiptOperation>(socketPath: string, context: string | null, op: K, body: ReceiptRequestBody[K], timeoutMs?: number): Promise<ReceiptResponse>;
@@ -0,0 +1,283 @@
1
+ // Explicit local receipt-only IPC. No native agent, shell, network or transcript calls.
2
+ import { randomUUID } from 'node:crypto';
3
+ import { chmodSync, lstatSync, realpathSync } from 'node:fs';
4
+ import { dirname, isAbsolute, resolve } from 'node:path';
5
+ import { createConnection, createServer } from 'node:net';
6
+ import { Refusal } from './discovery.js';
7
+ import { inspectMacosAcls } from './macos-acl.js';
8
+ import { ReceiptState } from './receipt-state.js';
9
+ import { RECEIPT_LIMITS, RECEIPT_PAIRS, parseReceiptRequest, parseReceiptResponse, publicReceiptError, validateReceiptRequest, validateReceiptResponse } from './receipt-protocol.js';
10
+ const fail = (code) => { throw new Refusal(code, 1); };
11
+ function privateParent(path) {
12
+ if (process.platform === 'win32' || process.getuid?.() === undefined)
13
+ fail('receipt_storage_unsupported');
14
+ if (!isAbsolute(path) || resolve(path) !== path || Buffer.byteLength(path) > 100 || path.includes('\0'))
15
+ fail('receipt_endpoint_untrusted');
16
+ const parent = dirname(path), stat = lstatSync(parent);
17
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 0o777) !== 0o700 ||
18
+ realpathSync(parent) !== parent)
19
+ fail('receipt_endpoint_untrusted');
20
+ }
21
+ function identity(stat) {
22
+ return [stat.dev, stat.ino, stat.uid, stat.mode, stat.ctimeNs, stat.birthtimeNs].join(':');
23
+ }
24
+ export function receiptEndpoint(path) {
25
+ try {
26
+ privateParent(path);
27
+ const stat = lstatSync(path, { bigint: true });
28
+ if (!stat.isSocket() || stat.uid !== BigInt(process.getuid()) || (stat.mode & 511n) !== 384n)
29
+ fail('receipt_endpoint_untrusted');
30
+ if (process.platform === 'darwin' && (inspectMacosAcls([dirname(path), path]) !== 'clear' ||
31
+ identity(lstatSync(path, { bigint: true })) !== identity(stat)))
32
+ fail('receipt_endpoint_untrusted');
33
+ return identity(stat);
34
+ }
35
+ catch (error) {
36
+ if (error instanceof Refusal)
37
+ throw error;
38
+ if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
39
+ return fail('receipt_collector_unavailable');
40
+ return fail('receipt_endpoint_untrusted');
41
+ }
42
+ }
43
+ const frame = (value) => Buffer.from(JSON.stringify(value) + '\n');
44
+ // Retain an unreferenced listener if its pathname was replaced. Node's normal
45
+ // server.close() unlinks that pathname, including a replacement regular file.
46
+ // Closing an untrusted pathname is therefore refused; process exit closes the
47
+ // orphaned FD. This is an explicitly unconfirmed cleanup, never deletion authority.
48
+ const orphanedListeners = new Set();
49
+ export async function startReceiptCollector(stateDir, socketPath) {
50
+ privateParent(socketPath);
51
+ if (dirname(socketPath) !== resolve(stateDir))
52
+ fail('receipt_endpoint_untrusted');
53
+ const state = new ReceiptState(stateDir);
54
+ state.open();
55
+ try {
56
+ if (state.endpointSelector !== socketPath)
57
+ fail('receipt_endpoint_untrusted');
58
+ try {
59
+ lstatSync(socketPath);
60
+ fail('receipt_endpoint_exists');
61
+ }
62
+ catch (error) {
63
+ if (error.code !== 'ENOENT')
64
+ throw error;
65
+ }
66
+ }
67
+ catch (error) {
68
+ state.close();
69
+ throw error;
70
+ }
71
+ let stopped = false, busy = false, original = '';
72
+ const connections = new Set();
73
+ const server = createServer({ allowHalfOpen: true }, socket => {
74
+ if (stopped || connections.size >= RECEIPT_LIMITS.connections) {
75
+ socket.destroy();
76
+ return;
77
+ }
78
+ connections.add(socket);
79
+ const started = performance.now();
80
+ let bytes = Buffer.alloc(0), handled = false;
81
+ const timeout = setTimeout(() => socket.destroy(), RECEIPT_LIMITS.readMs);
82
+ socket.on('error', () => { });
83
+ socket.once('close', () => { clearTimeout(timeout); connections.delete(socket); });
84
+ socket.on('data', chunk => {
85
+ if (handled) {
86
+ socket.destroy();
87
+ return;
88
+ }
89
+ if (performance.now() - started >= RECEIPT_LIMITS.exchangeMs || bytes.length + chunk.length > RECEIPT_LIMITS.frame) {
90
+ socket.destroy();
91
+ return;
92
+ }
93
+ bytes = Buffer.concat([bytes, chunk]);
94
+ });
95
+ // EOF is part of the one-frame request: do not mutate state merely because
96
+ // an early chunk ends in LF and then accept delayed trailing pollution.
97
+ socket.once('end', () => {
98
+ if (handled || socket.destroyed)
99
+ return;
100
+ handled = true;
101
+ clearTimeout(timeout);
102
+ if (performance.now() - started >= RECEIPT_LIMITS.readMs) {
103
+ socket.destroy();
104
+ return;
105
+ }
106
+ let request;
107
+ try {
108
+ request = parseReceiptRequest(bytes);
109
+ }
110
+ catch {
111
+ socket.destroy();
112
+ return;
113
+ }
114
+ let response;
115
+ try {
116
+ if (stopped || receiptEndpoint(socketPath) !== original)
117
+ fail('receipt_endpoint_changed');
118
+ if (request.collectorContextId !== null && request.collectorContextId !== state.collectorContextId)
119
+ fail('receipt_context_mismatch');
120
+ if (busy)
121
+ fail('receipt_collector_busy');
122
+ busy = true;
123
+ const body = dispatch(state, request);
124
+ response = validateReceiptResponse({ ipcVersion: 2, requestId: request.requestId,
125
+ collectorContextId: state.collectorContextId, ok: true, body }, request);
126
+ }
127
+ catch (error) {
128
+ response = { ipcVersion: 2, requestId: request.requestId, collectorContextId: state.collectorContextId,
129
+ ok: false, error: publicReceiptError(error) };
130
+ }
131
+ finally {
132
+ busy = false;
133
+ }
134
+ const remaining = Math.floor(RECEIPT_LIMITS.exchangeMs - (performance.now() - started));
135
+ if (remaining <= 0) {
136
+ socket.destroy();
137
+ return;
138
+ }
139
+ const encoded = frame(response);
140
+ if (encoded.length > RECEIPT_LIMITS.frame) {
141
+ socket.destroy();
142
+ return;
143
+ }
144
+ const output = setTimeout(() => socket.destroy(), Math.min(RECEIPT_LIMITS.writeMs, remaining));
145
+ socket.once('close', () => clearTimeout(output));
146
+ socket.end(encoded);
147
+ });
148
+ });
149
+ try {
150
+ await new Promise((ok, reject) => {
151
+ server.once('error', reject);
152
+ server.listen(socketPath, () => { server.removeListener('error', reject); ok(); });
153
+ });
154
+ chmodSync(socketPath, 0o600);
155
+ original = receiptEndpoint(socketPath);
156
+ }
157
+ catch (error) {
158
+ state.close();
159
+ if (server.listening) {
160
+ server.unref();
161
+ orphanedListeners.add(server);
162
+ }
163
+ throw error instanceof Refusal ? error : new Refusal('receipt_endpoint_untrusted', 1);
164
+ }
165
+ server.on('error', () => { });
166
+ let closing;
167
+ return { contextId: state.collectorContextId, ledgerEpoch: state.ledgerEpoch, socketPath,
168
+ close() {
169
+ if (closing)
170
+ return closing;
171
+ closing = (async () => {
172
+ stopped = true;
173
+ for (const socket of connections)
174
+ socket.destroy();
175
+ let safe = false;
176
+ try {
177
+ safe = receiptEndpoint(socketPath) === original;
178
+ }
179
+ catch { /* Never unlink an untrusted replacement. */ }
180
+ let cleanup = 'unconfirmed';
181
+ if (safe) {
182
+ await new Promise(ok => server.close(() => ok()));
183
+ try {
184
+ lstatSync(socketPath);
185
+ }
186
+ catch (error) {
187
+ if (error.code === 'ENOENT')
188
+ cleanup = 'confirmed';
189
+ }
190
+ }
191
+ else {
192
+ server.unref();
193
+ orphanedListeners.add(server);
194
+ }
195
+ try {
196
+ state.close();
197
+ }
198
+ catch {
199
+ cleanup = 'unconfirmed';
200
+ }
201
+ return { cleanup };
202
+ })();
203
+ return closing;
204
+ }
205
+ };
206
+ }
207
+ function dispatch(state, request) {
208
+ state.assertOpen();
209
+ switch (request.op) {
210
+ case 'hello': return { clockReferenceMs: state.clockReference(), receiptSchemas: RECEIPT_PAIRS, managedStoreVersion: 2,
211
+ endpointOwner: { uid: process.getuid(), pid: process.pid } };
212
+ case 'prepare': return state.prepare(request.body);
213
+ case 'mint': return { capability: state.mint(request.body).capability };
214
+ case 'fence': return { handoff: state.fence(request.body) };
215
+ case 'submission': return { handoff: state.submission(request.body) };
216
+ case 'status': return { handoff: state.status(request.body) };
217
+ case 'wait-open': return { handoff: state.waitOpen(request.body) };
218
+ case 'wait-status': return { handoff: state.waitStatus(request.body) };
219
+ case 'wait-stop': return { handoff: state.waitStop(request.body) };
220
+ case 'revoke': return { handoff: state.revoke(request.body) };
221
+ case 'receipt': {
222
+ const received = state.receipt(request.body.receipt);
223
+ return { ...received, ledgerEpoch: received.handoff.ledgerEpoch, correlationId: received.handoff.correlationId };
224
+ }
225
+ }
226
+ }
227
+ export async function receiptExchange(socketPath, context, op, body, timeoutMs = RECEIPT_LIMITS.exchangeMs) {
228
+ const started = performance.now();
229
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1)
230
+ fail('deadline_before_effect');
231
+ const duration = Math.min(Math.floor(timeoutMs), RECEIPT_LIMITS.exchangeMs);
232
+ const request = validateReceiptRequest({ ipcVersion: 2, requestId: randomUUID(), collectorContextId: context, op, body });
233
+ const before = receiptEndpoint(socketPath), encoded = frame(request);
234
+ if (performance.now() - started >= duration)
235
+ fail('deadline_before_effect');
236
+ return new Promise((ok, reject) => {
237
+ let attempted = false, finished = false, input = Buffer.alloc(0);
238
+ const connection = createConnection(socketPath);
239
+ const finish = (error, response) => {
240
+ if (finished)
241
+ return;
242
+ finished = true;
243
+ clearTimeout(timer);
244
+ connection.destroy();
245
+ if (error)
246
+ reject(error);
247
+ else
248
+ ok(response);
249
+ };
250
+ const timer = setTimeout(() => finish(new Refusal(attempted ? 'receipt_transport_unknown' : 'receipt_transport_timeout', 1)), Math.max(1, Math.min(RECEIPT_LIMITS.readMs, duration - (performance.now() - started))));
251
+ connection.once('connect', () => {
252
+ try {
253
+ if (receiptEndpoint(socketPath) !== before)
254
+ fail('receipt_endpoint_changed');
255
+ if (performance.now() - started >= duration)
256
+ fail('deadline_before_effect');
257
+ attempted = true;
258
+ connection.end(encoded);
259
+ }
260
+ catch (error) {
261
+ finish(error instanceof Refusal ? error : new Refusal('receipt_endpoint_untrusted', 1));
262
+ }
263
+ });
264
+ connection.on('data', chunk => {
265
+ if (input.length + chunk.length > RECEIPT_LIMITS.frame) {
266
+ finish(new Refusal('receipt_transport_unknown', 1));
267
+ return;
268
+ }
269
+ input = Buffer.concat([input, chunk]);
270
+ });
271
+ connection.once('end', () => {
272
+ try {
273
+ finish(undefined, parseReceiptResponse(input, request));
274
+ }
275
+ catch {
276
+ finish(new Refusal('receipt_transport_unknown', 1));
277
+ }
278
+ });
279
+ connection.once('error', () => finish(new Refusal(attempted ? 'receipt_transport_unknown' : 'receipt_collector_unavailable', 1)));
280
+ connection.once('close', () => { if (!finished)
281
+ finish(new Refusal(attempted ? 'receipt_transport_unknown' : 'receipt_collector_unavailable', 1)); });
282
+ });
283
+ }
@@ -0,0 +1,10 @@
1
+ import { type Collector } from './receipt-collector.js';
2
+ export type ReceiptCommandResult = {
3
+ value: Record<string, unknown>;
4
+ exitCode: number;
5
+ raw?: boolean;
6
+ collector?: Collector;
7
+ };
8
+ type Reader = (limit: number, privateInput?: boolean, timeoutMs?: number) => Promise<string>;
9
+ export declare function receiptCommand(args: string[], readInput: Reader): Promise<ReceiptCommandResult>;
10
+ export {};
@@ -0,0 +1,246 @@
1
+ // Explicit owner commands for the local receipt-only collector. This module
2
+ // never launches programs, submits native input or discovers another endpoint.
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { lstatSync, realpathSync } from 'node:fs';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { Refusal } from './discovery.js';
7
+ import { HandoffBudget, canonicalId, parseWaitTimeout, safeId } from './handoff.js';
8
+ import { ReceiptState } from './receipt-state.js';
9
+ import { receiptExchange, startReceiptCollector } from './receipt-collector.js';
10
+ import { RECEIPT_LIMITS, parseProducerProbeRequest, publicReceiptError, validateManagedHandoff, validateManagedReceipt } from './receipt-protocol.js';
11
+ import { VERSION } from './protocol.js';
12
+ const operations = ['init', 'serve', 'respond', 'status', 'wait', 'revoke', 'probe'];
13
+ function fail(code, exit = 2) { throw new Refusal(code, exit); }
14
+ function options(args) {
15
+ if (args[0] !== 'receipt' || !operations.includes(args[1]))
16
+ fail('unsupported_receipt_command');
17
+ const operation = args[1], values = new Map();
18
+ let json = false;
19
+ const names = ['--state-dir', '--collector', '--ledger-epoch', '--correlation-id', '--wait-timeout', '--receipt'];
20
+ for (let i = 2; i < args.length; i++) {
21
+ const token = args[i], equal = token.indexOf('='), key = equal < 0 ? token : token.slice(0, equal);
22
+ if (key === '--json') {
23
+ if (json || equal >= 0)
24
+ fail('invalid_option');
25
+ json = true;
26
+ continue;
27
+ }
28
+ if (!names.includes(key))
29
+ fail('unsupported_option');
30
+ if (values.has(key))
31
+ fail('invalid_option');
32
+ const value = equal < 0 ? args[++i] : token.slice(equal + 1);
33
+ if (value === undefined || (equal < 0 && value.startsWith('--')))
34
+ fail('invalid_option');
35
+ values.set(key, value);
36
+ }
37
+ if (!json)
38
+ fail('json_output_required');
39
+ const allowed = {
40
+ init: ['--state-dir', '--collector'], serve: ['--state-dir', '--collector'],
41
+ respond: ['--collector', '--receipt'], status: ['--collector', '--ledger-epoch', '--correlation-id'],
42
+ wait: ['--collector', '--ledger-epoch', '--correlation-id', '--wait-timeout'],
43
+ revoke: ['--collector', '--ledger-epoch', '--correlation-id'], probe: []
44
+ };
45
+ if ([...values.keys()].some(key => !allowed[operation].includes(key)))
46
+ fail('inapplicable_option');
47
+ return { operation, values };
48
+ }
49
+ function absolute(value, code, maximum = 4096) {
50
+ if (!safeId(value, maximum) || !isAbsolute(value) || resolve(value) !== value)
51
+ fail(code);
52
+ return value;
53
+ }
54
+ function success(response) {
55
+ if (!response.ok)
56
+ throw new Refusal(response.error, 1);
57
+ return response.body;
58
+ }
59
+ function unknown(error, handoff, exit = 1) {
60
+ if (!(error instanceof Refusal) || error.code !== 'receipt_transport_unknown')
61
+ return undefined;
62
+ return { value: { ok: false, status: 'unknown', error: 'receipt_transport_unknown', retryAllowed: false,
63
+ ...(handoff ? { handoff } : {}) }, exitCode: exit };
64
+ }
65
+ function waitResult(handoff) {
66
+ const satisfied = handoff.wait.status === 'satisfied';
67
+ return { value: { ok: satisfied, handoff }, exitCode: satisfied ? 0 : handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator' ? 130 : 1 };
68
+ }
69
+ async function privateInput(readInput) {
70
+ let raw;
71
+ try {
72
+ raw = await readInput(RECEIPT_LIMITS.privateFrame, true, RECEIPT_LIMITS.readMs);
73
+ }
74
+ catch {
75
+ throw new Refusal('invalid_receipt_protocol', 1);
76
+ }
77
+ if (typeof raw !== 'string')
78
+ throw new Refusal('invalid_receipt_protocol', 1);
79
+ if (Buffer.byteLength(raw, 'utf8') > RECEIPT_LIMITS.privateFrame)
80
+ throw new Refusal('receipt_frame_too_large', 1);
81
+ return raw;
82
+ }
83
+ function platform() {
84
+ if (process.platform === 'win32' || process.getuid?.() === undefined)
85
+ throw new Refusal('receipt_storage_unsupported', 1);
86
+ }
87
+ // Initialization may create only its explicitly selected leaf. Reject an alias
88
+ // before creating files that could not later pass the collector endpoint guard.
89
+ function statePath(value) {
90
+ const path = absolute(value, 'invalid_receipt_state');
91
+ try {
92
+ let present = true;
93
+ try {
94
+ lstatSync(path);
95
+ }
96
+ catch (error) {
97
+ if (error.code === 'ENOENT')
98
+ present = false;
99
+ else
100
+ throw error;
101
+ }
102
+ const existing = present ? path : dirname(path);
103
+ if (realpathSync(existing) !== existing)
104
+ throw new Error();
105
+ }
106
+ catch {
107
+ throw new Refusal('receipt_storage_untrusted', 1);
108
+ }
109
+ return path;
110
+ }
111
+ async function wait(socket, epoch, id, seconds) {
112
+ const budget = new HandoffBudget(seconds);
113
+ let interrupted = false, stopAttempted = false;
114
+ let latest, original;
115
+ let context, operationId;
116
+ const selector = { ledgerEpoch: epoch, correlationId: id };
117
+ const stop = () => { interrupted = true; };
118
+ const accept = (value) => {
119
+ const next = validateManagedHandoff(value);
120
+ if (next.ledgerEpoch !== epoch || next.correlationId !== id || next.wait.for !== 'acknowledged' || !canonicalId(next.wait.operationId))
121
+ throw new Refusal('invalid_receipt_protocol', 1);
122
+ if (original && (next.schemaVersion !== original.schemaVersion || next.targetGeneration !== original.targetGeneration ||
123
+ next.wait.operationId !== operationId || next.wait.deadlineAtUtcMs !== original.wait.deadlineAtUtcMs ||
124
+ (original.schemaVersion === 2 && (next.schemaVersion !== 2 || next.receiptContext.id !== original.receiptContext.id))))
125
+ throw new Refusal('receipt_binding_conflict', 1);
126
+ if (!original) {
127
+ original = structuredClone(next);
128
+ operationId = next.wait.operationId;
129
+ }
130
+ return next;
131
+ };
132
+ const retained = (error) => ({ value: { ok: false, status: 'unknown',
133
+ error: publicReceiptError(error), retryAllowed: false, ...(latest ? { handoff: latest } : {}) }, exitCode: latest?.wait.status === 'stopped' && latest.wait.reason === 'stopped_by_operator' ? 130 : 1 });
134
+ process.on('SIGINT', stop);
135
+ process.on('SIGTERM', stop);
136
+ try {
137
+ const hello = await receiptExchange(socket, null, 'hello', {}, budget.remainingMs());
138
+ const remainingMs = Math.floor(budget.remainingMs()), capabilities = success(hello);
139
+ context = hello.collectorContextId;
140
+ if (!('clockReferenceMs' in capabilities) || remainingMs < 1)
141
+ throw new Refusal('deadline_before_effect', 1);
142
+ const opened = success(await receiptExchange(socket, context, 'wait-open', { ...selector, goal: 'acknowledged', timeoutSeconds: seconds, clockReferenceMs: capabilities.clockReferenceMs, remainingMs }, budget.remainingMs()));
143
+ latest = accept(opened.handoff);
144
+ while (latest.wait.status === 'pending') {
145
+ if (budget.remainingMs() <= 0)
146
+ return retained(new Refusal('receipt_transport_unknown', 1));
147
+ if (interrupted && !stopAttempted) {
148
+ stopAttempted = true;
149
+ latest = accept(success(await receiptExchange(socket, context, 'wait-stop', { ...selector, operationId: operationId }, budget.remainingMs())).handoff);
150
+ return waitResult(latest);
151
+ }
152
+ await delay(Math.min(100, Math.max(1, budget.remainingMs())));
153
+ if (interrupted)
154
+ continue;
155
+ latest = accept(success(await receiptExchange(socket, context, 'wait-status', { ...selector, operationId: operationId }, budget.remainingMs())).handoff);
156
+ }
157
+ return waitResult(latest);
158
+ }
159
+ catch (error) {
160
+ // A terminal actor result may win the race against the explicit stop. Read
161
+ // that same operation once; do not retry stop, renew a wait or adopt an owner.
162
+ if (latest && stopAttempted && error instanceof Refusal && error.code === 'receipt_wait_terminal' &&
163
+ context && operationId && budget.remainingMs() > 0) {
164
+ try {
165
+ const terminal = accept(success(await receiptExchange(socket, context, 'wait-status', { ...selector, operationId }, budget.remainingMs())).handoff);
166
+ if (terminal.wait.status !== 'pending') {
167
+ latest = terminal;
168
+ return waitResult(terminal);
169
+ }
170
+ }
171
+ catch (readError) {
172
+ return retained(readError);
173
+ }
174
+ }
175
+ if (latest)
176
+ return retained(error);
177
+ const result = unknown(error, undefined, 1);
178
+ if (result)
179
+ return result;
180
+ if (interrupted)
181
+ return { value: { ok: false, error: publicReceiptError(error), retryAllowed: false }, exitCode: 1 };
182
+ throw error;
183
+ }
184
+ finally {
185
+ process.removeListener('SIGINT', stop);
186
+ process.removeListener('SIGTERM', stop);
187
+ }
188
+ }
189
+ export async function receiptCommand(args, readInput) {
190
+ const { operation, values } = options(args);
191
+ if (operation === 'probe') {
192
+ const request = parseProducerProbeRequest(await privateInput(readInput));
193
+ return { value: { ...request, implementation: 'typescript', runtimeVersion: VERSION }, exitCode: 0, raw: true };
194
+ }
195
+ platform();
196
+ if (operation === 'init' || operation === 'serve') {
197
+ const state = statePath(values.get('--state-dir'));
198
+ const socket = absolute(values.get('--collector') ?? join(state, 's'), 'receipt_endpoint_untrusted', 100);
199
+ if (dirname(socket) !== state)
200
+ throw new Refusal('receipt_endpoint_untrusted', 1);
201
+ if (operation === 'init')
202
+ return { value: { ...ReceiptState.initialize(state, socket), collector: socket }, exitCode: 0 };
203
+ const collector = await startReceiptCollector(state, socket);
204
+ return { value: { status: 'ready', collector: socket, collectorContextId: collector.contextId,
205
+ ledgerEpoch: collector.ledgerEpoch }, exitCode: 0, collector };
206
+ }
207
+ const socket = absolute(values.get('--collector'), 'receipt_endpoint_untrusted', 100);
208
+ if (operation === 'respond') {
209
+ if (values.get('--receipt') !== '-')
210
+ fail('private_receipt_stdin_required');
211
+ const raw = await privateInput(readInput), receipt = validateManagedReceipt(raw);
212
+ try {
213
+ const hello = await receiptExchange(socket, null, 'hello', {}), capabilities = success(hello);
214
+ const scope = receipt.schemaVersion === 1 ? 'original_generation' : 'delegated_context';
215
+ if (!capabilities.receiptSchemas.some((pair) => pair.receiptSchemaVersion === receipt.schemaVersion && pair.receiptScope === scope))
216
+ throw new Refusal('receipt_scope_unsupported', 1);
217
+ const result = success(await receiptExchange(socket, hello.collectorContextId, 'receipt', { receipt: raw }));
218
+ return { value: result, exitCode: 0 };
219
+ }
220
+ catch (error) {
221
+ const result = unknown(error);
222
+ if (result)
223
+ return result;
224
+ throw error;
225
+ }
226
+ }
227
+ const epoch = values.get('--ledger-epoch'), id = values.get('--correlation-id');
228
+ if (!canonicalId(epoch))
229
+ fail('invalid_ledger_epoch');
230
+ if (!canonicalId(id))
231
+ fail('invalid_correlation_id');
232
+ if (operation === 'wait')
233
+ return wait(socket, epoch, id, parseWaitTimeout(values.get('--wait-timeout') ?? '30'));
234
+ try {
235
+ const hello = await receiptExchange(socket, null, 'hello', {});
236
+ success(hello);
237
+ const result = success(await receiptExchange(socket, hello.collectorContextId, operation, { ledgerEpoch: epoch, correlationId: id }));
238
+ return { value: result, exitCode: 0 };
239
+ }
240
+ catch (error) {
241
+ const result = unknown(error);
242
+ if (result)
243
+ return result;
244
+ throw error;
245
+ }
246
+ }