@zieglar/pi-chat-exchange 0.3.4 → 0.3.6

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.
@@ -0,0 +1,138 @@
1
+ import fs from "node:fs";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { basename, dirname, join } from "node:path";
4
+ import type { NativeInboundPolicy } from "./native-inbound.js";
5
+
6
+ export interface NativeInboundIdentity {
7
+ readonly runtimeSessionId: string;
8
+ readonly endpointId: string;
9
+ readonly exchangeId: string;
10
+ }
11
+ type NativeInboundReadIdentity = Omit<NativeInboundIdentity, "exchangeId"> & { readonly exchangeId?: string };
12
+
13
+ export type NativeInboundPolicyInspection =
14
+ | { readonly status: "missing" }
15
+ | { readonly status: "enabled" | "disabled"; readonly policy: NativeInboundPolicy; readonly revision: string }
16
+ | { readonly status: "invalid"; readonly code: "INBOUND_POLICY_INVALID" };
17
+
18
+ const sha = (text: string): string => createHash("sha256").update(text).digest("hex");
19
+ const fail = (): never => { throw new Error("INBOUND_POLICY_INVALID"); };
20
+ const time = (text: string): number => typeof text === "string" && /(?:Z|[+-]\d{2}:\d{2})$/.test(text) ? Date.parse(text) : NaN;
21
+ const stamp = (stat: fs.BigIntStats): string => sha([stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs, stat.size].join(":"));
22
+
23
+ export function nativeInboundPolicyPath(profilePath: string, runtimeSessionId: string): string {
24
+ if (!profilePath.startsWith("/") || !runtimeSessionId) fail();
25
+ return join(profilePath + ".native-inbound", `${sha(runtimeSessionId)}.json`);
26
+ }
27
+
28
+ export function readNativeInboundPolicy(
29
+ path: string,
30
+ identity: NativeInboundReadIdentity,
31
+ now: number,
32
+ ): { readonly policy: NativeInboundPolicy; readonly revision: string } | undefined {
33
+ const uid = typeof process.getuid === "function" ? process.getuid() : fail();
34
+ if (!Number.isFinite(now)) fail();
35
+ let raw: string | undefined;
36
+ let revision: string;
37
+ try {
38
+ const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
39
+ try {
40
+ const stat = fs.fstatSync(fd, { bigint: true });
41
+ if (!stat.isFile() || stat.uid !== BigInt(uid) || (stat.mode & 0o077n) !== 0n || stat.nlink !== 1n || stat.size > 4096n) fail();
42
+ revision = stamp(stat);
43
+ raw = fs.readFileSync(fd, "utf8");
44
+ if (stamp(fs.fstatSync(fd, { bigint: true })) !== revision) fail();
45
+ } finally { fs.closeSync(fd); }
46
+ } catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
48
+ fail();
49
+ }
50
+ let value: unknown;
51
+ try { value = JSON.parse(raw!); } catch { fail(); }
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail();
53
+ const policy = value as Record<string, unknown>;
54
+ const keys = ["version", "enabled", "runtimeSessionId", "endpointId", "exchangeId", "from", "activatedAt", "afterAuditSequence", "maxAgeSeconds"];
55
+ if (Object.keys(policy).sort().join() !== keys.sort().join() || policy.version !== 1 || typeof policy.enabled !== "boolean" ||
56
+ policy.runtimeSessionId !== identity.runtimeSessionId || policy.endpointId !== identity.endpointId ||
57
+ (identity.exchangeId !== undefined && policy.exchangeId !== identity.exchangeId) || typeof policy.exchangeId !== "string" || policy.exchangeId.length === 0 ||
58
+ typeof policy.from !== "string" || policy.from.length === 0 || typeof policy.activatedAt !== "string" ||
59
+ !Number.isSafeInteger(policy.afterAuditSequence) || (policy.afterAuditSequence as number) < 0 ||
60
+ !Number.isSafeInteger(policy.maxAgeSeconds) || (policy.maxAgeSeconds as number) < 1 || (policy.maxAgeSeconds as number) > 300 ||
61
+ !Number.isFinite(time(policy.activatedAt)) || time(policy.activatedAt) > now) fail();
62
+ return { policy: policy as unknown as NativeInboundPolicy, revision: revision! };
63
+ }
64
+
65
+ export function inspectNativeInboundPolicy(path: string, identity: NativeInboundReadIdentity, now: number): NativeInboundPolicyInspection {
66
+ try {
67
+ const observed = readNativeInboundPolicy(path, identity, now);
68
+ if (!observed) return { status: "missing" };
69
+ return { status: observed.policy.enabled ? "enabled" : "disabled", ...observed };
70
+ } catch {
71
+ return { status: "invalid", code: "INBOUND_POLICY_INVALID" };
72
+ }
73
+ }
74
+
75
+ function ensureDirectory(path: string): void {
76
+ const directory = dirname(path);
77
+ try { fs.mkdirSync(directory, { mode: 0o700 }); } catch (error) {
78
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") fail();
79
+ }
80
+ const stat = fs.lstatSync(directory, { bigint: true });
81
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid!()) || (stat.mode & 0o077n) !== 0n) fail();
82
+ fs.chmodSync(directory, 0o700);
83
+ }
84
+
85
+ function writePolicy(path: string, policy: NativeInboundPolicy, now: number): NativeInboundPolicy {
86
+ ensureDirectory(path);
87
+ // Replacement is permitted only for a policy that already passes the same
88
+ // ownership, link, mode, shape and current-Session identity checks. A bad
89
+ // target is evidence to stop, not something activation may erase.
90
+ try {
91
+ fs.lstatSync(path);
92
+ if (!readNativeInboundPolicy(path, policy, now)) fail();
93
+ } catch (error) {
94
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") fail();
95
+ }
96
+ const directory = dirname(path);
97
+ const temporary = join(directory, `.${basename(path)}.${randomUUID()}.tmp`);
98
+ let fd: number | undefined;
99
+ try {
100
+ fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
101
+ fs.writeFileSync(fd, `${JSON.stringify(policy, null, 2)}\n`, "utf8");
102
+ fs.fsyncSync(fd); fs.closeSync(fd); fd = undefined;
103
+ fs.renameSync(temporary, path);
104
+ const directoryFd = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
105
+ try { fs.fsyncSync(directoryFd); } finally { fs.closeSync(directoryFd); }
106
+ } catch {
107
+ if (fd !== undefined) fs.closeSync(fd);
108
+ try { fs.unlinkSync(temporary); } catch { /* nothing durable to clean */ }
109
+ fail();
110
+ }
111
+ const verified = readNativeInboundPolicy(path, policy, now);
112
+ if (!verified || JSON.stringify(verified.policy) !== JSON.stringify(policy)) return fail();
113
+ return verified.policy;
114
+ }
115
+
116
+ export function enableNativeInboundPolicy(input: {
117
+ readonly path: string;
118
+ readonly identity: NativeInboundIdentity;
119
+ readonly from: string;
120
+ readonly afterAuditSequence: number;
121
+ readonly now: number;
122
+ }): NativeInboundPolicy {
123
+ if (!input.from || !Number.isSafeInteger(input.afterAuditSequence) || input.afterAuditSequence < 0 || !Number.isFinite(input.now)) fail();
124
+ return writePolicy(input.path, {
125
+ version: 1, enabled: true, ...input.identity, from: input.from,
126
+ activatedAt: new Date(input.now).toISOString(), afterAuditSequence: input.afterAuditSequence, maxAgeSeconds: 300,
127
+ }, input.now);
128
+ }
129
+
130
+ export function disableNativeInboundPolicy(input: {
131
+ readonly path: string;
132
+ readonly identity: NativeInboundIdentity;
133
+ readonly now: number;
134
+ }): NativeInboundPolicy {
135
+ const current = readNativeInboundPolicy(input.path, input.identity, input.now);
136
+ if (!current) return fail();
137
+ return writePolicy(input.path, { ...current.policy, enabled: false }, input.now);
138
+ }
@@ -1,8 +1,8 @@
1
- import fs from "node:fs";
2
1
  import { createHash } from "node:crypto";
