session-peer 0.5.1 → 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.
- package/CONTRIBUTING.md +26 -0
- package/PARITY.md +134 -4
- package/README.ja.md +12 -8
- package/README.ko.md +12 -8
- package/README.md +12 -8
- package/README.zh-CN.md +12 -8
- package/RELEASING.md +142 -0
- package/VALIDATION.md +154 -2
- package/dist/app-server.d.ts +10 -2
- package/dist/app-server.js +115 -53
- package/dist/cli.js +54 -4
- package/dist/codex-storage.d.ts +46 -0
- package/dist/codex-storage.js +447 -0
- package/dist/diagnostics.js +23 -102
- package/dist/discovery.d.ts +32 -1
- package/dist/discovery.js +405 -89
- package/dist/handoff-operations.js +40 -10
- package/dist/help.js +18 -2
- package/dist/macos-acl.d.ts +10 -0
- package/dist/macos-acl.js +75 -0
- package/dist/output.js +6 -1
- package/dist/process.d.ts +1 -0
- package/dist/process.js +1 -1
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/receipt-collector.d.ts +12 -0
- package/dist/receipt-collector.js +283 -0
- package/dist/receipt-command.d.ts +10 -0
- package/dist/receipt-command.js +246 -0
- package/dist/receipt-producer.d.ts +7 -0
- package/dist/receipt-producer.js +107 -0
- package/dist/receipt-protocol.d.ts +219 -0
- package/dist/receipt-protocol.js +374 -0
- package/dist/receipt-send.d.ts +26 -0
- package/dist/receipt-send.js +375 -0
- package/dist/receipt-state.d.ts +89 -0
- package/dist/receipt-state.js +503 -0
- package/dist/receipt-store.d.ts +32 -0
- package/dist/receipt-store.js +286 -0
- package/dist/replies.js +3 -1
- package/dist/send.d.ts +14 -3
- package/dist/send.js +165 -63
- package/dist/skill-metadata.js +5 -3
- package/docs/api.md +155 -7
- package/docs/design/remote-deployment.md +8 -0
- package/docs/design/typescript-skill-compatibility.md +50 -0
- package/docs/guide.ja.md +47 -15
- package/docs/guide.ko.md +50 -19
- package/docs/guide.md +48 -16
- package/docs/guide.zh-CN.md +47 -15
- package/docs/shorthand.md +1 -1
- package/package.json +5 -3
|
@@ -11,13 +11,34 @@ import { metadataCapability, observeMetadata, resumeMetadataObservation, metadat
|
|
|
11
11
|
import { checkMessage, queueId, send } from './send.js';
|
|
12
12
|
import { Refusal } from './discovery.js';
|
|
13
13
|
import { HomeRefusal } from './writer.js';
|
|
14
|
-
import {
|
|
14
|
+
import { run, UnknownOutcome } from './process.js';
|
|
15
15
|
import { currentPlatform, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
|
|
16
|
+
import { codexStoragePin } from './codex-storage.js';
|
|
17
|
+
function unmanaged(path) {
|
|
18
|
+
// A managed v2 context has one collector writer. New legacy CLI paths must
|
|
19
|
+
// refuse before even creating an old lock file; historical v1 stays intact.
|
|
20
|
+
if (process.platform !== 'win32') {
|
|
21
|
+
for (const marker of ['managed.json', 'collector.lock']) {
|
|
22
|
+
try {
|
|
23
|
+
lstatSync(join(path, marker));
|
|
24
|
+
throw new Refusal('receipt_managed_context_required', 1);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? '')) {
|
|
28
|
+
if (error instanceof Refusal)
|
|
29
|
+
throw error;
|
|
30
|
+
throw new Refusal('handoff_history_unavailable', 1);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return path;
|
|
36
|
+
}
|
|
16
37
|
export function ledgerPath() {
|
|
17
38
|
const path = process.env.SESSION_PEER_HANDOFF_HOME ?? join(homedir(), '.local', 'state', 'session-peer-ts', 'handoff');
|
|
18
39
|
if (!isAbsolute(path))
|
|
19
40
|
throw new Refusal('invalid_handoff_ledger', 2);
|
|
20
|
-
return resolve(path);
|
|
41
|
+
return unmanaged(resolve(path));
|
|
21
42
|
}
|
|
22
43
|
export function privateMessage(path) {
|
|
23
44
|
const before = lstatSync(path);
|
|
@@ -55,7 +76,8 @@ export function privateMessage(path) {
|
|
|
55
76
|
}
|
|
56
77
|
}
|
|
57
78
|
function binding(context, message, destination = hostname()) {
|
|
58
|
-
|
|
79
|
+
const { binary: _privateBinary, ...retained } = context;
|
|
80
|
+
return { ...retained, destination, payloadDigest: payloadDigest(message) };
|
|
59
81
|
}
|
|
60
82
|
export function correlationEnvelope(message, id) {
|
|
61
83
|
if (!canonicalId(id))
|
|
@@ -109,7 +131,7 @@ async function settleCutoffEdge(budget) {
|
|
|
109
131
|
class BeforeEffectRefused extends Error {
|
|
110
132
|
}
|
|
111
133
|
export async function prepareHandoff(options, path = ledgerPath(), correlationId, budget) {
|
|
112
|
-
const ledger = new HandoffLedger(path);
|
|
134
|
+
const ledger = new HandoffLedger(unmanaged(path));
|
|
113
135
|
let handoff;
|
|
114
136
|
const value = await send({ ...options, dryRun: true, hooks: { resolved(context) {
|
|
115
137
|
budget?.beforeEffect();
|
|
@@ -118,7 +140,7 @@ export async function prepareHandoff(options, path = ledgerPath(), correlationId
|
|
|
118
140
|
return { value: { ...value, handoff }, exitCode: 0 };
|
|
119
141
|
}
|
|
120
142
|
export async function handoffSend(options, handoffOptions) {
|
|
121
|
-
const ledger = new HandoffLedger(handoffOptions.ledgerPath ?? ledgerPath());
|
|
143
|
+
const ledger = new HandoffLedger(unmanaged(handoffOptions.ledgerPath ?? ledgerPath()));
|
|
122
144
|
const budget = handoffOptions.budget ?? new HandoffBudget(handoffOptions.seconds ?? 30);
|
|
123
145
|
let handoff, snapshot;
|
|
124
146
|
let scope, queueScope, deliverySupported = false, stopped = false, operationId;
|
|
@@ -176,10 +198,12 @@ export async function handoffSend(options, handoffOptions) {
|
|
|
176
198
|
// Account for the fixed correlation envelope before allocating an intent.
|
|
177
199
|
checkMessage(correlationEnvelope(options.message, '00000000-0000-4000-8000-000000000000'), context.agent === 'codex');
|
|
178
200
|
const wantsDelivery = handoffOptions.observeDelivery || handoffOptions.waitFor === 'delivered';
|
|
179
|
-
if (wantsDelivery && context.agent === 'codex' && context.home && context.generation && budget.observationRemainingMs() > 0) {
|
|
201
|
+
if (!options.dryRun && wantsDelivery && context.agent === 'codex' && context.home && context.generation && budget.observationRemainingMs() > 0) {
|
|
180
202
|
scope = { home: context.home, threadId: context.target, generation: context.generation };
|
|
181
203
|
queueScope = { codexHome: context.home, threadId: context.target, generation: context.generation, ownerIdentity: context.writerIdentity };
|
|
182
|
-
|
|
204
|
+
if (!context.binary)
|
|
205
|
+
throw new Refusal('codex_storage_loader_unverifiable', 1);
|
|
206
|
+
const version = await run(context.binary, ['--version'], { timeout: Math.min(1000, budget.observationRemainingMs()), limit: 4096 });
|
|
183
207
|
const nativeVersion = !version.interrupted && version.code === 0 ? version.stdout.trim().replace(/^codex-cli /, '') : '';
|
|
184
208
|
// Exact host platform and native version select one profile row, or none.
|
|
185
209
|
qualification = observationQualification(nativeVersion, currentPlatform(), handoffOptions.remote === true);
|
|
@@ -198,12 +222,18 @@ export async function handoffSend(options, handoffOptions) {
|
|
|
198
222
|
return correlationEnvelope(options.message, handoff.correlationId);
|
|
199
223
|
},
|
|
200
224
|
beforeEffect: authorize,
|
|
201
|
-
|
|
225
|
+
codexRoute: () => deliverySupported ? 'owned_app_server' : 'ordinary',
|
|
226
|
+
async submitCodex(context, message, storage) {
|
|
202
227
|
if (!deliverySupported) {
|
|
203
228
|
// Best-effort unsupported is chosen before ANY app-server attempt.
|
|
229
|
+
await storage.revalidate(false);
|
|
204
230
|
await authorize();
|
|
231
|
+
await storage.revalidate(false);
|
|
205
232
|
const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'CODEX_SQLITE_HOME'));
|
|
206
|
-
|
|
233
|
+
storage.finalCheck(false);
|
|
234
|
+
const timeout = Math.max(1, budget.observationRemainingMs());
|
|
235
|
+
budget.beforeEffect();
|
|
236
|
+
const done = await run(storage.binary, ['queue', '--thread', context.target, `--message=${message}`, '-c', codexStoragePin(context.home)], { env: { ...inherited, CODEX_HOME: context.home, PWD: storage.cwd }, cwd: storage.cwd, timeout });
|
|
207
237
|
if (!done.spawned)
|
|
208
238
|
throw new Refusal('native_spawn_failed', 1);
|
|
209
239
|
if (done.interrupted || done.code !== 0)
|
|
@@ -212,7 +242,7 @@ export async function handoffSend(options, handoffOptions) {
|
|
|
212
242
|
return { queueId: receipt, clientUserMessageId: handoff.correlationId };
|
|
213
243
|
}
|
|
214
244
|
try {
|
|
215
|
-
return await nativeQueueOnce({ binary:
|
|
245
|
+
return await nativeQueueOnce({ binary: storage.binary, scope: queueScope, message, clientUserMessageId: handoff.correlationId, deadlineMs: budget.cutoff, verifyOwner: async () => verifyOwner(scope), beforeEffect: authorize, verifyStorage: () => storage.revalidate(true), verifyStorageSync: () => storage.finalCheck(true) });
|
|
216
246
|
}
|
|
217
247
|
catch (error) {
|
|
218
248
|
if (error instanceof AppServerFault && error.attempted)
|
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;
|
|
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
|
|
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.' :
|
|
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.`);
|
package/dist/process.d.ts
CHANGED
package/dist/process.js
CHANGED
|
@@ -63,7 +63,7 @@ export function run(binary, args, options = {}) {
|
|
|
63
63
|
let stdout = '', stderr = '', bytes = 0, stderrBytes = 0, spawned = false, interrupted = false, finished = false, stopped = false;
|
|
64
64
|
let stopReason;
|
|
65
65
|
const chunks = [], outputDecoder = new StringDecoder('utf8'), diagnosticDecoder = new StringDecoder('utf8');
|
|
66
|
-
const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'], detached: posix });
|
|
66
|
+
const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, cwd: options.cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: posix });
|
|
67
67
|
const release = () => {
|
|
68
68
|
if (child.pid === undefined || !groups.delete(child.pid) || groups.size)
|
|
69
69
|
return;
|
package/dist/protocol.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
2
|
-
export declare const VERSION_LINE = "session-peer 0.
|
|
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.
|
|
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 {};
|