@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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/dist/bin/ce-native.js +119 -0
  4. package/dist/bin/mcp-stdio.js +196 -0
  5. package/dist/control/debug-log.js +67 -0
  6. package/dist/control/mcp/debug-transport.js +48 -0
  7. package/dist/control/mcp/messaging-tools.js +278 -0
  8. package/dist/control/mcp/ping.js +43 -0
  9. package/dist/control/mcp/server.js +153 -0
  10. package/dist/core/authorization.js +32 -0
  11. package/dist/core/reference.js +32 -0
  12. package/dist/core/rules.js +468 -0
  13. package/dist/endpoints/pi/contract.js +2 -0
  14. package/dist/endpoints/pi/session-host.js +39 -0
  15. package/dist/host/bound-endpoint.js +176 -0
  16. package/dist/host/endpoint-host.js +839 -0
  17. package/dist/host/mcp-binding-config.js +209 -0
  18. package/dist/host/ownership-recovery.js +257 -0
  19. package/dist/index.js +11 -0
  20. package/dist/protocol/capabilities.js +46 -0
  21. package/dist/protocol/endpoint-capabilities.js +15 -0
  22. package/dist/protocol/entities.js +185 -0
  23. package/dist/protocol/formats.js +13 -0
  24. package/dist/protocol/idempotency.js +93 -0
  25. package/dist/protocol/identity.js +130 -0
  26. package/dist/protocol/index.js +8 -0
  27. package/dist/protocol/lifecycle.js +125 -0
  28. package/dist/protocol/outcomes.js +55 -0
  29. package/dist/runtime/desktop-manifest.js +65 -0
  30. package/dist/runtime/diagnostics.js +34 -0
  31. package/dist/runtime/executables.js +217 -0
  32. package/dist/runtime/native-readiness.js +131 -0
  33. package/dist/storage/capability.js +221 -0
  34. package/dist/storage/connection.js +95 -0
  35. package/dist/storage/creation-request.js +176 -0
  36. package/dist/storage/creation.js +553 -0
  37. package/dist/storage/current-schema.js +397 -0
  38. package/dist/storage/delivery-ack.js +177 -0
  39. package/dist/storage/errors.js +9 -0
  40. package/dist/storage/filesystem.js +171 -0
  41. package/dist/storage/inbox-discovery.js +135 -0
  42. package/dist/storage/messaging.js +156 -0
  43. package/dist/storage/migration.js +258 -0
  44. package/dist/storage/native-artifact.js +234 -0
  45. package/dist/storage/native-compat.js +65 -0
  46. package/dist/storage/ownership.js +789 -0
  47. package/dist/storage/participant-identity.js +127 -0
  48. package/dist/storage/participant.js +700 -0
  49. package/dist/storage/recovery.js +99 -0
  50. package/dist/storage/runtime.js +256 -0
  51. package/dist/storage/schema.js +556 -0
  52. package/dist/storage/session-state.js +75 -0
  53. package/dist/storage/sqlite-driver-node.js +66 -0
  54. package/dist/storage/sqlite-driver-rust.js +121 -0
  55. package/dist/storage/sqlite-driver-selection.js +86 -0
  56. package/dist/storage/sqlite-driver.js +4 -0
  57. package/dist/storage/store.js +450 -0
  58. package/dist/storage/transaction.js +196 -0
  59. package/dist/storage/trust-root.js +164 -0
  60. package/dist/tunnel/background-manager.js +1727 -0
  61. package/dist/tunnel/codes.js +79 -0
  62. package/dist/tunnel/health.js +75 -0
  63. package/dist/tunnel/keychain.js +526 -0
  64. package/dist/tunnel/managed-binding.js +454 -0
  65. package/dist/tunnel/manager-panel.js +249 -0
  66. package/dist/tunnel/manager-ui.js +341 -0
  67. package/dist/tunnel/manager.js +372 -0
  68. package/dist/tunnel/messaging-activation-ui.js +85 -0
  69. package/dist/tunnel/messaging-config.js +246 -0
  70. package/dist/tunnel/multi-session-admission.js +31 -0
  71. package/dist/tunnel/multi-session-policy.js +314 -0
  72. package/dist/tunnel/offline-client.js +104 -0
  73. package/dist/tunnel/profile.js +319 -0
  74. package/dist/tunnel/redact.js +9 -0
  75. package/dist/tunnel/secure-input.js +318 -0
  76. package/dist/tunnel/session-process-mutex.js +338 -0
  77. package/dist/tunnel/setup-ui.js +443 -0
  78. package/dist/tunnel/setup.js +734 -0
  79. package/dist/tunnel/state.js +127 -0
  80. package/native/tunnel-keychain.swift +432 -0
  81. package/package.json +65 -4
  82. package/pi-extension/allowlist.example.json +11 -0
  83. package/pi-extension/index.ts +2346 -0
  84. package/pi-extension/multi-session-commands.ts +93 -0
  85. package/pi-extension/multi-session-runtime.ts +75 -0
  86. package/pi-extension/tui-keys.ts +40 -0
  87. package/scripts/reconcile-session-process-mutex.mjs +262 -0
  88. package/scripts/recover-stale-ownership.mjs +91 -0
