session-peer 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CONTRIBUTING.md +11 -5
  2. package/PARITY.md +20 -5
  3. package/README.ja.md +8 -8
  4. package/README.ko.md +8 -8
  5. package/README.md +8 -8
  6. package/README.zh-CN.md +8 -8
  7. package/RELEASING.md +116 -0
  8. package/VALIDATION.md +137 -1
  9. package/dist/cli.js +54 -4
  10. package/dist/diagnostics.js +17 -98
  11. package/dist/discovery.d.ts +32 -0
  12. package/dist/discovery.js +405 -68
  13. package/dist/handoff-operations.js +88 -34
  14. package/dist/help.js +18 -2
  15. package/dist/macos-acl.d.ts +10 -0
  16. package/dist/macos-acl.js +75 -0
  17. package/dist/output.js +6 -1
  18. package/dist/protocol.d.ts +2 -2
  19. package/dist/protocol.js +1 -1
  20. package/dist/receipt-collector.d.ts +12 -0
  21. package/dist/receipt-collector.js +283 -0
  22. package/dist/receipt-command.d.ts +10 -0
  23. package/dist/receipt-command.js +246 -0
  24. package/dist/receipt-producer.d.ts +7 -0
  25. package/dist/receipt-producer.js +107 -0
  26. package/dist/receipt-protocol.d.ts +219 -0
  27. package/dist/receipt-protocol.js +374 -0
  28. package/dist/receipt-send.d.ts +26 -0
  29. package/dist/receipt-send.js +375 -0
  30. package/dist/receipt-state.d.ts +89 -0
  31. package/dist/receipt-state.js +503 -0
  32. package/dist/receipt-store.d.ts +32 -0
  33. package/dist/receipt-store.js +286 -0
  34. package/dist/replies.js +3 -1
  35. package/dist/send.d.ts +5 -2
  36. package/dist/send.js +34 -49
  37. package/dist/skill-metadata.js +5 -3
  38. package/docs/api.md +32 -7
  39. package/docs/design/typescript-skill-compatibility.md +48 -0
  40. package/docs/guide.ja.md +41 -15
  41. package/docs/guide.ko.md +43 -17
  42. package/docs/guide.md +42 -16
  43. package/docs/guide.zh-CN.md +41 -15
  44. package/docs/shorthand.md +1 -1
  45. package/package.json +3 -3
@@ -1,6 +1,7 @@
1
1
  // Opt-in integration only. Default CLI imports this without opening storage or
2
2
  // starting an observer/collector. Production receipt bootstrap is unqualified.
3
3
  import { homedir, hostname } from 'node:os';
4
+ import { channel } from 'node:diagnostics_channel';
4
5
  import { dirname, isAbsolute, join, parse, resolve } from 'node:path';
5
6
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync } from 'node:fs';
6
7
  import { HandoffLedger, payloadDigest } from './handoff-ledger.js';
@@ -14,11 +15,93 @@ import { HomeRefusal } from './writer.js';
14
15
  import { run, UnknownOutcome } from './process.js';
