@zieglar/pi-chat-exchange 0.3.0 → 0.3.2
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/README.md +10 -6
- package/dist/bin/mcp-stdio.js +113 -62
- package/dist/control/mcp/endpoint-discovery.js +60 -0
- package/dist/control/mcp/messaging-tools.js +12 -2
- package/dist/control/mcp/server.js +10 -2
- package/dist/host/bound-endpoint.js +19 -6
- package/dist/host/endpoint-host.js +78 -4
- package/dist/host/mcp-binding-config.js +27 -4
- package/dist/runtime/native-readiness.js +8 -5
- package/dist/storage/creation.js +16 -0
- package/dist/storage/ownership.js +45 -1
- package/dist/tunnel/background-authorization.js +343 -0
- package/dist/tunnel/background-manager.js +104 -8
- package/dist/tunnel/background-scope.js +69 -0
- package/dist/tunnel/codes.js +1 -1
- package/dist/tunnel/hooks-management-ui.js +225 -0
- package/dist/tunnel/hooks-management.js +431 -0
- package/dist/tunnel/live-adoption-observation.js +136 -0
- package/dist/tunnel/live-adoption-probe.js +240 -0
- package/dist/tunnel/live-connection-status.js +136 -0
- package/dist/tunnel/live-mcp-composition.js +143 -0
- package/dist/tunnel/live-process-observation.js +98 -0
- package/dist/tunnel/live-session-migration.js +169 -0
- package/dist/tunnel/live-session-policy.js +578 -0
- package/dist/tunnel/manager-panel.js +4 -2
- package/dist/tunnel/manager-ui.js +71 -15
- package/dist/tunnel/multi-session-admission.js +1 -1
- package/dist/tunnel/setup-ui.js +2 -4
- package/dist/tunnel/status-ui.js +34 -0
- package/package.json +1 -1
- package/pi-extension/desktop-target.ts +157 -0
- package/pi-extension/index.ts +1060 -139
- package/pi-extension/live-session-profile.ts +49 -0
- package/pi-extension/live-session-runtime.ts +59 -0
- package/pi-extension/multi-session-commands.ts +114 -3
- package/pi-extension/multi-session-runtime.ts +63 -11
- package/pi-extension/native-inbound.ts +235 -0
- package/pi-extension/native-read-protocol.ts +44 -0
- package/pi-extension/ownership-feedback.ts +100 -0
- package/pi-extension/session-onboarding.ts +154 -0
- package/pi-extension/session-recovery.ts +214 -0
|
@@ -175,11 +175,34 @@ export function parseMcpBindingConfig(raw) {
|
|
|
175
175
|
const managed = fields.managed === undefined ? undefined : managedMetadata(fields.managed);
|
|
176
176
|
let admissionPolicy;
|
|
177
177
|
if (fields.admissionPolicy !== undefined) {
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
178
|
+
const kind = plain(fields.admissionPolicy, "admissionPolicy", ["kind", "profilePath", "root", "policyId", "genesisDigest", "upgradeSequence"], ["kind"]).kind;
|
|
179
|
+
if (kind === "ce-multi-session-v1") {
|
|
180
|
+
const ref = plain(fields.admissionPolicy, "admissionPolicy", ["kind", "profilePath"], ["kind", "profilePath"]);
|
|
181
|
+
const path = label(ref.profilePath, "admissionPolicy.profilePath", 4096);
|
|
182
|
+
if (!isAbsolute(path) || normalize(path) !== path || /[\u0000-\u001f\u007f]/.test(path))
|
|
183
|
+
throw new McpBindingConfigError("admissionPolicy");
|
|
184
|
+
admissionPolicy = Object.freeze({ kind, profilePath: path });
|
|
185
|
+
}
|
|
186
|
+
else if (kind === "ce-live-session-v1" || kind === "ce-live-session-v2") {
|
|
187
|
+
const keys = ["kind", "root", "policyId", "genesisDigest", ...(kind === "ce-live-session-v2" ? ["profilePath", "upgradeSequence"] : [])];
|
|
188
|
+
const ref = plain(fields.admissionPolicy, "admissionPolicy", keys, keys);
|
|
189
|
+
const root = label(ref.root, "admissionPolicy.root", 4096);
|
|
190
|
+
const policyId = label(ref.policyId, "admissionPolicy.policyId", 128);
|
|
191
|
+
if (!isAbsolute(root) || normalize(root) !== root || root === "/" || /[\u0000-\u001f\u007f]/.test(root) ||
|
|
192
|
+
typeof ref.genesisDigest !== "string" || !/^[a-f0-9]{64}$/.test(ref.genesisDigest) || !/^[A-Za-z0-9_-]{1,128}$/.test(policyId))
|
|
193
|
+
throw new McpBindingConfigError("admissionPolicy");
|
|
194
|
+
if (kind === "ce-live-session-v2") {
|
|
195
|
+
const profilePath = label(ref.profilePath, "admissionPolicy.profilePath", 4096);
|
|
196
|
+
if (!isAbsolute(profilePath) || normalize(profilePath) !== profilePath || /[\u0000-\u001f\u007f]/.test(profilePath) ||
|
|
197
|
+
typeof ref.upgradeSequence !== "number" || !Number.isSafeInteger(ref.upgradeSequence) || ref.upgradeSequence < 1 || ref.upgradeSequence > 65536)
|
|
198
|
+
throw new McpBindingConfigError("admissionPolicy");
|
|
199
|
+
admissionPolicy = Object.freeze({ kind, root, policyId, genesisDigest: ref.genesisDigest, profilePath, upgradeSequence: ref.upgradeSequence });
|
|
200
|
+
}
|
|
201
|
+
else
|
|
202
|
+
admissionPolicy = Object.freeze({ kind, root, policyId, genesisDigest: ref.genesisDigest });
|
|
203
|
+
}
|
|
204
|
+
else
|
|
181
205
|
throw new McpBindingConfigError("admissionPolicy");
|
|
182
|
-
admissionPolicy = Object.freeze({ kind: "ce-multi-session-v1", profilePath: path });
|
|
183
206
|
}
|
|
184
207
|
const endpoint = endpointRef(fields.endpoint, "endpoint");
|
|
185
208
|
if (!Array.isArray(fields.recipients))
|
|
@@ -92,11 +92,14 @@ export function assertNativeReadyForTunnel() {
|
|
|
92
92
|
return readiness;
|
|
93
93
|
}
|
|
94
94
|
export async function runNativeCommand(args, options = {}) {
|
|
95
|
+
return (await runNativeCommandOutcome(args, options)).message;
|
|
96
|
+
}
|
|
97
|
+
export async function runNativeCommandOutcome(args, options = {}) {
|
|
95
98
|
const command = args.trim();
|
|
96
99
|
if (command === "" || command === "status" || command === "verify")
|
|
97
|
-
return JSON.stringify(inspectNativeReadiness(options), null, 2);
|
|
100
|
+
return { kind: "ok", message: JSON.stringify(inspectNativeReadiness(options), null, 2) };
|
|
98
101
|
if (command !== "install" && command !== "repair confirm" && command !== "check-updates") {
|
|
99
|
-
return "Usage: /ce-native [status|install|verify|repair confirm|check-updates]. Repair requires explicit repair confirm.";
|
|
102
|
+
return { kind: "usage", message: "Usage: /ce-native [status|install|verify|repair confirm|check-updates]. Repair requires explicit repair confirm." };
|
|
100
103
|
}
|
|
101
104
|
const manifest = options.manifest ?? NATIVE_COMPAT;
|
|
102
105
|
try {
|
|
@@ -112,7 +115,7 @@ export async function runNativeCommand(args, options = {}) {
|
|
|
112
115
|
throw Object.assign(new Error(), { code: "CE_NATIVE_DISCOVERY_FAILED" });
|
|
113
116
|
}
|
|
114
117
|
const differs = metadata.tag_name !== `ce-sqlite-v${manifest.defaultVersion}`;
|
|
115
|
-
return `Current trusted Native version: ${manifest.defaultVersion}. Release discovery ${differs ? "differs; wait for a CE compatibility update" : "matches the trusted version"}. No driver was installed or selected
|
|
118
|
+
return { kind: "ok", message: `Current trusted Native version: ${manifest.defaultVersion}. Release discovery ${differs ? "differs; wait for a CE compatibility update" : "matches the trusted version"}. No driver was installed or selected.` };
|
|
116
119
|
}
|
|
117
120
|
if (!supported(options) || (options.platform !== undefined && options.platform !== process.platform)
|
|
118
121
|
|| (options.arch !== undefined && options.arch !== process.arch))
|
|
@@ -122,10 +125,10 @@ export async function runNativeCommand(args, options = {}) {
|
|
|
122
125
|
...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }) });
|
|
123
126
|
// Selection changes only after the fixed default artifact has been verified.
|
|
124
127
|
writeDriverSelection({ driver: "rust-native", nativeVersion: manifest.defaultVersion }, options.selectionFile);
|
|
125
|
-
return `Trusted Native ${manifest.defaultVersion} installed and selected. Restart Pi to initialize messaging with the installed driver
|
|
128
|
+
return { kind: "ok", message: `Trusted Native ${manifest.defaultVersion} installed and selected. Restart Pi to initialize messaging with the installed driver.` };
|
|
126
129
|
}
|
|
127
130
|
catch (error) {
|
|
128
|
-
return `Native command failed (${errorCode(error)}). Current selection was not changed
|
|
131
|
+
return { kind: "failed", message: `Native command failed (${errorCode(error)}). Current selection was not changed.` };
|
|
129
132
|
}
|
|
130
133
|
}
|
|
131
134
|
//# sourceMappingURL=native-readiness.js.map
|
package/dist/storage/creation.js
CHANGED
|
@@ -69,6 +69,22 @@ function replay(tx, request) {
|
|
|
69
69
|
record: Object.freeze({ entityId: row.entity_id, requestDigest: row.request_digest, createdAt: row.created_at }),
|
|
70
70
|
});
|
|
71
71
|
}
|
|
72
|
+
/** Private advisory lookup for identity preflight. Reuse creation replay checks
|
|
73
|
+
* without entering the create path; this read never establishes authority. */
|
|
74
|
+
export function readExistingExchange(store, input) {
|
|
75
|
+
const request = normalizeCreateExchangeRequest(input);
|
|
76
|
+
const db = store.database;
|
|
77
|
+
if (db.isTransaction)
|
|
78
|
+
throw new Error("Exchange reads cannot run inside an active transaction");
|
|
79
|
+
db.exec("BEGIN");
|
|
80
|
+
try {
|
|
81
|
+
return replay(db, request);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
if (db.isTransaction)
|
|
85
|
+
db.exec("ROLLBACK");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
72
88
|
function hook(action) {
|
|
73
89
|
if (action === undefined)
|
|
74
90
|
return;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { encodeUlid } from "../protocol/identity.js";
|
|
3
3
|
import { captureFields, rejectRequest, requireInstant, requireParticipantId, requireSessionId, SESSION_ID_PATTERN, SESSION_ID_PREFIX, } from "./participant-identity.js";
|
|
4
|
-
import { authorize, clock, hook, readParticipantRow, refuse, runOwned, } from "./participant.js";
|
|
4
|
+
import { authorize, clock, hook, readParticipantRow, readParticipantByEndpoint, readMembershipRow, refuse, runOwned, } from "./participant.js";
|
|
5
5
|
import { parseSessionRow, SESSION_COLUMNS } from "./session-state.js";
|
|
6
6
|
import { requireSingleRowChange } from "./transaction.js";
|
|
7
7
|
/**
|
|
@@ -626,6 +626,8 @@ function readSnapshot(store, body) {
|
|
|
626
626
|
throw new Error("ownership reads cannot run inside an active transaction");
|
|
627
627
|
db.exec("BEGIN");
|
|
628
628
|
try {
|
|
629
|
+
// SAFETY: the SQLite connection supplies prepare/get/all; row consumers
|
|
630
|
+
// validate unparsed SQL values before constructing domain records.
|
|
629
631
|
return body(db);
|
|
630
632
|
}
|
|
631
633
|
finally {
|
|
@@ -633,6 +635,23 @@ function readSnapshot(store, body) {
|
|
|
633
635
|
db.exec("ROLLBACK");
|
|
634
636
|
}
|
|
635
637
|
}
|
|
638
|
+
/** Private advisory aggregate. Callers filter authorized labels before entry.
|
|
639
|
+
* All parsers share one deferred snapshot and one clock; no authority is issued. */
|
|
640
|
+
export function readEndpointObservations(store, exchangeId, endpoints, seams = {}) {
|
|
641
|
+
return readSnapshot(store, (handle) => {
|
|
642
|
+
const observedAt = clock(seams);
|
|
643
|
+
const targets = endpoints.map((endpoint) => {
|
|
644
|
+
// This lookup uses the existing validated parser on the same connection.
|
|
645
|
+
const participant = readParticipantByEndpoint(store, endpoint.adapter, endpoint.endpointId);
|
|
646
|
+
const membership = participant === undefined ? undefined : readMembershipRow(handle, exchangeId, participant.participantId);
|
|
647
|
+
const ownership = participant === undefined ? undefined : loadOwnershipState(handle, participant.participantId).ownership;
|
|
648
|
+
const lease = ownership === undefined ? undefined : evaluateLease(ownership, observedAt);
|
|
649
|
+
const active = lease === "CLOCK_REGRESSION" ? "UNKNOWN" : lease === "ACTIVE" ? "TRUE" : "FALSE";
|
|
650
|
+
return Object.freeze({ ...endpoint, joined: membership !== undefined, active });
|
|
651
|
+
});
|
|
652
|
+
return Object.freeze({ observedAt, targets: Object.freeze(targets) });
|
|
653
|
+
});
|
|
654
|
+
}
|
|
636
655
|
/** One Participant–Session binding, or undefined. Detached rows are not
|
|
637
656
|
* current bindings and are reported as undefined. */
|
|
638
657
|
export function readSessionBinding(store, participantId, sessionId) {
|
|
@@ -665,6 +684,31 @@ export function readCurrentOwnership(store, participantId) {
|
|
|
665
684
|
const pid = requireParticipantId(participantId, "participantId");
|
|
666
685
|
return readSnapshot(store, (handle) => loadOwnershipState(handle, pid).ownership);
|
|
667
686
|
}
|
|
687
|
+
/** Private coherent Owner/lease observation; advisory only, never authorization. */
|
|
688
|
+
export function readOwnershipObservation(store, participantId, seams = {}) {
|
|
689
|
+
const pid = requireParticipantId(participantId, "participantId");
|
|
690
|
+
return readSnapshot(store, handle => {
|
|
691
|
+
const now = clock(seams);
|
|
692
|
+
const { ownership } = loadOwnershipState(handle, pid);
|
|
693
|
+
return Object.freeze({ ownership, lease: ownership === undefined ? "UNOWNED" : evaluateLease(ownership, now) });
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
/** Private fixed-endpoint view for a live transport observation. The Exchange
|
|
697
|
+
* comes from the caller's existing mapping; this read creates no membership. */
|
|
698
|
+
export function readEndpointOwnerObservation(store, endpoint, exchangeId, seams = {}) {
|
|
699
|
+
return readSnapshot(store, handle => {
|
|
700
|
+
const now = clock(seams);
|
|
701
|
+
const participant = readParticipantByEndpoint(store, endpoint.adapter, endpoint.endpointId);
|
|
702
|
+
if (participant === undefined || readMembershipRow(handle, exchangeId, participant.participantId) === undefined)
|
|
703
|
+
return undefined;
|
|
704
|
+
const { ownership } = loadOwnershipState(handle, participant.participantId);
|
|
705
|
+
if (ownership === undefined)
|
|
706
|
+
return undefined;
|
|
707
|
+
return Object.freeze({ endpointId: endpoint.endpointId, registered: true, participantId: participant.participantId,
|
|
708
|
+
sessionId: ownership.sessionId, exchangeId, fencingToken: ownership.fencingToken,
|
|
709
|
+
lease: evaluateLease(ownership, now), leaseExpiresAt: ownership.expiresAt });
|
|
710
|
+
});
|
|
711
|
+
}
|
|
668
712
|
/** Highest fencing token ever allocated for the Participant; 0 when none. */
|
|
669
713
|
export function readFencingHighWater(store, participantId) {
|
|
670
714
|
const pid = requireParticipantId(participantId, "participantId");
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { closeSync, constants, fsyncSync, fstatSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
4
|
+
import { userInfo } from "node:os";
|
|
5
|
+
import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
6
|
+
import { TunnelRefusal } from "./codes.js";
|
|
7
|
+
const refusal = () => new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED");
|
|
8
|
+
const digestPattern = /^[a-f0-9]{64}$/;
|
|
9
|
+
const SELECTION_FILE = "selection.json";
|
|
10
|
+
function checkedPath(value) {
|
|
11
|
+
if (typeof value !== "string" || !isAbsolute(value) || normalize(value) !== value || /[\x00-\x1f\x7f]/.test(value) || value.split("/").includes(".."))
|
|
12
|
+
throw refusal();
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
function owner() {
|
|
16
|
+
if (typeof process.geteuid !== "function" || constants.O_NOFOLLOW === undefined)
|
|
17
|
+
throw refusal();
|
|
18
|
+
return process.geteuid();
|
|
19
|
+
}
|
|
20
|
+
function missing(error) {
|
|
21
|
+
return error?.code === "ENOENT";
|
|
22
|
+
}
|
|
23
|
+
function privateRecord(stat, uid) {
|
|
24
|
+
return stat.isFile() && stat.nlink === 1 && stat.uid === uid && (stat.mode & 0o7777) === 0o600 && stat.size <= 8192;
|
|
25
|
+
}
|
|
26
|
+
/** macOS ACL grants are independent of POSIX mode. Only absent ACLs or
|
|
27
|
+
* deny-only ACLs are admitted; unknown output or probe failure is fail-closed.
|
|
28
|
+
* The OS utility is fixed and never discovered through PATH. */
|
|
29
|
+
function darwinAclOutput(path) {
|
|
30
|
+
if (process.platform !== "darwin")
|
|
31
|
+
return undefined;
|
|
32
|
+
try {
|
|
33
|
+
return execFileSync("/bin/ls", ["-lde", path], {
|
|
34
|
+
cwd: "/", env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
|
|
35
|
+
shell: false, timeout: 5_000, killSignal: "SIGKILL", maxBuffer: 16_384,
|
|
36
|
+
encoding: "utf8", stdio: ["ignore", "pipe", "pipe"],
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw refusal();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Directory injection is solely for isolated tests; production uses the OS account home. */
|
|
44
|
+
export function createBackgroundAuthorizationStore(options = {}) {
|
|
45
|
+
const home = userInfo().homedir;
|
|
46
|
+
const directory = options.directory ?? join(home, ".config/pi-chat-exchange/background-authorization");
|
|
47
|
+
const now = options.now ?? Date.now;
|
|
48
|
+
const seam = options.filesystem ?? {};
|
|
49
|
+
const writeBytes = seam.writeSync ?? writeSync;
|
|
50
|
+
const syncFile = seam.fsyncSync ?? fsyncSync;
|
|
51
|
+
const moveFile = seam.renameSync ?? renameSync;
|
|
52
|
+
function path(profilePath) {
|
|
53
|
+
checkedPath(directory);
|
|
54
|
+
return join(directory, `${createHash("sha256").update(checkedPath(profilePath)).digest("hex")}.json`);
|
|
55
|
+
}
|
|
56
|
+
function selectionPath() {
|
|
57
|
+
checkedPath(directory);
|
|
58
|
+
return join(directory, SELECTION_FILE);
|
|
59
|
+
}
|
|
60
|
+
/** Rejects allow ACLs and unrecognised ACL output. Never mutates the path. */
|
|
61
|
+
function assertAclSafe(target) {
|
|
62
|
+
const output = options.readAcl ? options.readAcl(target) : darwinAclOutput(target);
|
|
63
|
+
if (output === undefined)
|
|
64
|
+
return;
|
|
65
|
+
const lines = output.trimEnd().split("\n");
|
|
66
|
+
const header = lines.shift() ?? "";
|
|
67
|
+
if (!/^[bcdlps-][rwxStTs-]{9}[+@ ]/.test(header))
|
|
68
|
+
throw refusal();
|
|
69
|
+
for (const entry of lines) {
|
|
70
|
+
if (!/^\s*\d+: \S+ deny [a-z_,]+$/.test(entry))
|
|
71
|
+
throw refusal();
|
|
72
|
+
}
|
|
73
|
+
if (header[10] === "+" && lines.length === 0)
|
|
74
|
+
throw refusal();
|
|
75
|
+
}
|
|
76
|
+
function trustedDirectory(uid, create) {
|
|
77
|
+
checkedPath(directory);
|
|
78
|
+
const chain = [];
|
|
79
|
+
for (let cursor = directory;; cursor = dirname(cursor)) {
|
|
80
|
+
chain.unshift(cursor);
|
|
81
|
+
if (dirname(cursor) === cursor)
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
let absent = false;
|
|
85
|
+
for (const entry of chain) {
|
|
86
|
+
let stat;
|
|
87
|
+
try {
|
|
88
|
+
stat = lstatSync(entry);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (!missing(error))
|
|
92
|
+
throw error;
|
|
93
|
+
if (!create) {
|
|
94
|
+
absent = true;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
mkdirSync(entry, { mode: 0o700 });
|
|
98
|
+
stat = lstatSync(entry);
|
|
99
|
+
}
|
|
100
|
+
const inHome = entry === home || entry.startsWith(`${home}/`);
|
|
101
|
+
const stickyRoot = stat.uid === 0 && (stat.mode & 0o1000) !== 0;
|
|
102
|
+
if (!stat.isDirectory() || (stat.uid !== uid && stat.uid !== 0) ||
|
|
103
|
+
((stat.mode & 0o022) !== 0 && !stickyRoot) ||
|
|
104
|
+
(inHome && entry !== home && stat.uid !== uid) ||
|
|
105
|
+
(entry === directory && (stat.uid !== uid || (stat.mode & 0o7777) !== 0o700)))
|
|
106
|
+
throw refusal();
|
|
107
|
+
assertAclSafe(entry);
|
|
108
|
+
}
|
|
109
|
+
return !absent;
|
|
110
|
+
}
|
|
111
|
+
/** Reads a private record file without healing or repairing it. */
|
|
112
|
+
function readPrivateRecord(file, uid) {
|
|
113
|
+
let fd;
|
|
114
|
+
try {
|
|
115
|
+
let before;
|
|
116
|
+
try {
|
|
117
|
+
before = lstatSync(file);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (missing(error))
|
|
121
|
+
return { kind: "absent" };
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
if (!privateRecord(before, uid))
|
|
125
|
+
return { kind: "invalid" };
|
|
126
|
+
assertAclSafe(file);
|
|
127
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
128
|
+
const opened = fstatSync(fd);
|
|
129
|
+
if (!privateRecord(opened, uid) || opened.dev !== before.dev || opened.ino !== before.ino)
|
|
130
|
+
return { kind: "invalid" };
|
|
131
|
+
const buffer = Buffer.alloc(8193);
|
|
132
|
+
let length = 0;
|
|
133
|
+
while (length < buffer.length) {
|
|
134
|
+
const count = readSync(fd, buffer, length, buffer.length - length, null);
|
|
135
|
+
if (count === 0)
|
|
136
|
+
break;
|
|
137
|
+
length += count;
|
|
138
|
+
}
|
|
139
|
+
if (length > 8192)
|
|
140
|
+
return { kind: "invalid" };
|
|
141
|
+
const data = JSON.parse(buffer.subarray(0, length).toString("utf8"));
|
|
142
|
+
if (!data || typeof data !== "object" || Array.isArray(data))
|
|
143
|
+
return { kind: "invalid" };
|
|
144
|
+
return { kind: "valid", record: data };
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return { kind: "invalid" };
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
if (fd !== undefined) {
|
|
151
|
+
try {
|
|
152
|
+
closeSync(fd);
|
|
153
|
+
}
|
|
154
|
+
catch { /* No raw filesystem errors escape inspection. */ }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Durable commit of one private record: write, file sync, rename, directory sync.
|
|
159
|
+
* Failures before the rename are refusals; the previous record still stands.
|
|
160
|
+
* A failure after the rename returns `uncertain` and never claims rollback. */
|
|
161
|
+
function commitRecord(file, bytes) {
|
|
162
|
+
let fd;
|
|
163
|
+
let temp;
|
|
164
|
+
let renamed = false;
|
|
165
|
+
try {
|
|
166
|
+
temp = join(directory, `.${randomUUID()}.tmp`);
|
|
167
|
+
fd = openSync(temp, constants.O_EXCL | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_WRONLY, 0o600);
|
|
168
|
+
const uid = owner();
|
|
169
|
+
if (!privateRecord(fstatSync(fd), uid))
|
|
170
|
+
throw refusal();
|
|
171
|
+
let offset = 0;
|
|
172
|
+
while (offset < bytes.length) {
|
|
173
|
+
const count = writeBytes(fd, bytes, offset, bytes.length - offset);
|
|
174
|
+
if (count === 0)
|
|
175
|
+
throw refusal();
|
|
176
|
+
offset += count;
|
|
177
|
+
}
|
|
178
|
+
syncFile(fd);
|
|
179
|
+
closeSync(fd);
|
|
180
|
+
fd = undefined;
|
|
181
|
+
trustedDirectory(uid, false);
|
|
182
|
+
assertAclSafe(temp);
|
|
183
|
+
moveFile(temp, file);
|
|
184
|
+
renamed = true;
|
|
185
|
+
temp = undefined;
|
|
186
|
+
try {
|
|
187
|
+
fd = openSync(directory, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
188
|
+
syncFile(fd);
|
|
189
|
+
closeSync(fd);
|
|
190
|
+
fd = undefined;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return { committed: true, durability: "uncertain" };
|
|
194
|
+
}
|
|
195
|
+
return { committed: true, durability: "synced" };
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
if (renamed)
|
|
199
|
+
return { committed: true, durability: "uncertain" };
|
|
200
|
+
throw refusal();
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
if (fd !== undefined) {
|
|
204
|
+
try {
|
|
205
|
+
closeSync(fd);
|
|
206
|
+
}
|
|
207
|
+
catch { /* Best effort cleanup. */ }
|
|
208
|
+
}
|
|
209
|
+
if (temp !== undefined) {
|
|
210
|
+
try {
|
|
211
|
+
unlinkSync(temp);
|
|
212
|
+
}
|
|
213
|
+
catch { /* Only remove this write's exclusive temporary file. */ }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function inspect(profilePath) {
|
|
218
|
+
try {
|
|
219
|
+
const file = path(profilePath);
|
|
220
|
+
const uid = owner();
|
|
221
|
+
if (!trustedDirectory(uid, false))
|
|
222
|
+
return { kind: "absent" };
|
|
223
|
+
const found = readPrivateRecord(file, uid);
|
|
224
|
+
if (found.kind !== "valid" || !found.record)
|
|
225
|
+
return found.kind === "absent" ? { kind: "absent" } : { kind: "invalid" };
|
|
226
|
+
const record = found.record;
|
|
227
|
+
const keys = ["version", "uid", "profilePath", "state", "scopeDigest", "updatedAt"];
|
|
228
|
+
if (Object.keys(record).length !== keys.length || !keys.every(key => Object.hasOwn(record, key)) ||
|
|
229
|
+
record.version !== 1 || record.uid !== uid || record.profilePath !== profilePath ||
|
|
230
|
+
(record.state !== "granted" && record.state !== "revoked") ||
|
|
231
|
+
typeof record.scopeDigest !== "string" || !digestPattern.test(record.scopeDigest) ||
|
|
232
|
+
!Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0)
|
|
233
|
+
return { kind: "invalid" };
|
|
234
|
+
// A prior writer may have observed rename but not directory-sync success.
|
|
235
|
+
// Re-establish durability before a visible grant can authorize a fresh process.
|
|
236
|
+
if (record.state === "granted") {
|
|
237
|
+
const directoryFd = openSync(directory, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
238
|
+
try {
|
|
239
|
+
syncFile(directoryFd);
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
closeSync(directoryFd);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return { kind: "valid", state: record.state, scopeDigest: record.scopeDigest };
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return { kind: "invalid" };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function write(profilePath, state, scopeDigest) {
|
|
252
|
+
try {
|
|
253
|
+
const file = path(profilePath);
|
|
254
|
+
const uid = owner();
|
|
255
|
+
const updatedAt = now();
|
|
256
|
+
if ((state !== "granted" && state !== "revoked") || typeof scopeDigest !== "string" || !digestPattern.test(scopeDigest) || !Number.isSafeInteger(updatedAt) || updatedAt < 0)
|
|
257
|
+
throw refusal();
|
|
258
|
+
trustedDirectory(uid, true);
|
|
259
|
+
const existing = lstatSync(file, { throwIfNoEntry: false });
|
|
260
|
+
if (existing) {
|
|
261
|
+
if (existing.nlink !== 1)
|
|
262
|
+
throw refusal();
|
|
263
|
+
assertAclSafe(file);
|
|
264
|
+
}
|
|
265
|
+
const bytes = Buffer.from(JSON.stringify({ version: 1, uid, profilePath, state, scopeDigest, updatedAt }));
|
|
266
|
+
if (bytes.length > 8192)
|
|
267
|
+
throw refusal();
|
|
268
|
+
return commitRecord(file, bytes);
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
if (error?.code === "CE_TUNNEL_BACKGROUND_UNAUTHORIZED")
|
|
272
|
+
throw error;
|
|
273
|
+
throw refusal();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Non-authoritative launch selection. The per-profile grant stays separate. */
|
|
277
|
+
function readSelection() {
|
|
278
|
+
try {
|
|
279
|
+
const uid = owner();
|
|
280
|
+
if (!trustedDirectory(uid, false))
|
|
281
|
+
return { kind: "absent" };
|
|
282
|
+
const found = readPrivateRecord(selectionPath(), uid);
|
|
283
|
+
if (found.kind === "absent")
|
|
284
|
+
return { kind: "absent" };
|
|
285
|
+
if (found.kind !== "valid" || !found.record)
|
|
286
|
+
return { kind: "invalid" };
|
|
287
|
+
const record = found.record;
|
|
288
|
+
const keys = ["version", "uid", "profilePath", "clientPath", "updatedAt"];
|
|
289
|
+
if (Object.keys(record).length !== keys.length || !keys.every(key => Object.hasOwn(record, key)) ||
|
|
290
|
+
record.version !== 1 || record.uid !== uid ||
|
|
291
|
+
typeof record.profilePath !== "string" || typeof record.clientPath !== "string" ||
|
|
292
|
+
!Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0)
|
|
293
|
+
return { kind: "invalid" };
|
|
294
|
+
try {
|
|
295
|
+
checkedPath(record.profilePath);
|
|
296
|
+
checkedPath(record.clientPath);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return { kind: "invalid" };
|
|
300
|
+
}
|
|
301
|
+
const directoryFd = openSync(directory, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
302
|
+
try {
|
|
303
|
+
syncFile(directoryFd);
|
|
304
|
+
}
|
|
305
|
+
finally {
|
|
306
|
+
closeSync(directoryFd);
|
|
307
|
+
}
|
|
308
|
+
return { kind: "valid", profilePath: record.profilePath, clientPath: record.clientPath };
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return { kind: "invalid" };
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function writeSelection(profilePath, clientPath) {
|
|
315
|
+
try {
|
|
316
|
+
const uid = owner();
|
|
317
|
+
const updatedAt = now();
|
|
318
|
+
const normalizedProfile = checkedPath(profilePath);
|
|
319
|
+
const normalizedClient = checkedPath(clientPath);
|
|
320
|
+
if (!Number.isSafeInteger(updatedAt) || updatedAt < 0)
|
|
321
|
+
throw refusal();
|
|
322
|
+
trustedDirectory(uid, true);
|
|
323
|
+
const file = selectionPath();
|
|
324
|
+
const existing = lstatSync(file, { throwIfNoEntry: false });
|
|
325
|
+
if (existing) {
|
|
326
|
+
if (existing.nlink !== 1)
|
|
327
|
+
throw refusal();
|
|
328
|
+
assertAclSafe(file);
|
|
329
|
+
}
|
|
330
|
+
const bytes = Buffer.from(JSON.stringify({ version: 1, uid, profilePath: normalizedProfile, clientPath: normalizedClient, updatedAt }));
|
|
331
|
+
if (bytes.length > 8192)
|
|
332
|
+
throw refusal();
|
|
333
|
+
return commitRecord(file, bytes);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (error?.code === "CE_TUNNEL_BACKGROUND_UNAUTHORIZED")
|
|
337
|
+
throw error;
|
|
338
|
+
throw refusal();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return { inspect, write, path, selectionPath, readSelection, writeSelection };
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=background-authorization.js.map
|