3
2
  import type { CeReadResult } from "../dist/endpoints/pi/session-host.js";
4
3
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
5
4
  import { validateFeedbackClassification, validateFeedbackTerminal, type FeedbackAssociation, type OwnershipFeedbackPort } from "./ownership-feedback.js";
5
+ import { readNativeInboundPolicy } from "./native-inbound-policy.js";
6
6
 
7
7
  type Metadata = Omit<CeReadResult, "state">;
8
8
  type Entries = ReadonlyArray<Record<string, unknown>>;
@@ -26,6 +26,7 @@ interface InboundOptions {
26
26
  append(customType: string, data: unknown): void;
27
27
  listInbox(input: { afterAuditSequence: number; pageSize: number; rawScanLimit: number }): { messages: ReadonlyArray<{ messageId: string; auditSequence: number }>; continuationAuditSequence: number | null; scanBudgetExhausted: boolean };
28
28
  readMetadata(input: { messageId: string }): Metadata;
29
+ canReceiveTask(messageId: string): boolean;
29
30
  wake(input: { messageId: string; auditSequence: number; policyDigest: string; policyRevision: string }): void;
30
31
  readonly feedback?: OwnershipFeedbackPort | undefined;
31
32
  controlWake?(input: { messageId: string; auditSequence: number; policyDigest: string; policyRevision: string }): void;
@@ -37,38 +38,6 @@ const metadataKeys = ["messageId", "exchangeId", "from", "to", "payloadDigest",
37
38
  const sha = (text: string) => createHash("sha256").update(text).digest("hex");
38
39
  const time = (text: string) => typeof text === "string" && /(?:Z|[+-]\d{2}:\d{2})$/.test(text) ? Date.parse(text) : NaN;
39
40
  function failure(code: string): never { throw new Error(code); }
40
-
41
- function readPolicy(file: string, session: string, endpoint: string, now: number): { policy: NativeInboundPolicy; revision: string } | undefined {
42
- let raw: string | undefined;
43
- let revision: string | undefined;
44
- const stamp = (s: fs.BigIntStats): string => sha([s.dev, s.ino, s.mtimeNs, s.ctimeNs, s.size].join(":"));
45
- try {
46
- const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
47
- try {
48
- const stat = fs.fstatSync(fd, { bigint: true });
49
- if (!stat.isFile() || stat.uid !== BigInt(process.getuid!()) || (stat.mode & 0o077n) !== 0n || stat.nlink !== 1n || stat.size > 4096n) failure("INBOUND_POLICY_INVALID");
50
- revision = stamp(stat);
51
- raw = fs.readFileSync(fd, "utf8");
52
- if (stamp(fs.fstatSync(fd, { bigint: true })) !== revision) failure("INBOUND_POLICY_CHANGED");
53
- } finally { fs.closeSync(fd); }
54
- } catch (error) {
55
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
56
- failure("INBOUND_POLICY_INVALID");
57
- }
58
- let value: unknown;
59
- try { value = JSON.parse(raw!); } catch { failure("INBOUND_POLICY_INVALID"); }
60
- if (!value || typeof value !== "object" || Array.isArray(value)) failure("INBOUND_POLICY_INVALID");
61
- const policy = value as Record<string, unknown>;
62
- const keys = ["version", "enabled", "runtimeSessionId", "endpointId", "exchangeId", "from", "activatedAt", "afterAuditSequence", "maxAgeSeconds"];
63
- if (Object.keys(policy).sort().join() !== keys.sort().join() || policy.version !== 1 || typeof policy.enabled !== "boolean" ||
64
- policy.runtimeSessionId !== session || policy.endpointId !== endpoint ||
65
- !["exchangeId", "from", "activatedAt"].every(key => typeof policy[key] === "string" && (policy[key] as string).length > 0) ||
66
- !Number.isSafeInteger(policy.afterAuditSequence) || (policy.afterAuditSequence as number) < 0 ||
67
- !Number.isSafeInteger(policy.maxAgeSeconds) || (policy.maxAgeSeconds as number) < 1 || (policy.maxAgeSeconds as number) > 300 ||
68
- !Number.isFinite(time(policy.activatedAt as string)) || time(policy.activatedAt as string) > now) failure("INBOUND_POLICY_INVALID");
69
- // SAFETY: the closed-key and scalar checks above validate every policy field.
70
- return policy.enabled ? { policy: policy as unknown as NativeInboundPolicy, revision: revision! } : undefined;
71
- }
72
41
  function metadata(input: unknown, policy: NativeInboundPolicy, messageId: string, now: number): Metadata | undefined {
73
42
  if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
74
43
  const value = input as Record<string, unknown>;
@@ -119,8 +88,8 @@ export function createNativeInbound(options: InboundOptions) {
119
88
  if (closed) failure("INBOUND_CLOSED");
120
89
  if (options.getSessionId() !== options.runtimeSessionId) failure("INBOUND_SESSION_CHANGED");
121
90
  if (typeof process.getuid !== "function") failure("INBOUND_POLICY_INVALID");
122
- const observed = readPolicy(options.policyPath, options.runtimeSessionId, options.endpointId, options.now());
123
- if (!observed) { if (expectedDigest) failure("INBOUND_DISABLED"); return undefined; }
91
+ const observed = readNativeInboundPolicy(options.policyPath, { runtimeSessionId: options.runtimeSessionId, endpointId: options.endpointId }, options.now());
92
+ if (!observed || !observed.policy.enabled) { if (expectedDigest) failure("INBOUND_DISABLED"); return undefined; }
124
93
  const policy = observed.policy;
125
94
  const policyDigest = sha(JSON.stringify(policy));
126
95
  if (expectedDigest !== undefined && policyDigest !== expectedDigest) failure("INBOUND_POLICY_CHANGED");
@@ -143,6 +112,7 @@ export function createNativeInbound(options: InboundOptions) {
143
112
  const records = history();
144
113
  for (const candidate of result.messages) {
145
114
  if (records.some(entry => entry.data.messageId === candidate.messageId)) continue;
115
+ if (!options.canReceiveTask(candidate.messageId)) continue;
146
116
  const admittedAt = options.now();
147
117
  const fresh = metadata(options.readMetadata({ messageId: candidate.messageId }), current.policy, candidate.messageId, admittedAt);
148
118
  if (!fresh) continue;
@@ -1,6 +1,7 @@
1
1
  /** Configuration-only onboarding. Transport and messaging authority stay with Connect. */
2
2
  import { createHash } from "node:crypto";
3
3
  import { readFileSync } from "node:fs";
4
+ import { basename } from "node:path";
4
5
  import { readLivePolicy, createLivePolicyRegistration, type LiveSnapshot } from "../dist/tunnel/live-session-policy.js";
5
6
  import { readLiveSelectedSessionPolicy } from "./live-session-profile.js";
6
7
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit";
@@ -19,6 +20,7 @@ export class SessionOnboardingRefusal extends Error {
19
20
  interface OnboardingContext {
20
21
  readonly mode: string;
21
22
  readonly hasUI: boolean;
23
+ readonly cwd?: string;
22
24
  readonly sessionManager: { getSessionId(): string };
23
25
  readonly ui: {
24
26
  confirm?(title: string, message: string, options?: { signal?: AbortSignal; timeout?: number }): Promise<boolean>;
@@ -116,7 +118,9 @@ async function prepareLiveSession(ctx: OnboardingContext, options: Parameters<ty
116
118
  const old = selected.manifest.registrations.find(r => r.runtimeSessionId === runtimeSessionId);
117
119
  if (old?.status === "revoked") throw new SessionOnboardingRefusal("registration-revoked", "Connect cannot restore a revoked registration. Fresh operator confirmation is required.");
118
120
  if (old?.payloadRead && old.ack) return "ready";
119
- const endpointId = old?.endpointId ?? "pi/session-" + createHash("sha256").update(JSON.stringify(["ce-session-onboarding-v1", runtimeSessionId])).digest("hex").slice(0, 32);
121
+ const project = typeof ctx.cwd === "string" ? basename(ctx.cwd).replace(/[^\p{L}\p{N}._-]+/gu, "-").slice(0, 40) : "";
122
+ const visibleProject = /cap_[0-9a-f]{16,}/i.test(project) ? "" : project;
123
+ const endpointId = old?.endpointId ?? "pi/session-" + createHash("sha256").update(JSON.stringify(["ce-session-onboarding-v1", runtimeSessionId])).digest("hex").slice(0, 32) + (visibleProject ? `-${visibleProject}` : "");
120
124
  if (selected.manifest.chatgptEndpoint.endpointId === endpointId || selected.manifest.registrations.some(r => r.endpointId === endpointId && r !== old)) throw new SessionOnboardingRefusal("endpoint-collision", "Endpoint collision; nothing was overwritten.");
121
125
  if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.confirm !== "function") throw new SessionOnboardingRefusal("input-unavailable", "Open an interactive Pi TUI to confirm live messaging grants.");
122
126
  const api = createLivePolicyRegistration({ ref: selected.ref });