@zieglar/pi-chat-exchange 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/dist/bin/ce-native.js +119 -0
- package/dist/bin/mcp-stdio.js +196 -0
- package/dist/control/debug-log.js +67 -0
- package/dist/control/mcp/debug-transport.js +48 -0
- package/dist/control/mcp/messaging-tools.js +278 -0
- package/dist/control/mcp/ping.js +43 -0
- package/dist/control/mcp/server.js +153 -0
- package/dist/core/authorization.js +32 -0
- package/dist/core/reference.js +32 -0
- package/dist/core/rules.js +468 -0
- package/dist/endpoints/pi/contract.js +2 -0
- package/dist/endpoints/pi/session-host.js +39 -0
- package/dist/host/bound-endpoint.js +176 -0
- package/dist/host/endpoint-host.js +839 -0
- package/dist/host/mcp-binding-config.js +209 -0
- package/dist/host/ownership-recovery.js +257 -0
- package/dist/index.js +11 -0
- package/dist/protocol/capabilities.js +46 -0
- package/dist/protocol/endpoint-capabilities.js +15 -0
- package/dist/protocol/entities.js +185 -0
- package/dist/protocol/formats.js +13 -0
- package/dist/protocol/idempotency.js +93 -0
- package/dist/protocol/identity.js +130 -0
- package/dist/protocol/index.js +8 -0
- package/dist/protocol/lifecycle.js +125 -0
- package/dist/protocol/outcomes.js +55 -0
- package/dist/runtime/desktop-manifest.js +65 -0
- package/dist/runtime/diagnostics.js +34 -0
- package/dist/runtime/executables.js +217 -0
- package/dist/runtime/native-readiness.js +131 -0
- package/dist/storage/capability.js +221 -0
- package/dist/storage/connection.js +95 -0
- package/dist/storage/creation-request.js +176 -0
- package/dist/storage/creation.js +553 -0
- package/dist/storage/current-schema.js +397 -0
- package/dist/storage/delivery-ack.js +177 -0
- package/dist/storage/errors.js +9 -0
- package/dist/storage/filesystem.js +171 -0
- package/dist/storage/inbox-discovery.js +135 -0
- package/dist/storage/messaging.js +156 -0
- package/dist/storage/migration.js +258 -0
- package/dist/storage/native-artifact.js +234 -0
- package/dist/storage/native-compat.js +65 -0
- package/dist/storage/ownership.js +789 -0
- package/dist/storage/participant-identity.js +127 -0
- package/dist/storage/participant.js +700 -0
- package/dist/storage/recovery.js +99 -0
- package/dist/storage/runtime.js +256 -0
- package/dist/storage/schema.js +556 -0
- package/dist/storage/session-state.js +75 -0
- package/dist/storage/sqlite-driver-node.js +66 -0
- package/dist/storage/sqlite-driver-rust.js +121 -0
- package/dist/storage/sqlite-driver-selection.js +86 -0
- package/dist/storage/sqlite-driver.js +4 -0
- package/dist/storage/store.js +450 -0
- package/dist/storage/transaction.js +196 -0
- package/dist/storage/trust-root.js +164 -0
- package/dist/tunnel/background-manager.js +1727 -0
- package/dist/tunnel/codes.js +79 -0
- package/dist/tunnel/health.js +75 -0
- package/dist/tunnel/keychain.js +526 -0
- package/dist/tunnel/managed-binding.js +454 -0
- package/dist/tunnel/manager-panel.js +249 -0
- package/dist/tunnel/manager-ui.js +341 -0
- package/dist/tunnel/manager.js +372 -0
- package/dist/tunnel/messaging-activation-ui.js +85 -0
- package/dist/tunnel/messaging-config.js +246 -0
- package/dist/tunnel/multi-session-admission.js +31 -0
- package/dist/tunnel/multi-session-policy.js +314 -0
- package/dist/tunnel/offline-client.js +104 -0
- package/dist/tunnel/profile.js +319 -0
- package/dist/tunnel/redact.js +9 -0
- package/dist/tunnel/secure-input.js +318 -0
- package/dist/tunnel/session-process-mutex.js +338 -0
- package/dist/tunnel/setup-ui.js +443 -0
- package/dist/tunnel/setup.js +734 -0
- package/dist/tunnel/state.js +127 -0
- package/native/tunnel-keychain.swift +432 -0
- package/package.json +65 -4
- package/pi-extension/allowlist.example.json +11 -0
- package/pi-extension/index.ts +2346 -0
- package/pi-extension/multi-session-commands.ts +93 -0
- package/pi-extension/multi-session-runtime.ts +75 -0
- package/pi-extension/tui-keys.ts +40 -0
- package/scripts/reconcile-session-process-mutex.mjs +262 -0
- package/scripts/recover-stale-ownership.mjs +91 -0
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CE custom masked secret input hosted through Pi 1.3.0 `ctx.ui.custom()`.
|
|
3
|
+
* Pi 1.3.0 does not provide a native PasswordInput / SecretInput.
|
|
4
|
+
*
|
|
5
|
+
* Scope and non-goals (PHASE-A-DESIGN-v2 §3, B1.1 handoff):
|
|
6
|
+
* - The secret is captured by a dedicated `ui.custom` component and handed to
|
|
7
|
+
* exactly ONE sink: the injected credential writer. It is never passed to
|
|
8
|
+
* `ui.input`, the main editor, `pasteToEditor`, `notify`, `sendMessage`,
|
|
9
|
+
* `appendEntry`, a log, a tool result, or the resolved outcome value.
|
|
10
|
+
* - Rendering emits fixed labels plus a mask only. Errors are fixed strings;
|
|
11
|
+
* an underlying writer failure (which can embed the secret in its message)
|
|
12
|
+
* is suppressed down to a closed `CE_TUNNEL_*` code.
|
|
13
|
+
* - Pi 1.3.0 `ui.custom` has NO built-in abort or timeout (verified against
|
|
14
|
+
* dist/core/extensions/types.d.ts:121 and the interactive-mode `done`
|
|
15
|
+
* handling), so this module implements both and keeps ONE idempotent finish
|
|
16
|
+
* for submit / Escape / Ctrl-C / timeout / external abort / dispose.
|
|
17
|
+
* - `ctx.mode === "tui"` is required: `hasUI` is also true for RPC, where a
|
|
18
|
+
* custom terminal component cannot be shown (docs/extensions.md, "UI and
|
|
19
|
+
* modes"). Non-TUI never silently degrades to a plaintext path; it refuses
|
|
20
|
+
* with `CE_TUNNEL_INPUT_UNAVAILABLE`.
|
|
21
|
+
*
|
|
22
|
+
* Honest limitation: masking prevents shoulder-surfing and terminal echo. It
|
|
23
|
+
* is NOT memory erasure. JavaScript strings are immutable, so this module
|
|
24
|
+
* cannot promise complete zeroization; it only drops its own references and
|
|
25
|
+
* clears its buffer at finish/dispose. Terminal paste buffers, crash dumps,
|
|
26
|
+
* and terminal recording remain independent exposure surfaces. Malicious
|
|
27
|
+
* same-process extensions and process-level observation are not isolated by it.
|
|
28
|
+
*/
|
|
29
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
30
|
+
import { TunnelRefusal } from "./codes.js";
|
|
31
|
+
/** Fixed policy. Not configurable from commands, profiles, or the model. */
|
|
32
|
+
export const SECURE_INPUT_LIMITS = Object.freeze({
|
|
33
|
+
/** Maximum accepted secret length in characters. */
|
|
34
|
+
maxLength: 512,
|
|
35
|
+
/** Default interaction timeout. */
|
|
36
|
+
defaultTimeoutMs: 120_000,
|
|
37
|
+
/** Hard cap on buffered bracketed-paste bytes before the paste is refused. */
|
|
38
|
+
maxPasteChars: 4_096,
|
|
39
|
+
});
|
|
40
|
+
const LABEL = "API key (masked; not echoed, not logged)";
|
|
41
|
+
const HINT = "Enter submits · Esc/Ctrl-C cancels · Backspace corrects · Ctrl-U resets";
|
|
42
|
+
const REJECTED = "input rejected: 1-512 visible ASCII characters, no spaces";
|
|
43
|
+
const MASK_CHAR = "•";
|
|
44
|
+
const PROMPT = "> ";
|
|
45
|
+
const PASTE_START = "\x1b[200~";
|
|
46
|
+
const PASTE_END = "\x1b[201~";
|
|
47
|
+
/** Visible ASCII only: no space, no control byte, no non-ASCII. */
|
|
48
|
+
function isAcceptable(text) {
|
|
49
|
+
for (const char of text) {
|
|
50
|
+
const code = char.codePointAt(0) ?? 0;
|
|
51
|
+
if (code < 0x21 || code > 0x7e)
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
function truncate(line, width) {
|
|
57
|
+
if (width <= 0)
|
|
58
|
+
return "";
|
|
59
|
+
return line.length <= width ? line : line.slice(0, width);
|
|
60
|
+
}
|
|
61
|
+
const CANCELLED_USER = Object.freeze({ kind: "cancelled", reason: "user" });
|
|
62
|
+
const CANCELLED_ABORTED = Object.freeze({ kind: "cancelled", reason: "aborted" });
|
|
63
|
+
class SecretPrompt {
|
|
64
|
+
tui;
|
|
65
|
+
done;
|
|
66
|
+
buffer = "";
|
|
67
|
+
pasteBuffer = "";
|
|
68
|
+
inPaste = false;
|
|
69
|
+
pasteOverflow = false;
|
|
70
|
+
rejected = false;
|
|
71
|
+
finished = false;
|
|
72
|
+
disposed = false;
|
|
73
|
+
timer;
|
|
74
|
+
deferredAbort;
|
|
75
|
+
abortListener;
|
|
76
|
+
signal;
|
|
77
|
+
keys;
|
|
78
|
+
preamble;
|
|
79
|
+
constructor(tui, done, options) {
|
|
80
|
+
this.tui = tui;
|
|
81
|
+
this.done = done;
|
|
82
|
+
this.keys = options.keys;
|
|
83
|
+
this.preamble = options.preamble ?? [];
|
|
84
|
+
const timeoutMs = options.timeoutMs ?? SECURE_INPUT_LIMITS.defaultTimeoutMs;
|
|
85
|
+
this.timer = setTimeout(() => this.finish({ kind: "cancelled", reason: "timeout" }), Math.max(0, timeoutMs));
|
|
86
|
+
this.timer.unref?.();
|
|
87
|
+
this.signal = options.signal;
|
|
88
|
+
if (this.signal !== undefined) {
|
|
89
|
+
const onAbort = () => this.finish({ kind: "cancelled", reason: "aborted" });
|
|
90
|
+
if (this.signal.aborted) {
|
|
91
|
+
// Never call `done` synchronously inside the factory: the runtime has
|
|
92
|
+
// not installed (and therefore cannot dispose) this component yet.
|
|
93
|
+
this.deferredAbort = setTimeout(onAbort, 0);
|
|
94
|
+
this.deferredAbort.unref?.();
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
this.abortListener = onAbort;
|
|
98
|
+
this.signal.addEventListener("abort", onAbort, { once: true });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
render(width) {
|
|
103
|
+
// The preamble is fixed caller text, but it is sanitized anyway: render
|
|
104
|
+
// lines must never carry terminal control sequences.
|
|
105
|
+
const lines = [...this.preamble.map((line) => truncate(sanitizeTerminalText(line), width)), truncate(LABEL, width), truncate(PROMPT + MASK_CHAR.repeat(this.buffer.length), width), truncate(HINT, width)];
|
|
106
|
+
if (this.rejected)
|
|
107
|
+
lines.push(truncate(REJECTED, width));
|
|
108
|
+
return lines;
|
|
109
|
+
}
|
|
110
|
+
invalidate() {
|
|
111
|
+
// Nothing is cached: every line is rebuilt from fixed text plus a mask.
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Dispose is an OUTCOME, not just a cleanup: the runtime's `ui.custom`
|
|
115
|
+
* promise only settles through `done`, so a component that is unmounted by a
|
|
116
|
+
* session teardown (or any other external dispose) before submit/cancel must
|
|
117
|
+
* still finish exactly once. Not doing so left the caller awaiting forever.
|
|
118
|
+
*
|
|
119
|
+
* This stays safe when the runtime disposes re-entrantly from inside `done`:
|
|
120
|
+
* `finish` flips `finished` BEFORE calling `done`, so the nested dispose is a
|
|
121
|
+
* pure cleanup and `done` is never invoked twice.
|
|
122
|
+
*/
|
|
123
|
+
dispose() {
|
|
124
|
+
this.disposed = true;
|
|
125
|
+
this.finish({ kind: "cancelled", reason: "aborted" });
|
|
126
|
+
this.buffer = "";
|
|
127
|
+
this.pasteBuffer = "";
|
|
128
|
+
this.inPaste = false;
|
|
129
|
+
this.clearResources();
|
|
130
|
+
}
|
|
131
|
+
handleInput(data) {
|
|
132
|
+
if (this.finished || this.disposed || data === "")
|
|
133
|
+
return;
|
|
134
|
+
// A standalone cancel key remains an action even if a paste never closes.
|
|
135
|
+
// Control bytes inside a framed paste are content and fail atomic validation.
|
|
136
|
+
// The native helper uses a substring heuristic: scope it to terminal
|
|
137
|
+
// sequences outside paste so valid ASCII such as ":3u" is never dropped.
|
|
138
|
+
if (!this.inPaste && data.startsWith("\x1b") && this.keys.isKeyRelease(data))
|
|
139
|
+
return;
|
|
140
|
+
if (this.keys.matches(data, this.keys.escape) || this.keys.matches(data, this.keys.ctrlC)) {
|
|
141
|
+
this.finish(CANCELLED_USER);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (this.inPaste || data.includes(PASTE_START)) {
|
|
145
|
+
this.handlePasteChunk(data);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (this.keys.matches(data, this.keys.enter) || data === "\n") {
|
|
149
|
+
this.submit();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (this.keys.matches(data, this.keys.backspace) || data === "\b") {
|
|
153
|
+
this.buffer = this.buffer.slice(0, -1);
|
|
154
|
+
this.rejected = false;
|
|
155
|
+
this.requestRender();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (this.keys.matches(data, this.keys.ctrlU)) {
|
|
159
|
+
this.buffer = "";
|
|
160
|
+
this.rejected = false;
|
|
161
|
+
this.requestRender();
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const printable = this.keys.decodePrintable(data);
|
|
165
|
+
// Ignore navigation/modifier sequences, never insert their escape payload.
|
|
166
|
+
if (data.startsWith("\x1b") && printable === undefined)
|
|
167
|
+
return;
|
|
168
|
+
this.append(printable ?? data);
|
|
169
|
+
}
|
|
170
|
+
handlePasteChunk(data) {
|
|
171
|
+
let chunk = data;
|
|
172
|
+
if (!this.inPaste) {
|
|
173
|
+
this.inPaste = true;
|
|
174
|
+
this.pasteBuffer = "";
|
|
175
|
+
this.pasteOverflow = false;
|
|
176
|
+
chunk = chunk.slice(chunk.indexOf(PASTE_START) + PASTE_START.length);
|
|
177
|
+
}
|
|
178
|
+
const endIndex = (this.pasteBuffer + chunk).indexOf(PASTE_END);
|
|
179
|
+
if (endIndex === -1) {
|
|
180
|
+
if (this.pasteBuffer.length + chunk.length > SECURE_INPUT_LIMITS.maxPasteChars) {
|
|
181
|
+
// Keep consuming until the frame closes, but never accept the content.
|
|
182
|
+
this.pasteOverflow = true;
|
|
183
|
+
this.pasteBuffer = "";
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
this.pasteBuffer += chunk;
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const combined = this.pasteBuffer + chunk;
|
|
190
|
+
const content = combined.slice(0, endIndex);
|
|
191
|
+
const remaining = combined.slice(endIndex + PASTE_END.length);
|
|
192
|
+
const overflowed = this.pasteOverflow;
|
|
193
|
+
this.pasteBuffer = "";
|
|
194
|
+
this.inPaste = false;
|
|
195
|
+
this.pasteOverflow = false;
|
|
196
|
+
// Atomic validation: a paste is accepted as ONE unit or not at all. A
|
|
197
|
+
// pasted newline is content, never a submit.
|
|
198
|
+
if (overflowed || !this.acceptPaste(content)) {
|
|
199
|
+
this.rejected = true;
|
|
200
|
+
this.requestRender();
|
|
201
|
+
}
|
|
202
|
+
if (remaining !== "")
|
|
203
|
+
this.handleInput(remaining);
|
|
204
|
+
}
|
|
205
|
+
acceptPaste(content) {
|
|
206
|
+
if (this.rejected || content === "" || !isAcceptable(content))
|
|
207
|
+
return false;
|
|
208
|
+
if (this.buffer.length + content.length > SECURE_INPUT_LIMITS.maxLength)
|
|
209
|
+
return false;
|
|
210
|
+
this.buffer += content;
|
|
211
|
+
this.rejected = false;
|
|
212
|
+
this.requestRender();
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
append(data) {
|
|
216
|
+
// Never silently strip invalid characters or truncate a credential. Reject
|
|
217
|
+
// the whole event and require an explicit correction/reset before submit.
|
|
218
|
+
if (this.rejected || !isAcceptable(data) || this.buffer.length + data.length > SECURE_INPUT_LIMITS.maxLength) {
|
|
219
|
+
this.rejected = true;
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
this.buffer += data;
|
|
223
|
+
}
|
|
224
|
+
this.requestRender();
|
|
225
|
+
}
|
|
226
|
+
submit() {
|
|
227
|
+
if (this.rejected || this.buffer.length === 0) {
|
|
228
|
+
this.rejected = true;
|
|
229
|
+
this.requestRender();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const secret = this.buffer;
|
|
233
|
+
this.finish({ kind: "submitted", secret });
|
|
234
|
+
}
|
|
235
|
+
finish(result) {
|
|
236
|
+
if (this.finished)
|
|
237
|
+
return;
|
|
238
|
+
this.finished = true;
|
|
239
|
+
this.buffer = "";
|
|
240
|
+
this.pasteBuffer = "";
|
|
241
|
+
this.clearResources();
|
|
242
|
+
this.done(result);
|
|
243
|
+
}
|
|
244
|
+
clearResources() {
|
|
245
|
+
if (this.timer !== undefined) {
|
|
246
|
+
clearTimeout(this.timer);
|
|
247
|
+
this.timer = undefined;
|
|
248
|
+
}
|
|
249
|
+
if (this.deferredAbort !== undefined) {
|
|
250
|
+
clearTimeout(this.deferredAbort);
|
|
251
|
+
this.deferredAbort = undefined;
|
|
252
|
+
}
|
|
253
|
+
if (this.abortListener !== undefined) {
|
|
254
|
+
this.signal?.removeEventListener("abort", this.abortListener);
|
|
255
|
+
this.abortListener = undefined;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
requestRender() {
|
|
259
|
+
try {
|
|
260
|
+
this.tui.requestRender?.();
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// Rendering is advisory; a render failure must not leak or retry input.
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function refused(code) {
|
|
268
|
+
return Object.freeze({ status: "refused", code });
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Capture one credential through a masked TUI component and hand it to
|
|
272
|
+
* `writer` only. The returned outcome never carries the secret.
|
|
273
|
+
*/
|
|
274
|
+
export async function captureTunnelSecret(ctx, writer, options) {
|
|
275
|
+
if (ctx.mode !== "tui")
|
|
276
|
+
return refused("CE_TUNNEL_INPUT_UNAVAILABLE");
|
|
277
|
+
const custom = ctx.ui?.custom;
|
|
278
|
+
if (typeof custom !== "function")
|
|
279
|
+
return refused("CE_TUNNEL_INPUT_UNAVAILABLE");
|
|
280
|
+
// The runtime surface is generic (`custom<T>`); this adapter pins T to the
|
|
281
|
+
// module-private `Finish` so the secret type never escapes this file.
|
|
282
|
+
// SAFETY: `custom<T>` resolves with exactly the value its factory hands to
|
|
283
|
+
// `done`. The only factory installed here is `SecretPrompt`, whose `done`
|
|
284
|
+
// parameter is `(result: Finish) => void`, so the resolved value is always a
|
|
285
|
+
// `Finish`. TypeScript cannot bind the caller-chosen T through
|
|
286
|
+
// `Function.call`, hence the explicit instantiation.
|
|
287
|
+
const open = custom;
|
|
288
|
+
let finish;
|
|
289
|
+
try {
|
|
290
|
+
finish = await open.call(ctx.ui, (tui, _theme, _keybindings, done) => new SecretPrompt(tui, done, options));
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// The component surface itself failed; no secret can have been captured.
|
|
294
|
+
return refused("CE_TUNNEL_INPUT_UNAVAILABLE");
|
|
295
|
+
}
|
|
296
|
+
// Commit boundary: after the UI resolves but before writer.store starts, an
|
|
297
|
+
// abort still prevents persistence. Once writer.store is entered, cancellation
|
|
298
|
+
// cannot claim rollback; the caller waits for that completion barrier.
|
|
299
|
+
if (options.signal?.aborted) {
|
|
300
|
+
finish = CANCELLED_ABORTED;
|
|
301
|
+
return Object.freeze({ status: "cancelled", reason: "aborted" });
|
|
302
|
+
}
|
|
303
|
+
if (finish.kind === "cancelled")
|
|
304
|
+
return Object.freeze({ status: "cancelled", reason: finish.reason });
|
|
305
|
+
try {
|
|
306
|
+
await writer.store(finish.secret);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
// The underlying failure may embed the secret; only a closed code escapes.
|
|
310
|
+
return refused(error instanceof TunnelRefusal ? error.code : "CE_TUNNEL_KEYCHAIN_UNAVAILABLE");
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
// Drop this module's own reference. JS strings cannot be wiped.
|
|
314
|
+
finish = CANCELLED_USER;
|
|
315
|
+
}
|
|
316
|
+
return Object.freeze({ status: "stored" });
|
|
317
|
+
}
|
|
318
|
+
//# sourceMappingURL=secure-input.js.map
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/** Additional local exclusion, NEVER CE authority or expired-Owner takeover.
|
|
2
|
+
*
|
|
3
|
+
* Append-only slots avoid the check-then-unlink retirement race entirely. An
|
|
4
|
+
* exclusive mkdir claims the next slot; its owner and immutable release receipt
|
|
5
|
+
* are retained (only explicit drained local transfer may replace an owner). No automatic dead-marker reclamation is provided (even proven
|
|
6
|
+
* dead processes require offline operator reconciliation). Partial/unknown files
|
|
7
|
+
* block. This deliberately trades availability/disk growth for safe exclusion.
|
|
8
|
+
*
|
|
9
|
+
* Composition must wrap EVERY operation and heartbeat in run(), close admission,
|
|
10
|
+
* stop heartbeat scheduling, await drain(), then either explicitly transfer the
|
|
11
|
+
* still-attached CE handle OR perform CE end and release its confirmed result.
|
|
12
|
+
* Uncertain cleanup/release latches forever and retains the marker. Transfer is
|
|
13
|
+
* an explicit local object operation, never inferred from matching PIDs.
|
|
14
|
+
*/
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
17
|
+
import { spawnSync } from "node:child_process";
|
|
18
|
+
import { dirname, isAbsolute, join, normalize, parse } from "node:path";
|
|
19
|
+
const processToken = randomUUID();
|
|
20
|
+
const refused = () => Object.assign(new Error("CE_SESSION_PROCESS_MUTEX_REFUSED"), { code: "CE_SESSION_PROCESS_MUTEX_REFUSED" });
|
|
21
|
+
const missing = (e) => e.code === "ENOENT";
|
|
22
|
+
function same(a, b) { return a.dev === b.dev && a.ino === b.ino; }
|
|
23
|
+
/** Fixed command/arguments and minimal environment; unknown is never proof.
|
|
24
|
+
* No PID reuse/death inference is needed because this module never reclaims. */
|
|
25
|
+
function inspectSelf() {
|
|
26
|
+
const result = spawnSync("/bin/ps", ["-p", String(process.pid), "-o", "lstart="], { encoding: "utf8", timeout: 5_000, maxBuffer: 4096, env: { PATH: "/usr/bin:/bin", LC_ALL: "C" } });
|
|
27
|
+
const birth = result.stdout?.trim();
|
|
28
|
+
return result.status === 0 && birth !== undefined && /^\w{3}\s+\w{3}\s+\d+\s+\d\d:\d\d:\d\d\s+\d{4}$/.test(birth) ? birth : undefined;
|
|
29
|
+
}
|
|
30
|
+
/** Validate all ancestors, rejecting symlink aliases and writable non-sticky
|
|
31
|
+
* parents. Root-owned sticky temporary ancestors are permitted; the Store and
|
|
32
|
+
* mutex directories themselves must be private, owned by the effective UID.
|
|
33
|
+
* Same-UID malicious modification is not an authority boundary; every later
|
|
34
|
+
* check nevertheless detects inode/path/marker replacement and latches. */
|
|
35
|
+
function directoryChain(path) {
|
|
36
|
+
if (!isAbsolute(path) || normalize(path) !== path || fs.realpathSync(path) !== path)
|
|
37
|
+
throw refused();
|
|
38
|
+
const chain = new Map();
|
|
39
|
+
let current = path;
|
|
40
|
+
for (;;) {
|
|
41
|
+
const s = fs.lstatSync(current);
|
|
42
|
+
const stickyRoot = s.uid === 0 && (s.mode & 0o1000) !== 0;
|
|
43
|
+
if (!s.isDirectory() || s.isSymbolicLink() || (!stickyRoot && (s.mode & 0o022) !== 0) || (s.uid !== 0 && s.uid !== process.geteuid?.()))
|
|
44
|
+
throw refused();
|
|
45
|
+
chain.set(current, { dev: s.dev, ino: s.ino });
|
|
46
|
+
if (current === parse(current).root)
|
|
47
|
+
break;
|
|
48
|
+
current = dirname(current);
|
|
49
|
+
}
|
|
50
|
+
return chain;
|
|
51
|
+
}
|
|
52
|
+
function privateDir(path) {
|
|
53
|
+
const s = fs.lstatSync(path);
|
|
54
|
+
if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.geteuid?.() || (s.mode & 0o7777) !== 0o700)
|
|
55
|
+
throw refused();
|
|
56
|
+
}
|
|
57
|
+
function mkdir(path) {
|
|
58
|
+
try {
|
|
59
|
+
fs.mkdirSync(path, { mode: 0o700 });
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (e.code !== "EEXIST")
|
|
63
|
+
throw e;
|
|
64
|
+
}
|
|
65
|
+
privateDir(path);
|
|
66
|
+
}
|
|
67
|
+
function read(path) {
|
|
68
|
+
const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
69
|
+
try {
|
|
70
|
+
const s = fs.fstatSync(fd);
|
|
71
|
+
if (!s.isFile() || s.uid !== process.geteuid?.() || (s.mode & 0o7777) !== 0o600 || s.nlink !== 1 || s.size < 1 || s.size > 4096)
|
|
72
|
+
throw refused();
|
|
73
|
+
const bytes = fs.readFileSync(fd, "utf8");
|
|
74
|
+
if (!same(s, fs.lstatSync(path)))
|
|
75
|
+
throw refused();
|
|
76
|
+
return { bytes, identity: { dev: s.dev, ino: s.ino } };
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
fs.closeSync(fd);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function write(path, bytes) {
|
|
83
|
+
const fd = fs.openSync(path, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
84
|
+
try {
|
|
85
|
+
fs.writeFileSync(fd, bytes, "utf8");
|
|
86
|
+
fs.fsyncSync(fd);
|
|
87
|
+
return fs.fstatSync(fd);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
fs.closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function syncDir(path) {
|
|
94
|
+
const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
95
|
+
try {
|
|
96
|
+
fs.fsyncSync(fd);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
fs.closeSync(fd);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function absent(path) {
|
|
103
|
+
try {
|
|
104
|
+
fs.lstatSync(path);
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
if (missing(e))
|
|
109
|
+
return true;
|
|
110
|
+
throw e;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
export function acquireSessionProcessMutex(options) {
|
|
114
|
+
try {
|
|
115
|
+
return acquire(options);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
throw refused();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function acquire(options) {
|
|
122
|
+
// Copy trusted input so caller mutation cannot redirect later ownership checks.
|
|
123
|
+
const store = { ...options.store };
|
|
124
|
+
const endpointId = options.endpointId;
|
|
125
|
+
const runtimeSessionId = options.runtimeSessionId;
|
|
126
|
+
const inspect = options.inspectSelf ?? inspectSelf;
|
|
127
|
+
for (const value of [endpointId, runtimeSessionId, store.file]) {
|
|
128
|
+
if (typeof value !== "string" || !value.length || value.length > 256 || /[\u0000-\u001f\u007f]/.test(value))
|
|
129
|
+
throw refused();
|
|
130
|
+
}
|
|
131
|
+
if (store.file === "." || store.file === ".." || /[/\\]/.test(store.file))
|
|
132
|
+
throw refused();
|
|
133
|
+
const birth = inspect();
|
|
134
|
+
if (typeof birth !== "string" || !birth.length || birth.length > 256)
|
|
135
|
+
throw refused();
|
|
136
|
+
directoryChain(store.directory);
|
|
137
|
+
privateDir(store.directory);
|
|
138
|
+
const storePath = join(store.directory, store.file);
|
|
139
|
+
let storeIdentity;
|
|
140
|
+
const checkStore = () => {
|
|
141
|
+
if (absent(storePath)) {
|
|
142
|
+
if (storeIdentity !== undefined)
|
|
143
|
+
throw refused();
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const s = fs.lstatSync(storePath);
|
|
147
|
+
if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || s.uid !== process.geteuid?.() || (s.mode & 0o077) !== 0 ||
|
|
148
|
+
(storeIdentity !== undefined && !same(storeIdentity, s)))
|
|
149
|
+
throw refused();
|
|
150
|
+
storeIdentity ??= { dev: s.dev, ino: s.ino };
|
|
151
|
+
};
|
|
152
|
+
checkStore();
|
|
153
|
+
const root = join(store.directory, ".ce-session-process-mutex");
|
|
154
|
+
mkdir(root);
|
|
155
|
+
const key = createHash("sha256").update(JSON.stringify([store.directory, store.file, endpointId, runtimeSessionId])).digest("hex");
|
|
156
|
+
const scope = join(root, key);
|
|
157
|
+
mkdir(scope);
|
|
158
|
+
const chain = directoryChain(scope);
|
|
159
|
+
const validatePaths = () => {
|
|
160
|
+
const now = directoryChain(scope);
|
|
161
|
+
for (const [path, id] of chain)
|
|
162
|
+
if (!same(id, now.get(path)))
|
|
163
|
+
throw refused();
|
|
164
|
+
privateDir(store.directory);
|
|
165
|
+
privateDir(root);
|
|
166
|
+
privateDir(scope);
|
|
167
|
+
checkStore();
|
|
168
|
+
};
|
|
169
|
+
validatePaths();
|
|
170
|
+
// Immutable release receipts, not unlink/rename of a judged stale pathname.
|
|
171
|
+
// A concurrent contender either observes a complete release or refuses.
|
|
172
|
+
const entries = fs.readdirSync(scope);
|
|
173
|
+
if (entries.length > 100_000 || entries.some((name) => !/^[1-9][0-9]*$/.test(name)))
|
|
174
|
+
throw refused();
|
|
175
|
+
let slot = 1;
|
|
176
|
+
for (; slot <= entries.length; slot++) {
|
|
177
|
+
const previous = join(scope, String(slot));
|
|
178
|
+
privateDir(previous);
|
|
179
|
+
const owner = read(join(previous, "owner.json")).bytes;
|
|
180
|
+
// Validate shape by exact canonical reconstruction, including unknown keys.
|
|
181
|
+
let parsed;
|
|
182
|
+
try {
|
|
183
|
+
parsed = JSON.parse(owner);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
throw refused();
|
|
187
|
+
}
|
|
188
|
+
if (parsed === null || typeof parsed !== "object")
|
|
189
|
+
throw refused();
|
|
190
|
+
if (parsed.version !== 1 || parsed.scope !== key || !Number.isSafeInteger(parsed.pid) || typeof parsed.birth !== "string" ||
|
|
191
|
+
typeof parsed.processToken !== "string" || typeof parsed.handleToken !== "string" ||
|
|
192
|
+
JSON.stringify({ version: 1, scope: key, pid: parsed.pid, birth: parsed.birth, processToken: parsed.processToken, handleToken: parsed.handleToken }) !== owner)
|
|
193
|
+
throw refused();
|
|
194
|
+
if (read(join(previous, "released.json")).bytes !== owner)
|
|
195
|
+
throw refused();
|
|
196
|
+
}
|
|
197
|
+
const directory = join(scope, String(slot));
|
|
198
|
+
fs.mkdirSync(directory, { mode: 0o700 }); // exclusive claim; EEXIST is refusal
|
|
199
|
+
privateDir(directory);
|
|
200
|
+
const directoryId = fs.lstatSync(directory);
|
|
201
|
+
const handleToken = randomUUID();
|
|
202
|
+
const markerPath = join(directory, "owner.json");
|
|
203
|
+
const bytes = JSON.stringify({ version: 1, scope: key, pid: process.pid, birth, processToken, handleToken });
|
|
204
|
+
const markerId = write(markerPath, bytes);
|
|
205
|
+
syncDir(directory);
|
|
206
|
+
syncDir(scope);
|
|
207
|
+
syncDir(root);
|
|
208
|
+
syncDir(store.directory);
|
|
209
|
+
const makeHandle = (handleToken, bytes, markerId) => {
|
|
210
|
+
let closed = false;
|
|
211
|
+
let done = false;
|
|
212
|
+
let uncertain = false;
|
|
213
|
+
let inFlight = 0;
|
|
214
|
+
let drained = false;
|
|
215
|
+
const waiters = [];
|
|
216
|
+
const check = () => {
|
|
217
|
+
if (uncertain || done)
|
|
218
|
+
throw refused();
|
|
219
|
+
try {
|
|
220
|
+
validatePaths();
|
|
221
|
+
privateDir(directory);
|
|
222
|
+
if (!same(directoryId, fs.lstatSync(directory)) || inspect() !== birth ||
|
|
223
|
+
!absent(join(directory, "released.json")) || !absent(join(scope, String(slot + 1))))
|
|
224
|
+
throw refused();
|
|
225
|
+
const current = read(markerPath);
|
|
226
|
+
if (!same(markerId, current.identity) || current.bytes !== bytes)
|
|
227
|
+
throw refused();
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
uncertain = true;
|
|
231
|
+
throw refused();
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
const finish = () => { inFlight--; if (inFlight === 0)
|
|
235
|
+
for (const resolve of waiters.splice(0))
|
|
236
|
+
resolve(); };
|
|
237
|
+
const retire = () => {
|
|
238
|
+
check();
|
|
239
|
+
try {
|
|
240
|
+
// Prepare and sync BEFORE the activation rename. A write/close/fsync
|
|
241
|
+
// uncertainty must not publish reusable release bytes. No fallible
|
|
242
|
+
// durability operation follows activation: losing this directory entry
|
|
243
|
+
// after a power loss only causes conservative refusal, never takeover.
|
|
244
|
+
const pending = join(directory, "release-pending.json");
|
|
245
|
+
const pendingId = write(pending, bytes);
|
|
246
|
+
syncDir(directory);
|
|
247
|
+
const released = join(directory, "released.json");
|
|
248
|
+
try {
|
|
249
|
+
fs.renameSync(pending, released);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
// A throwing rename can have committed. Reconcile only the EXACT
|
|
253
|
+
// inode+bytes we prepared; any unverified outcome latches below.
|
|
254
|
+
const committed = read(released);
|
|
255
|
+
if (!same(pendingId, committed.identity) || committed.bytes !== bytes)
|
|
256
|
+
throw refused();
|
|
257
|
+
}
|
|
258
|
+
done = true;
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
uncertain = true;
|
|
262
|
+
throw refused();
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const ready = () => { if (!closed || !drained || inFlight !== 0 || done || uncertain)
|
|
266
|
+
throw refused(); };
|
|
267
|
+
return Object.freeze({
|
|
268
|
+
handleToken, markerPath,
|
|
269
|
+
assertOwnership: () => { if (closed)
|
|
270
|
+
throw refused(); check(); },
|
|
271
|
+
run: (operation) => {
|
|
272
|
+
if (closed)
|
|
273
|
+
throw refused();
|
|
274
|
+
check();
|
|
275
|
+
inFlight++;
|
|
276
|
+
try {
|
|
277
|
+
const result = operation();
|
|
278
|
+
if (result !== null && (typeof result === "object" || typeof result === "function") &&
|
|
279
|
+
typeof result.then === "function") {
|
|
280
|
+
return Promise.resolve(result).finally(finish);
|
|
281
|
+
}
|
|
282
|
+
finish();
|
|
283
|
+
return result;
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
finish();
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
closeAdmission: () => { closed = true; },
|
|
291
|
+
drain: async () => {
|
|
292
|
+
if (!closed)
|
|
293
|
+
throw refused();
|
|
294
|
+
if (inFlight !== 0)
|
|
295
|
+
await new Promise((resolve) => waiters.push(resolve));
|
|
296
|
+
drained = true;
|
|
297
|
+
},
|
|
298
|
+
explicitTransfer: () => {
|
|
299
|
+
ready();
|
|
300
|
+
check();
|
|
301
|
+
try {
|
|
302
|
+
// No release receipt or acquisition gap: all other processes continue
|
|
303
|
+
// to see an occupied slot. Only this closed/drained local object may
|
|
304
|
+
// replace its exact owner marker with a fresh handle identity.
|
|
305
|
+
const nextToken = randomUUID();
|
|
306
|
+
const nextBytes = JSON.stringify({ version: 1, scope: key, pid: process.pid, birth, processToken, handleToken: nextToken });
|
|
307
|
+
const pending = join(directory, `transfer-${nextToken}.json`);
|
|
308
|
+
const nextId = write(pending, nextBytes);
|
|
309
|
+
syncDir(directory);
|
|
310
|
+
try {
|
|
311
|
+
fs.renameSync(pending, markerPath);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
const committed = read(markerPath);
|
|
315
|
+
if (!same(nextId, committed.identity) || committed.bytes !== nextBytes)
|
|
316
|
+
throw refused();
|
|
317
|
+
}
|
|
318
|
+
done = true;
|
|
319
|
+
return makeHandle(nextToken, nextBytes, nextId);
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
uncertain = true;
|
|
323
|
+
throw refused();
|
|
324
|
+
}
|
|
325
|
+
},
|
|
326
|
+
release: (cleanup) => {
|
|
327
|
+
ready();
|
|
328
|
+
if (cleanup.released !== true || cleanup.detached !== true) {
|
|
329
|
+
uncertain = true;
|
|
330
|
+
throw refused();
|
|
331
|
+
}
|
|
332
|
+
retire();
|
|
333
|
+
},
|
|
334
|
+
});
|
|
335
|
+
};
|
|
336
|
+
return makeHandle(handleToken, bytes, markerId);
|
|
337
|
+
}
|
|
338
|
+
//# sourceMappingURL=session-process-mutex.js.map
|