@@ -0,0 +1,127 @@
1
+ export const DEFAULT_TUNNEL_TIMING = Object.freeze({
2
+ startupTimeoutMs: 30_000, pollIntervalMs: 5_000, freshnessMs: 15_000,
3
+ failThresholdN: 3, recoverThresholdM: 2, stopGraceMs: 10_000,
4
+ });
5
+ export function initialTunnelState(now) {
6
+ return Object.freeze({ name: "Stopped", since: now, consecutiveFailures: 0, consecutiveHealthy: 0, lastHealthyAt: undefined, recovering: false });
7
+ }
8
+ /** now < startedAt + timeout is the ONLY startup window; equality is timeout. */
9
+ export function nextTunnelState(previous, observation, timing = DEFAULT_TUNNEL_TIMING) {
10
+ const { now, managedPid, runId, startedAt, probe } = observation;
11
+ let base = previous;
12
+ let run = previous.run;
13
+ const finish = (name, patch = {}) => Object.freeze({
14
+ ...base, ...patch, name, since: previous.name === name ? previous.since : now,
15
+ ...(run === undefined ? {} : { run: Object.freeze(run) }),
16
+ observedAt: Number.isFinite(now) ? Math.max(previous.observedAt ?? now, now) : previous.observedAt ?? previous.since,
17
+ });
18
+ const clear = { consecutiveFailures: 0, consecutiveHealthy: 0, lastHealthyAt: undefined, recovering: false };
19
+ // A retained PID does not make an old/misattributed absence current either.
20
+ if (!observation.processAlive && run !== undefined &&
21
+ (runId !== run.id || startedAt !== run.startedAt ||
22
+ (managedPid !== undefined && managedPid !== run.managedPid) ||
23
+ !Number.isFinite(now) || (previous.observedAt !== undefined && now < previous.observedAt)))
24
+ return previous;
25
+ // Absence has no PID to cross-check. It may fence an existing run only
26
+ // when the run identity/start and observation order still match. Delayed
27
+ // or unattributed absence is not evidence about the current process.
28
+ if (managedPid === undefined && !observation.processAlive) {
29
+ if (!Number.isFinite(now) || (previous.observedAt !== undefined && now < previous.observedAt))
30
+ return previous;
31
+ if (run !== undefined) {
32
+ if (runId !== run.id || startedAt !== run.startedAt || run.terminal)
33
+ return previous;
34
+ run = { ...run, terminal: true };
35
+ }
36
+ return finish("Stopped", clear);
37
+ }
38
+ if (!Number.isFinite(now) || (previous.observedAt !== undefined && now < previous.observedAt)) {
39
+ return finish(run?.terminal ? previous.name : "Unknown", { consecutiveHealthy: 0 });
40
+ }
41
+ const identityValid = typeof runId === "string" && runId.length > 0 && Number.isSafeInteger(managedPid) && managedPid > 0;
42
+ if (!identityValid)
43
+ return finish(run?.terminal ? previous.name : "Error", { consecutiveHealthy: 0 });
44
+ // Explicit new-run attribution must advance the start clock; delayed old-run
45
+ // observations (even exits) cannot replace the currently supervised run.
46
+ if (run !== undefined && run.id !== runId) {
47
+ if (startedAt === undefined || !Number.isFinite(startedAt) || startedAt <= (run.startedAt ?? -Infinity) || startedAt > now) {
48
+ return finish(run.terminal ? previous.name : "Unknown", { consecutiveHealthy: 0 });
49
+ }
50
+ base = initialTunnelState(now);
51
+ run = undefined;
52
+ }
53
+ if (run === undefined) {
54
+ run = { id: runId, managedPid: managedPid, startedAt, sequence: 0, completedAt: undefined, terminal: false };
55
+ }
56
+ else if (run.managedPid !== managedPid || (startedAt !== undefined && run.startedAt !== startedAt)) {
57
+ return finish(run.terminal ? previous.name : "Unknown", { consecutiveHealthy: 0 });
58
+ }
59
+ if (run.terminal)
60
+ return finish(previous.name);
61
+ // Exit wins over all health evidence, including a contradictory alive flag.
62
+ if (!observation.processAlive || observation.exit !== undefined) {
63
+ const exit = observation.exit;
64
+ const expected = observation.userStopped && (exit === undefined || exit.signal === "SIGTERM" || exit.signal === "SIGINT" || exit.code === 0);
65
+ run = { ...run, terminal: true };
66
+ return finish(expected ? "Stopped" : "Error", clear);
67
+ }
68
+ if (observation.userStopped)
69
+ return finish("Stopping", { consecutiveHealthy: 0 });
70
+ if (startedAt === undefined || !Number.isFinite(startedAt) || startedAt > now) {
71
+ run = { ...run, terminal: true };
72
+ return finish("Error", { consecutiveHealthy: 0 });
73
+ }
74
+ // Evaluate startup against PREVIOUS evidence; late first health cannot erase
75
+ // the deadline. An established run instead expires by completion freshness.
76
+ const startup = base.lastHealthyAt === undefined && !base.recovering;
77
+ if (startup && now >= startedAt + timing.startupTimeoutMs) {
78
+ run = { ...run, terminal: true };
79
+ return finish("Error", { consecutiveHealthy: 0, consecutiveFailures: Math.max(base.consecutiveFailures, 1) });
80
+ }
81
+ const completion = probe?.completion;
82
+ const attributed = completion !== undefined && completion.runId === run.id && completion.managedPid === run.managedPid &&
83
+ Number.isSafeInteger(completion.sequence) && completion.sequence > 0 && Number.isFinite(completion.completedAt) &&
84
+ completion.completedAt >= startedAt && completion.completedAt <= now && now - completion.completedAt <= timing.freshnessMs;
85
+ const distinct = attributed && completion.sequence > run.sequence && (run.completedAt === undefined || completion.completedAt >= run.completedAt);
86
+ // Replaying the last accepted healthy completion may KEEP an already fresh
87
+ // Connected, but can never create one, refresh a timestamp, or advance M.
88
+ const duplicate = attributed && completion.sequence === run.sequence && completion.completedAt === run.completedAt;
89
+ if (!distinct || probe === undefined) {
90
+ const fresh = base.lastHealthyAt !== undefined && now - base.lastHealthyAt <= timing.freshnessMs;
91
+ const keepConnected = base.name === "Connected" && fresh && (probe === undefined || (duplicate && probe.kind === "healthy" && probe.connectedEligible));
92
+ const name = keepConnected ? "Connected" : startup ? "Starting" : base.recovering && fresh ? "Disconnected" : "Unknown";
93
+ return finish(name, { consecutiveHealthy: duplicate ? base.consecutiveHealthy : 0 });
94
+ }
95
+ run = { ...run, sequence: completion.sequence, completedAt: completion.completedAt };
96
+ const healthyNow = probe.kind === "healthy" && probe.connectedEligible === true;
97
+ const failures = healthyNow ? 0 : base.consecutiveFailures + 1;
98
+ const healthy = healthyNow ? base.consecutiveHealthy + 1 : 0;
99
+ const counters = { consecutiveFailures: failures, consecutiveHealthy: healthy, lastHealthyAt: healthyNow ? completion.completedAt : base.lastHealthyAt };
100
+ if (healthyNow) {
101
+ if (base.recovering && healthy < timing.recoverThresholdM)
102
+ return finish("Disconnected", counters);
103
+ return finish("Connected", { ...counters, recovering: false });
104
+ }
105
+ if (startup)
106
+ return finish(probe.kind === "unhealthy" ? "Connecting" : "Starting", counters);
107
+ if (probe.kind === "unverifiable")
108
+ return finish("Unknown", counters);
109
+ if (failures >= timing.failThresholdN || base.recovering)
110
+ return finish("Disconnected", { ...counters, recovering: true });
111
+ return finish("Connecting", counters);
112
+ }
113
+ /** Human-facing transport label. Never implies delivery, ACK, or completion. */
114
+ export function tunnelStatusLabel(state) {
115
+ switch (state.name) {
116
+ case "Connected": return "Tunnel ● transport up";
117
+ case "Connecting": return "Tunnel ◐ connecting";
118
+ case "Starting": return "Tunnel ◐ starting";
119
+ case "Disconnected": return "Tunnel ○ transport down";
120
+ case "Stopping": return "Tunnel ◌ stopping";
121
+ case "Unknown": return "Tunnel ? unverified";
122
+ case "Error": return "Tunnel ✗ error";
123
+ case "Stopped":
124
+ default: return "Tunnel ○ stopped";
125
+ }
126
+ }
127
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1,432 @@
1
+ // HANDOFF-CE-HOST-09 B1.1 Task 2 — minimal macOS Keychain helper.
2
+ //
3
+ // One operation per process. The request arrives as a bounded frame on stdin:
4
+ //
5
+ // v1 <op> <accountByteLength> <secretByteLength>[ <keychainPathByteLength>][ interactive]
6
+ // <account bytes><secret bytes><keychain path bytes>
7
+ //
8
+ // B1.1-INTEGRATION: the literal trailing token `interactive` is accepted on
9
+ // `read` ONLY. It enables the NATIVE macOS authorization prompt for that one
10
+ // read (the user-triggered authorize path). Every other invocation runs with
11
+ // interaction disabled, exactly as before.
12
+ // The frame is read ONLY from file descriptor 0 through a single reader, with a
13
+ // bounded header scan and an exact-length payload read. Nothing is read with
14
+ // `readLine` (which buffers in C stdio and would desynchronise a later
15
+ // descriptor read) and nothing is read with `readDataToEndOfFile` (which would
16
+ // allocate before the length bound is known).
17
+ //
18
+ // The secret is DATA only: it never appears in argv, in the environment, in a
19
+ // file, in a shell/interpreter command string, or in any diagnostic. Responses
20
+ // are a single fixed-shape JSON line on stdout; the only free-form field is a
21
+ // fixed reason token from the closed list below. Raw OSStatus text is never
22
+ // emitted, so the caller cannot be used as an error-message oracle.
23
+ //
24
+ // Scope discipline (keychain-design-recon.md):
25
+ // - legacy macOS Keychain, resolved ONCE per process. By DEFAULT that is the
26
+ // default keychain (SecKeychainCopyDefault) and production behaviour is
27
+ // unchanged. The optional fifth header field names exactly ONE keychain file,
28
+ // which is opened with SecKeychainOpen; it exists so the authorized probe can
29
+ // target an exclusively owned temporary keychain WITHOUT mutating the default
30
+ // keychain. The default keychain and the search list are never set, modified,
31
+ // or extended, and the path is supplied only by the explicitly configured
32
+ // test/probe runner option — never by a CE command, profile, or environment
33
+ // variable.
34
+ // - never the whole default search list, never a prefix or service-wide match.
35
+ // - exact generic-password class + exact service + exact account.
36
+ // - create installs an access object with an EXPLICIT EMPTY trusted-application
37
+ // list (documented equivalent of `security -T ""`). nil would trust the
38
+ // creating application and `-A` style allow-all is never used.
39
+ // - update/read inspect the existing ACL and REFUSE when it is broader than the
40
+ // empty-trusted-app policy. The helper never "repairs", adopts, or widens an
41
+ // ACL, never touches partition lists, and never automates an OS prompt.
42
+ // - deletion and modification always target the exact resolved item reference.
43
+ //
44
+ // Error semantics: native `errSecItemNotFound` is -25300. The `security(1)`
45
+ // CLI's "not found" exit status is a CLI-only convention and is deliberately
46
+ // NOT recognised here; this helper reports absence only from the native status.
47
+ //
48
+ // NOT VERIFIED in B1.1 by the implementing worker: compilation, runtime Keychain
49
+ // CRUD, ACL behaviour, and prompt behaviour. Those require the authorized
50
+ // fake-item probe in an exclusively owned temporary Keychain.
51
+ import Foundation
52
+ import Security
53
+
54
+ let maxAccountBytes = 128
55
+ let maxSecretBytes = 4096
56
+ let maxKeychainPathBytes = 1024
57
+ let maxHeaderBytes = 96
58
+ let allowedOps = ["exists", "read", "create", "update", "delete"]
59
+
60
+ func respond(_ line: String) -> Never {
61
+ FileHandle.standardOutput.write(Data((line + "\n").utf8))
62
+ exit(0)
63
+ }
64
+
65
+ func ok() -> Never { respond(#"{"status":"ok"}"#) }
66
+
67
+ func okSecret(_ secret: String) -> Never {
68
+ // The secret travels only on this private stdout pipe, which the credential
69
+ // adapter is the sole reader of.
70
+ let encoded = Data(secret.utf8).base64EncodedString()
71
+ respond(#"{"status":"ok","secretBase64":"\#(encoded)"}"#)
72
+ }
73
+
74
+ func notFound() -> Never { respond(#"{"status":"not_found"}"#) }
75
+
76
+ /// Fixed reason tokens only: `bad_request`, `unavailable`, `acl_too_broad`,
77
+ /// `already_exists`, `authorization_required`, `user_canceled`.
78
+ func failure(_ reason: String) -> Never {
79
+ respond(#"{"status":"error","reason":"\#(reason)"}"#)
80
+ }
81
+
82
+ /// Absolute, single-line, NUL-free, bounded. Nothing is created or mutated from
83
+ /// this path: it only selects which single keychain is opened.
84
+ func validKeychainPath(_ path: String) -> Bool {
85
+ if !path.hasPrefix("/") { return false }
86
+ if path.utf8.count > maxKeychainPathBytes { return false }
87
+ for scalar in path.unicodeScalars {
88
+ if scalar == "\0" || scalar == "\n" || scalar == "\r" { return false }
89
+ }
90
+ return true
91
+ }
92
+
93
+ func validAccount(_ account: String) -> Bool {
94
+ if account.isEmpty || account.utf8.count > maxAccountBytes { return false }
95
+ for scalar in account.unicodeScalars {
96
+ let isLower = scalar >= "a" && scalar <= "z"
97
+ let isUpper = scalar >= "A" && scalar <= "Z"
98
+ let isDigit = scalar >= "0" && scalar <= "9"
99
+ let isPunct = scalar == ":" || scalar == "-" || scalar == "_" || scalar == "."
100
+ if !(isLower || isUpper || isDigit || isPunct) { return false }
101
+ }
102
+ return true
103
+ }
104
+
105
+ // Default: NEVER surface interactive UI from this helper. The B1.1-INTEGRATION
106
+ // authorize path is the single exception, enabled explicitly by the trailing
107
+ // `interactive` frame token AFTER the frame has been parsed and validated —
108
+ // an unattended caller can never trigger an approval request by accident.
109
+ SecKeychainSetUserInteractionAllowed(false)
110
+
111
+ // Single reader on fd 0, used for both the header and the payload.
112
+ let input = FileHandle.standardInput
113
+
114
+ /// Bounded header scan: at most `maxHeaderBytes` bytes before the newline, so a
115
+ /// caller cannot force an unbounded allocation by never terminating the line.
116
+ func readHeaderLine() -> String? {
117
+ var bytes = [UInt8]()
118
+ while bytes.count <= maxHeaderBytes {
119
+ guard let chunk = try? input.read(upToCount: 1), let byte = chunk.first else { return nil }
120
+ if byte == 0x0a { return String(bytes: bytes, encoding: .utf8) }
121
+ bytes.append(byte)
122
+ }
123
+ return nil
124
+ }
125
+
126
+ /// Exact-length read: only after the declared bound has been validated.
127
+ func readExactly(_ count: Int) -> [UInt8]? {
128
+ if count == 0 { return [] }
129
+ var bytes = [UInt8]()
130
+ bytes.reserveCapacity(count)
131
+ while bytes.count < count {
132
+ guard let chunk = try? input.read(upToCount: count - bytes.count), !chunk.isEmpty else { return nil }
133
+ bytes.append(contentsOf: chunk)
134
+ }
135
+ return bytes
136
+ }
137
+
138
+ guard let header = readHeaderLine() else { failure("bad_request") }
139
+ let fields = header.split(separator: " ").map(String.init)
140
+ guard fields.count >= 4, fields.count <= 6, fields[0] == "v1", allowedOps.contains(fields[1]),
141
+ let accountLength = Int(fields[2]), let secretLength = Int(fields[3]),
142
+ accountLength > 0, accountLength <= maxAccountBytes,
143
+ secretLength >= 0, secretLength <= maxSecretBytes
144
+ else { failure("bad_request") }
145
+
146
+ var keychainPathLength = 0
147
+ var allowInteraction = false
148
+ if fields.count == 5 {
149
+ if let declared = Int(fields[4]) {
150
+ guard declared > 0, declared <= maxKeychainPathBytes else { failure("bad_request") }
151
+ keychainPathLength = declared
152
+ } else if fields[4] == "interactive" {
153
+ guard fields[1] == "read" else { failure("bad_request") }
154
+ allowInteraction = true
155
+ } else {
156
+ failure("bad_request")
157
+ }
158
+ } else if fields.count == 6 {
159
+ guard fields[5] == "interactive", fields[1] == "read",
160
+ let declared = Int(fields[4]), declared > 0, declared <= maxKeychainPathBytes
161
+ else { failure("bad_request") }
162
+ keychainPathLength = declared
163
+ allowInteraction = true
164
+ }
165
+
166
+ // The single B1.1-INTEGRATION exception: enable the native authorization
167
+ // prompt for THIS process only when the validated frame asked for it.
168
+ SecKeychainSetUserInteractionAllowed(allowInteraction)
169
+
170
+ let operation = fields[1]
171
+ let totalLength = accountLength + secretLength + keychainPathLength
172
+ guard let payload = readExactly(totalLength) else { failure("bad_request") }
173
+ // The frame is exact: trailing bytes are a protocol violation, not padding.
174
+ if let trailing = (try? input.read(upToCount: 1)) ?? nil, !trailing.isEmpty { failure("bad_request") }
175
+
176
+ guard let account = String(bytes: payload[0..<accountLength], encoding: .utf8), validAccount(account)
177
+ else { failure("bad_request") }
178
+ let secretData = Data(payload[accountLength..<(accountLength + secretLength)])
179
+ var requestedKeychainPath: String?
180
+ if keychainPathLength > 0 {
181
+ guard let path = String(bytes: payload[(accountLength + secretLength)..<totalLength], encoding: .utf8),
182
+ validKeychainPath(path)
183
+ else { failure("bad_request") }
184
+ requestedKeychainPath = path
185
+ }
186
+ let needsSecret = operation == "create" || operation == "update"
187
+ if needsSecret && secretLength == 0 { failure("bad_request") }
188
+ if !needsSecret && secretLength != 0 { failure("bad_request") }
189
+
190
+ let service = "pi-chat-exchange-tunnel"
191
+ let serviceBytes = Array(service.utf8)
192
+ let accountBytes = Array(account.utf8)
193
+
194
+ // Exactly one keychain is resolved for this process: either the production
195
+ // default keychain, or the ONE explicitly named probe keychain. Neither the
196
+ // default keychain setting nor any search list is read or written.
197
+ var keychain: SecKeychain?
198
+ if let requestedKeychainPath {
199
+ guard SecKeychainOpen(requestedKeychainPath, &keychain) == errSecSuccess, let opened = keychain else {
200
+ failure("unavailable")
201
+ }
202
+ // SecKeychainOpen also succeeds for a path that does not exist, so the
203
+ // keychain is probed for an actual status before anything is attempted.
204
+ var keychainStatus = SecKeychainStatus()
205
+ guard SecKeychainGetStatus(opened, &keychainStatus) == errSecSuccess else { failure("unavailable") }
206
+ } else {
207
+ if SecKeychainCopyDefault(&keychain) != errSecSuccess { failure("unavailable") }
208
+ }
209
+
210
+ /// Exact-match lookup: class + service + account, no wildcard and no fallback.
211
+ /// This NEVER requests the secret. Every path first resolves metadata only, so
212
+ /// the ACL can be validated before any value is asked for.
213
+ func findExactItem() -> (OSStatus, SecKeychainItem?) {
214
+ var itemRef: SecKeychainItem?
215
+ let status = SecKeychainFindGenericPassword(
216
+ keychain,
217
+ UInt32(serviceBytes.count), service,
218
+ UInt32(accountBytes.count), account,
219
+ nil, nil, &itemRef
220
+ )
221
+ guard status == errSecSuccess else { return (status, nil) }
222
+ return (status, itemRef)
223
+ }
224
+
225
+ /// Retrieve the value through the EXACT item reference that was already found
226
+ /// and ACL-validated. Requesting the secret is the last step, never the first.
227
+ /// Retrieve the value through the EXACT item reference that was already found
228
+ /// and ACL-validated. Requesting the secret is the last step, never the first.
229
+ /// B1.1-INTEGRATION: the native status is returned so the caller can classify
230
+ /// authorization outcomes (-25293 / -128) into closed reason tokens.
231
+ func copySecretData(_ item: SecKeychainItem) -> (OSStatus, Data?) {
232
+ var length: UInt32 = 0
233
+ var pointer: UnsafeMutableRawPointer?
234
+ let status = SecKeychainItemCopyContent(item, nil, nil, &length, &pointer)
235
+ guard status == errSecSuccess, let pointer
236
+ else { return (status, nil) }
237
+ let data = Data(bytes: pointer, count: Int(length))
238
+ SecKeychainItemFreeContent(nil, pointer)
239
+ return (status, data)
240
+ }
241
+
242
+ /// READ policy. The stored policy is "no application may read this item
243
+ /// without an explicit user decision". B1.1-INTEGRATION refines the shipped
244
+ /// check with the KEYCHAIN-GATE-verified user-authorization state:
245
+ /// - every secret-reading ACL must carry a NON-NIL application list (nil means
246
+ /// "all applications" and is still refused);
247
+ /// - an EMPTY list is the not-yet-authorized state and is accepted;
248
+ /// - a NON-EMPTY list is accepted ONLY as the user-approved state, and only
249
+ /// while the ChangeACL authorization itself still carries an EMPTY list:
250
+ /// since every ACL modification then requires an explicit user decision, a
251
+ /// non-empty read list can only be the result of the user approving the
252
+ /// native prompt (verified in B1.1-KEYCHAIN-GATE: Always Allow added exactly
253
+ /// one entry and left ChangeACL empty).
254
+ ///
255
+ /// Fail closed in every ambiguous case. An access object that cannot be copied,
256
+ /// an ACL list that cannot be enumerated, an empty ACL list, an authorization
257
+ /// list that is absent or unreadable, or an application list that is nil (which
258
+ /// means "all applications") all REFUSE. The absence of any secret-reading ACL
259
+ /// is not treated as "unrestricted but harmless".
260
+ func aclReadAcceptable(_ item: SecKeychainItem) -> Bool {
261
+ var access: SecAccess?
262
+ guard SecKeychainItemCopyAccess(item, &access) == errSecSuccess, let access else { return false }
263
+ var aclList: CFArray?
264
+ guard SecAccessCopyACLList(access, &aclList) == errSecSuccess,
265
+ let acls = aclList as? [SecACL], !acls.isEmpty else { return false }
266
+ var sawRestrictedReadAcl = false
267
+ var sawUserApprovedReadAcl = false
268
+ var sawChangeGovernanceAcl = false
269
+ for acl in acls {
270
+ var applications: CFArray?
271
+ var description: CFString?
272
+ var prompt = SecKeychainPromptSelector()
273
+ guard SecACLCopyContents(acl, &applications, &description, &prompt) == errSecSuccess else { return false }
274
+ let rawAuthorizations: CFArray? = SecACLCopyAuthorizations(acl)
275
+ guard let authorizations = rawAuthorizations as? [String] else { return false }
276
+ let readish = authorizations.contains(kSecACLAuthorizationDecrypt as String)
277
+ || authorizations.contains(kSecACLAuthorizationExportClear as String)
278
+ || authorizations.contains(kSecACLAuthorizationExportWrapped as String)
279
+ || authorizations.contains(kSecACLAuthorizationAny as String)
280
+ let governsAcl = authorizations.contains(kSecACLAuthorizationChangeACL as String)
281
+ || authorizations.contains(kSecACLAuthorizationAny as String)
282
+ if !readish && !governsAcl { continue }
283
+ guard let trusted = applications as? [SecTrustedApplication] else { return false }
284
+ if readish {
285
+ if trusted.isEmpty { sawRestrictedReadAcl = true } else { sawUserApprovedReadAcl = true }
286
+ }
287
+ if governsAcl {
288
+ sawChangeGovernanceAcl = true
289
+ // An application that can edit the ACLs unattended ends the
290
+ // user-decision guarantee; refuse instead of adopting the drift.
291
+ if !trusted.isEmpty { return false }
292
+ }
293
+ }
294
+ if sawUserApprovedReadAcl { return sawChangeGovernanceAcl }
295
+ return sawRestrictedReadAcl
296
+ }
297
+
298
+ /// UPDATE policy: the pristine shipped state only. Every secret-reading ACL
299
+ /// must carry an explicitly EMPTY trusted-application list (nil still means
300
+ /// "all applications" and is refused), and at least one such ACL must exist.
301
+ /// B1.1-INTEGRATION round 3 (Lane S S-R2-01): every ACL that authorizes
302
+ /// modifying this item's own access control without a user decision
303
+ /// (ChangeACL or Any) must ALSO carry an explicitly empty, non-nil trusted
304
+ /// list. An attacker-pre-planted item can pass the empty-read-list check and
305
+ /// still name the attacker's program in a separate ChangeACL ACL; without
306
+ /// this governance check `update` would write the new secret into that item
307
+ /// and the attacker could then grant itself read access unattended. Missing
308
+ /// or unreadable governance state fails closed exactly like the read state.
309
+ /// At least one ChangeACL/Any ACL must be present; absence is not evidence
310
+ /// that future ACL changes require a user decision.
311
+ /// After the user chooses Always Allow the read list is no longer empty, so
312
+ /// rotation requires delete + create + one new authorization — a documented,
313
+ /// deliberate cost instead of an adoptable ambiguity.
314
+ func aclUpdateAcceptable(_ item: SecKeychainItem) -> Bool {
315
+ var access: SecAccess?
316
+ guard SecKeychainItemCopyAccess(item, &access) == errSecSuccess, let access else { return false }
317
+ var aclList: CFArray?
318
+ guard SecAccessCopyACLList(access, &aclList) == errSecSuccess,
319
+ let acls = aclList as? [SecACL], !acls.isEmpty else { return false }
320
+ var sawRestrictedReadAcl = false
321
+ var sawChangeGovernanceAcl = false
322
+ for acl in acls {
323
+ var applications: CFArray?
324
+ var description: CFString?
325
+ var prompt = SecKeychainPromptSelector()
326
+ guard SecACLCopyContents(acl, &applications, &description, &prompt) == errSecSuccess else { return false }
327
+ let rawAuthorizations: CFArray? = SecACLCopyAuthorizations(acl)
328
+ guard let authorizations = rawAuthorizations as? [String] else { return false }
329
+ let readish = authorizations.contains(kSecACLAuthorizationDecrypt as String)
330
+ || authorizations.contains(kSecACLAuthorizationExportClear as String)
331
+ || authorizations.contains(kSecACLAuthorizationExportWrapped as String)
332
+ || authorizations.contains(kSecACLAuthorizationAny as String)
333
+ let governsAcl = authorizations.contains(kSecACLAuthorizationChangeACL as String)
334
+ || authorizations.contains(kSecACLAuthorizationAny as String)
335
+ if !readish && !governsAcl { continue }
336
+ guard let trusted = applications as? [SecTrustedApplication] else { return false }
337
+ if !trusted.isEmpty { return false }
338
+ if readish { sawRestrictedReadAcl = true }
339
+ if governsAcl { sawChangeGovernanceAcl = true }
340
+ }
341
+ return sawRestrictedReadAcl && sawChangeGovernanceAcl
342
+ }
343
+
344
+ switch operation {
345
+ case "exists":
346
+ let (status, _) = findExactItem()
347
+ if status == errSecItemNotFound { notFound() }
348
+ if status != errSecSuccess { failure("unavailable") }
349
+ ok()
350
+
351
+ case "read":
352
+ // Metadata FIRST: the exact item is resolved and its ACL validated before
353
+ // the secret is requested at all, so a broad-ACL item never has its value
354
+ // copied out of the keychain.
355
+ let (status, item) = findExactItem()
356
+ if status == errSecItemNotFound { notFound() }
357
+ guard status == errSecSuccess, let item else { failure("unavailable") }
358
+ if !aclReadAcceptable(item) { failure("acl_too_broad") }
359
+ let (readStatus, data) = copySecretData(item)
360
+ // B1.1-INTEGRATION: classify the native authorization outcomes instead of
361
+ // collapsing them into unavailability. -25293 errSecAuthFailed with no
362
+ // interaction available means THIS code identity has no user decision
363
+ // yet; -128 errSecUserCanceled means the user dismissed the prompt.
364
+ if readStatus == errSecAuthFailed { failure("authorization_required") }
365
+ if readStatus == errSecUserCanceled { failure("user_canceled") }
366
+ guard readStatus == errSecSuccess, let data else { failure("unavailable") }
367
+ guard let secret = String(data: data, encoding: .utf8) else { failure("unavailable") }
368
+ okSecret(secret)
369
+
370
+ case "create":
371
+ let (existing, _) = findExactItem()
372
+ if existing == errSecSuccess { failure("already_exists") }
373
+ if existing != errSecItemNotFound { failure("unavailable") }
374
+ // Documented equivalent of `security … -T ""`: an explicit EMPTY list.
375
+ let emptyTrustedApps = [] as CFArray
376
+ var access: SecAccess?
377
+ if SecAccessCreate(service as CFString, emptyTrustedApps, &access) != errSecSuccess { failure("unavailable") }
378
+ guard let access else { failure("unavailable") }
379
+ var attributes = [
380
+ SecKeychainAttribute(tag: SecItemAttr.serviceItemAttr.rawValue, length: UInt32(serviceBytes.count),
381
+ data: UnsafeMutableRawPointer(mutating: (service as NSString).utf8String)),
382
+ SecKeychainAttribute(tag: SecItemAttr.accountItemAttr.rawValue, length: UInt32(accountBytes.count),
383
+ data: UnsafeMutableRawPointer(mutating: (account as NSString).utf8String)),
384
+ ]
385
+ var created: SecKeychainItem?
386
+ let createStatus = attributes.withUnsafeMutableBufferPointer { buffer -> OSStatus in
387
+ var list = SecKeychainAttributeList(count: UInt32(buffer.count), attr: buffer.baseAddress)
388
+ return secretData.withUnsafeBytes { bytes in
389
+ SecKeychainItemCreateFromContent(
390
+ SecItemClass.genericPasswordItemClass, &list,
391
+ UInt32(secretData.count), bytes.baseAddress,
392
+ keychain, access, &created
393
+ )
394
+ }
395
+ }
396
+ if createStatus != errSecSuccess { failure("unavailable") }
397
+ ok()
398
+
399
+ case "update":
400
+ let (status, item) = findExactItem()
401
+ if status == errSecItemNotFound { notFound() }
402
+ guard status == errSecSuccess, let item else { failure("unavailable") }
403
+ // UPDATE policy (Lane S S-01, rework round): STRICTER than the read policy.
404
+ // An empty ChangeACL list constrains only FUTURE ACL modifications; it
405
+ // cannot prove that a non-empty read trusted list was created by a user
406
+ // approval. An attacker who pre-creates this exact service/account item
407
+ // with their own app trusted (and an empty ChangeACL) would otherwise
408
+ // receive the newly typed secret through `update`. Reading such an item
409
+ // leaks nothing (our read still fails), so only `read` accepts the
410
+ // user-approved state; `update` requires the pristine empty-list state
411
+ // and never adopts, repairs, or recreates a drifted item.
412
+ // B1.1-INTEGRATION round 3 (Lane S S-R2-01): the check now ALSO refuses an
413
+ // item whose ChangeACL/Any authorization names ANY trusted application:
414
+ // that program could admit itself to the read list after our update, so
415
+ // an attacker-pre-planted governance right can never receive the secret.
416
+ if !aclUpdateAcceptable(item) { failure("acl_too_broad") }
417
+ let updateStatus = secretData.withUnsafeBytes { bytes in
418
+ SecKeychainItemModifyAttributesAndData(item, nil, UInt32(secretData.count), bytes.baseAddress)
419
+ }
420
+ if updateStatus != errSecSuccess { failure("unavailable") }
421
+ ok()
422
+
423
+ case "delete":
424
+ let (status, item) = findExactItem()
425
+ if status == errSecItemNotFound { notFound() }
426
+ guard status == errSecSuccess, let item else { failure("unavailable") }
427
+ if SecKeychainItemDelete(item) != errSecSuccess { failure("unavailable") }
428
+ ok()
429
+
430
+ default:
431
+ failure("bad_request")
432
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@zieglar/pi-chat-exchange",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "license": "MIT",
5
+ "publishConfig": {
6
+ "access": "public",
7
+ "registry": "https://registry.npmjs.org/"
8
+ },
9
+ "description": "Pi extension for explicit ChatGPT message exchange with durable SQLite storage and Secure MCP Tunnel management.",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/zieglar/pi-packages.git",
13
+ "directory": "packages/pi-chat-exchange"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=22.19.0"
18
+ },
19
+ "scripts": {
20
+ "test": "CE_DEFAULT_CLIENT_GUARD=1 vitest run --exclude test/tunnel/real-client-compat.test.ts --exclude test/tunnel/offline.integration.test.ts --exclude test/host-regression/real-host-recovery.test.ts --exclude test/package/installed-host.test.ts --exclude '**/native-{artifact,value-regression,cli}.test.ts' --exclude '**/sqlite-driver-cross.test.ts'",
21
+ "test:distribution-host": "CE_DISTRIBUTION_HOST_TEST=1 vitest run test/package/installed-host.test.ts",
22
+ "test:distribution-npm": "CE_DISTRIBUTION_HOST_TEST=1 CE_DISTRIBUTION_MODE=managed-npm vitest run test/package/installed-host.test.ts",
23
+ "test:installed-client": "vitest run test/tunnel/real-client-compat.test.ts test/tunnel/offline.integration.test.ts",
24
+ "test:host-regression": "CE_HOST_REGRESSION_TEST=1 vitest run test/host-regression/real-host-recovery.test.ts",
25
+ "test:storage": "vitest run test/storage --exclude '**/native-{artifact,value-regression,cli}.test.ts' --exclude '**/sqlite-driver-cross.test.ts'",
26
+ "native": "node dist/bin/ce-native.js",
27
+ "test:rust-native": "vitest run --config test/rust-native.vitest.config.ts --dir test/storage --testTimeout 120000 --hookTimeout 120000 --exclude '**/runtime-cross-version.test.ts' --exclude '**/runtime-wal-safety.test.ts' --exclude '**/inbox-ack-volume.test.ts'",
28
+ "test:plugin-package": "CE_PLUGIN_PACKAGE_TEST=1 vitest run test/plugin/local-plugin-package.test.ts",
29
+ "test:watch": "vitest",
30
+ "typecheck": "tsc --noEmit -p tsconfig.json",
31
+ "build": "tsc -p tsconfig.build.json",
32
+ "package:pi-extension": "pnpm run build && node scripts/package-pi-extension.mjs",
33
+ "package:desktop-plugin": "node scripts/package-local-plugin.mjs",
34
+ "recover:ownership": "node scripts/recover-stale-ownership.mjs",
35
+ "reconcile:session-mutex": "node scripts/reconcile-session-process-mutex.mjs",
36
+ "check": "node scripts/check-contract.mjs && node scripts/check-native.mjs",
37
+ "verify": "pnpm run check && pnpm run typecheck && pnpm run build && pnpm test && pnpm run test:plugin-package"
38
+ },
39
+ "dependencies": {
40
+ "@earendil-works/pi-tui": "1.3.0",
41
+ "@modelcontextprotocol/sdk": "1.30.1",
42
+ "@narumitw/pi-tui-kit": "0.66.0",
43
+ "@sinclair/typebox": "0.34.52"
44
+ },
45
+ "devDependencies": {
46
+ "@earendil-works/pi-coding-agent": "1.3.0",
47
+ "@types/node": "24.19.1",
48
+ "typescript": "5.9.3",
49
+ "vitest": "4.1.11"
50
+ },
51
+ "files": [
52
+ "pi-extension/*.ts",
53
+ "pi-extension/allowlist.example.json",
54
+ "dist/**/*.js",
55
+ "native/tunnel-keychain.swift",
56
+ "scripts/recover-stale-ownership.mjs",
57
+ "scripts/reconcile-session-process-mutex.mjs"
58
+ ],
59
+ "peerDependencies": {
60
+ "@earendil-works/pi-coding-agent": "1.3.0"
61
+ },
62
+ "pi": {
63
+ "extensions": [
64
+ "./pi-extension/index.ts"
65
+ ]
66
+ }
67
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "exchangeNamespace": "local",
3
+ "exchangeIdempotencyKey": "chatgpt-pi",
4
+ "leaseTtlSeconds": 120,
5
+ "payloadRead": { "enabled": false },
6
+ "inboxNotification": { "enabled": false, "pageSize": 10, "rawScanLimit": 100 },
7
+ "recipients": [{ "adapter": "mcp", "endpointId": "chatgpt-desktop" }],
8
+ "sessions": {
9
+ "pi-main": { "endpointId": "pi-main" }
10
+ }
11
+ }