15
16
  import { currentPlatform, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
16
17
  import { codexStoragePin } from './codex-storage.js';
18
+ // Internal observations only: no I/O or public protocol changes. Never publish
19
+ // paths, identifiers, generations, native output or arguments on this channel.
20
+ const ownerProbeChannel = channel('session-peer.handoff.owner-probe');
21
+ async function retainedOwnerProbe(scope, budget, ownerArgs, phase, stopped, signal) {
22
+ const observed = ownerProbeChannel.hasSubscribers, started = observed ? performance.now() : 0;
23
+ let timeoutMs = 0;
24
+ const report = (outcome, result) => {
25
+ if (!observed)
26
+ return;
27
+ ownerProbeChannel.publish(Object.freeze({ schemaVersion: 1, phase, outcome,
28
+ elapsedMs: Math.max(0, Math.round((performance.now() - started) * 1000) / 1000),
29
+ timeoutMs: Math.max(0, timeoutMs), spawned: result?.spawned ?? false,
30
+ code: result?.code ?? null, interrupted: result?.interrupted ?? false, stopReason: result?.stopReason ?? null }));
31
+ };
32
+ if (stopped()) {
33
+ report('stopped');
34
+ return false;
35
+ }
36
+ if (signal?.aborted) {
37
+ report('aborted');
38
+ return false;
39
+ }
40
+ if (budget.observationRemainingMs() < 1) {
41
+ report('budget_exhausted');
42
+ return false;
43
+ }
44
+ const worker = fileURLToPath(new URL('./handoff-writer-probe.js', import.meta.url));
45
+ timeoutMs = Math.min(800, budget.observationRemainingMs());
46
+ let result;
47
+ try {
48
+ result = await run(process.execPath, [worker, scope.home, scope.threadId, ...ownerArgs], { timeout: timeoutMs, limit: 4096, env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
49
+ }
50
+ catch (error) {
51
+ report('process_error');
52
+ throw error;
53
+ }
54
+ if (stopped()) {
55
+ report('stopped', result);
56
+ return false;
57
+ }
58
+ if (signal?.aborted) {
59
+ report('aborted', result);
60
+ return false;
61
+ }
62
+ if (result.code !== 0 || result.interrupted) {
63
+ report(result.stopReason ?? (result.interrupted ? 'interrupted' : 'nonzero_exit'), result);
64
+ return false;
65
+ }
66
+ try {
67
+ const value = JSON.parse(result.stdout);
68
+ const valid = value.schemaVersion === 1 && value.ok === true &&
69
+ Object.keys(value).every(key => ['schemaVersion', 'ok', 'generation'].includes(key)) && /^[0-9a-f]{64}$/.test(value.generation);
70
+ const matched = valid && value.generation === scope.generation;
71
+ report(matched ? 'matched' : valid ? 'generation_mismatch' :
72
+ value.schemaVersion === 1 && value.ok === false ? 'unverified_reply' : 'invalid_reply', result);
73
+ return matched;
74
+ }
75
+ catch {
76
+ report('invalid_reply', result);
77
+ return false;
78
+ }
79
+ }
80
+ function unmanaged(path) {
81
+ // A managed v2 context has one collector writer. New legacy CLI paths must
82
+ // refuse before even creating an old lock file; historical v1 stays intact.
83
+ if (process.platform !== 'win32') {
84
+ for (const marker of ['managed.json', 'collector.lock']) {
85
+ try {
86
+ lstatSync(join(path, marker));
87
+ throw new Refusal('receipt_managed_context_required', 1);
88
+ }
89
+ catch (error) {
90
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? '')) {
91
+ if (error instanceof Refusal)
92
+ throw error;
93
+ throw new Refusal('handoff_history_unavailable', 1);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ return path;
99
+ }
17
100
  export function ledgerPath() {
18
101
  const path = process.env.SESSION_PEER_HANDOFF_HOME ?? join(homedir(), '.local', 'state', 'session-peer-ts', 'handoff');
19
102
  if (!isAbsolute(path))
20
103
  throw new Refusal('invalid_handoff_ledger', 2);
21
- return resolve(path);
104
+ return unmanaged(resolve(path));
22
105
  }
23
106
  export function privateMessage(path) {
24
107
  const before = lstatSync(path);
@@ -111,7 +194,7 @@ async function settleCutoffEdge(budget) {
111
194
  class BeforeEffectRefused extends Error {
112
195
  }
113
196
  export async function prepareHandoff(options, path = ledgerPath(), correlationId, budget) {
114
- const ledger = new HandoffLedger(path);
197
+ const ledger = new HandoffLedger(unmanaged(path));
115
198
  let handoff;
116
199
  const value = await send({ ...options, dryRun: true, hooks: { resolved(context) {
117
200
  budget?.beforeEffect();
@@ -120,7 +203,7 @@ export async function prepareHandoff(options, path = ledgerPath(), correlationId
120
203
  return { value: { ...value, handoff }, exitCode: 0 };
121
204
  }
122
205
  export async function handoffSend(options, handoffOptions) {
123
- const ledger = new HandoffLedger(handoffOptions.ledgerPath ?? ledgerPath());
206
+ const ledger = new HandoffLedger(unmanaged(handoffOptions.ledgerPath ?? ledgerPath()));
124
207
  const budget = handoffOptions.budget ?? new HandoffBudget(handoffOptions.seconds ?? 30);
125
208
  let handoff, snapshot;
126
209
  let scope, queueScope, deliverySupported = false, stopped = false, operationId;
@@ -150,21 +233,7 @@ export async function handoffSend(options, handoffOptions) {
150
233
  const authorize = async () => { if (stopped)
151
234
  throw new Refusal('stopped_by_operator', 130); budget.beforeEffect(); handoff = await persist(() => { if (stopped)
152
235
  throw new Refusal('stopped_by_operator', 130); return ledger.commitEffect(handoff.correlationId, original, budget); }); fenced = true; ownWait(); };
153
- const verifyOwner = async (target, signal) => {
154
- if (stopped || signal?.aborted || budget.observationRemainingMs() < 1)
155
- return false;
156
- const worker = fileURLToPath(new URL('./handoff-writer-probe.js', import.meta.url));
157
- const result = await run(process.execPath, [worker, target.home, target.threadId, ...ownerArgs], { timeout: Math.min(800, budget.observationRemainingMs()), limit: 4096, env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
158
- if (signal?.aborted || stopped || result.code !== 0 || result.interrupted)
159
- return false;
160
- try {
161
- const value = JSON.parse(result.stdout);
162
- return value.schemaVersion === 1 && value.ok === true && Object.keys(value).every(key => ['schemaVersion', 'ok', 'generation'].includes(key)) && /^[0-9a-f]{64}$/.test(value.generation) && value.generation === target.generation;
163
- }
164
- catch {
165
- return false;
166
- }
167
- };
236
+ const verifyOwner = (target, signal) => retainedOwnerProbe(target, budget, ownerArgs, 'send', () => stopped, signal);
168
237
  const finish = (value, exitCode) => ({ value: { ...value, ...(handoff ? { handoff } : {}) }, exitCode });
169
238
  if (handoffOptions.waitFor)
170
239
  process.on('SIGINT', stop);
@@ -350,22 +419,7 @@ export async function waitForHandoff(ledger, id, goal, budget) {
350
419
  const ownWait = () => { if (operationId)
351
420
  handoff = ledger.operationStatus(id, operationId); };
352
421
  const ownerArgs = ownerProbeArgs(context?.qualification);
353
- const verifyOwner = async (scope, signal) => {
354
- if (stopped || signal.aborted || budget.observationRemainingMs() < 1)
355
- return false;
356
- const worker = fileURLToPath(new URL('./handoff-writer-probe.js', import.meta.url));
357
- const result = await run(process.execPath, [worker, scope.home, scope.threadId, ...ownerArgs], { timeout: Math.min(800, budget.observationRemainingMs()), limit: 4096, env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
358
- if (stopped || signal.aborted || result.code !== 0 || result.interrupted)
359
- return false;
360
- try {
361
- const value = JSON.parse(result.stdout);
362
- return value.schemaVersion === 1 && value.ok === true && Object.keys(value).every(key => ['schemaVersion', 'ok', 'generation'].includes(key)) &&
363
- /^[0-9a-f]{64}$/.test(value.generation) && value.generation === scope.generation;
364
- }
365
- catch {
366
- return false;
367
- }
368
- };
422
+ const verifyOwner = (scope, signal) => retainedOwnerProbe(scope, budget, ownerArgs, 'wait', () => stopped, signal);
369
423
  process.on('SIGINT', stop);
370
424
  try {
371
425
  handoff = await persist(() => ledger.beginWait(id, goal, budget, { observationSupported: context !== undefined }));
package/dist/help.js CHANGED
@@ -17,6 +17,18 @@ Transport:
17
17
  known online peers use their MagicDNS name, known offline peers are refused.
18
18
  --no-update-notice Suppress the opt-in cached update notice
19
19
  -h, --help Show command help`;
20
+ if (command === 'receipt')
21
+ return `Usage: session-peer receipt <operation> --json
22
+ init --state-dir DIR [--collector SOCKET] Explicitly create fresh private managed state
23
+ serve --state-dir DIR [--collector SOCKET] Start a foreground local collector; stop with Ctrl-C
24
+ respond --collector SOCKET --receipt - Read one private receipt from stdin; never prompt an agent
25
+ status|revoke --collector SOCKET --ledger-epoch UUID --correlation-id UUID
26
+ wait --collector SOCKET --ledger-epoch UUID --correlation-id UUID [--wait-timeout SECONDS]
27
+ Explicit POSIX local owner operations only; no automatic start, remote collector, migration or resend.
28
+ Only use separately permitted private stdin/FD tooling. Never put receipt capability data in argv,
29
+ environment, URI, shell command text, public output or sender/collector files.
30
+ Receipt evidence is delegated token possession, not model identity, consumption or completion.
31
+ Status/wait can retain private classifications; they never submit native messages.`;
20
32
  if (command === 'handoff' || command === 'ack')
21
33
  return `Usage: session-peer handoff init|prepare|status|wait|confirm --json
22
34
  init Initialize private POSIX sender ledger explicitly
@@ -31,6 +43,8 @@ Missing history never authorizes retry. Secrets must never be passed through arg
31
43
  if (command === 'list')
32
44
  return `Usage: session-peer list [options]
33
45
  List reachable Claude and saved Codex sessions. Listing is not send authorization.
46
+ On macOS, Claude includes bounded known Orca profiles unless CLAUDE_CONFIG_DIR or
47
+ ANTHROPIC_CONFIG_DIR selects one registry. Incomplete/conflicting inventory refuses send.
34
48
  --agent claude|codex Filter one agent (default: both)
35
49
  --codex-home HOME Pin Codex listing to one home
36
50
  --all Include stale Claude/archived Codex rows
@@ -63,7 +77,8 @@ TARGET: Claude name/PID, claude:NAME/PID, codex:UUID, or session-peer reply URI.
63
77
  Omit the body or use - for UTF-8 stdin. Only one body source is permitted.
64
78
  Unicode names use exact Unicode 14.0.0 default casefold; collisions require PID.
65
79
  --correlation-id UUID Use an already-prepared private handoff ID (opt-in)
66
- --request-ack Add handoff metadata; automated ACK currently unsupported
80
+ --request-ack Add handoff metadata; no implicit receipt bootstrap
81
+ --receipt-collector SOCKET Explicit local receipt bootstrap (requires --request-ack or ACK wait)
67
82
  --observe-delivery Request optional body-free observation (qualified routes only)
68
83
  --wait-for delivered|acknowledged Refuse before submission if required evidence is unsupported
69
84
  --wait-timeout SECONDS Total budget 1..60 (default 30, includes 5 s cleanup)
@@ -88,8 +103,9 @@ Usage: session-peer <command> [options]
88
103
  doctor Inspect read-only metadata and capabilities
89
104
  update --check Check npm for a newer version (no self-update)
90
105
  handoff / ack Opt-in private evidence operations (see handoff --help)
106
+ receipt Explicit local receipt collector and private handler operations
91
107
  --version Print exact runtime version
92
108
  --help, -h Show help; <command> --help for details
93
109
  ${common}
94
- No Relay server, MCP, wake, wait or automatic ACK support.`;
110
+ No Relay server, MCP or wake support. Receipts never imply automatic model ACK or permission to act.`;
95
111
  }
@@ -0,0 +1,10 @@
1
+ export declare const MACOS_ACL_LIMITS: Readonly<{
2
+ paths: 4481;
3
+ batchPaths: 128;
4
+ argumentBytes: 32768;
5
+ batchOutput: 262144;
6
+ totalOutput: 8388608;
7
+ batches: 128;
8
+ timeoutMs: 5000;
9
+ }>;
10
+ export declare function inspectMacosAcls(input: readonly string[]): 'clear' | 'acl' | 'unknown';
@@ -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.1";
2
+ export declare const VERSION_LINE = "session-peer 0.6.1 (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.1';
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 {};