session-peer 0.5.1 → 0.5.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.
@@ -13,6 +13,7 @@ import { basename, isAbsolute, join } from 'node:path';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { TextDecoder } from 'node:util';
15
15
  import { run } from './process.js';
16
+ import { classifyCodexStorage, codexConsumerCwd, codexConsumerSnapshotSync, codexStoragePin, decodeLsofFilename } from './codex-storage.js';
16
17
  import { CANDIDATE_PROFILES, NATIVE_PROFILES, platformProfiled, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
17
18
  import { procOwnedFiles } from './linux-proc.js';
18
19
  import { fileURLToPath } from 'node:url';
@@ -286,6 +287,7 @@ export class BoundedAppServerClient {
286
287
  verifyOwner;
287
288
  nativeQueue;
288
289
  beforeEffect;
290
+ beforeWrite;
289
291
  pending = new Map();
290
292
  observers = new Set();
291
293
  operations = new Set();
@@ -304,13 +306,14 @@ export class BoundedAppServerClient {
304
306
  fault;
305
307
  closing;
306
308
  timer;
307
- constructor(scope, transport, deadlineMs, verifyOwner, nativeQueue = false, beforeEffect = async () => { }) {
309
+ constructor(scope, transport, deadlineMs, verifyOwner, nativeQueue = false, beforeEffect = async () => { }, beforeWrite = () => { }) {
308
310
  this.scope = scope;
309
311
  this.transport = transport;
310
312
  this.deadlineMs = deadlineMs;
311
313
  this.verifyOwner = verifyOwner;
312
314
  this.nativeQueue = nativeQueue;
313
315
  this.beforeEffect = beforeEffect;
316
+ this.beforeWrite = beforeWrite;
314
317
  this.timer = setTimeout(() => this.fail('deadline'), Math.max(1, deadlineMs - performance.now()));
315
318
  transport.input.on('data', this.receive);
316
319
  transport.input.once('end', this.ended);
@@ -327,10 +330,10 @@ export class BoundedAppServerClient {
327
330
  static async connectNativeQueueFixture(scope, transport, deadlineMs, verifyOwner, beforeEffect, nativeVersion = APP_SERVER_EVIDENCE.version, platform = APP_SERVER_EVIDENCE.inspectedPlatform, profiles = NATIVE_PROFILES) {
328
331
  return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, selectNativeProfile({ platform, version: nativeVersion }, validateNativeProfiles(profiles)));
329
332
  }
330
- static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, profile) {
331
- return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, profile);
333
+ static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, profile, beforeWrite) {
334
+ return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, profile, beforeWrite);
332
335
  }
333
- static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, profile) {
336
+ static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, profile, beforeWrite) {
334
337
  let original;
335
338
  try {
336
339
  original = scopeValue(scope);
@@ -348,7 +351,7 @@ export class BoundedAppServerClient {
348
351
  await disposeTransport(transport);
349
352
  throw new AppServerFault('deadline', false);
350
353
  }
351
- const client = new BoundedAppServerClient(original, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect);
354
+ const client = new BoundedAppServerClient(original, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect, beforeWrite);
352
355
  try {
353
356
  await client.owner();
354
357
  if (nativeQueue) {
@@ -404,9 +407,9 @@ export class BoundedAppServerClient {
404
407
  return new Promise((resolve, reject) => {
405
408
  const wait = { reject };
406
409
  this.operations.add(wait);
407
- promise.then(value => { this.operations.delete(wait); resolve(value); }, () => {
410
+ promise.then(value => { this.operations.delete(wait); resolve(value); }, error => {
408
411
  this.operations.delete(wait);
409
- this.fail(failureCode);
412
+ this.fail(error instanceof AppServerFault ? error.code : failureCode);
410
413
  reject(this.fault);
411
414
  });
412
415
  });
@@ -542,6 +545,7 @@ export class BoundedAppServerClient {
542
545
  // owner after that await, before marking an attempt or writing the RPC.
543
546
  // The ledger may already be fenced; this never authorizes a new effect.
544
547
  await this.owner();
548
+ this.beforeWrite();
545
549
  this.check();
546
550
  }
547
551
  return new Promise((resolve, reject) => {
@@ -668,7 +672,7 @@ async function beforeDeadline(deadlineMs, operation, code) {
668
672
  async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
669
673
  if (!pid || pid < 2 || performance.now() >= deadlineMs)
670
674
  throw new AppServerFault('storage_binding_unverified', false);
671
- verifyOpenedSqlite(await darwinOpenedFiles(pid, deadlineMs), home);
675
+ return verifyOpenedSqlite(await darwinOpenedFiles(pid, deadlineMs), home);
672
676
  }
673
677
  async function darwinOpenedFiles(pid, deadlineMs) {
674
678
  // Only the owned app-server PID is queried, never a session inventory/PID scan.
@@ -694,8 +698,14 @@ async function darwinOpenedFiles(pid, deadlineMs) {
694
698
  current = {};
695
699
  files.push(current);
696
700
  }
697
- else if (current && field.startsWith('n'))
698
- current.name = lsofFilename(field.slice(1));
701
+ else if (current && field.startsWith('n')) {
702
+ try {
703
+ current.name = decodeLsofFilename(field.slice(1));
704
+ }
705
+ catch {
706
+ throw new AppServerFault('storage_binding_unverified', false);
707
+ }
708
+ }
699
709
  else if (current && /^D0x[0-9a-f]+$/i.test(field))
700
710
  current.dev = BigInt(field.slice(1));
701
711
  else if (current && /^i[0-9]+$/.test(field))
@@ -707,6 +717,7 @@ async function darwinOpenedFiles(pid, deadlineMs) {
707
717
  // be opened by the owned PID with the inode now at that canonical path.
708
718
  function verifyOpenedSqlite(files, home) {
709
719
  const required = ['state_5.sqlite', 'queue_1.sqlite'];
720
+ const proof = new Map();
710
721
  for (const file of required) {
711
722
  const expected = join(home, file);
712
723
  const opened = files.filter(row => row.name && [file, file + '-wal', file + '-shm'].includes(basename(row.name)));
@@ -719,12 +730,52 @@ function verifyOpenedSqlite(files, home) {
719
730
  const canonical = lstatSync(row.name, { bigint: true });
720
731
  if (!canonical.isFile() || canonical.isSymbolicLink() || row.dev !== canonical.dev || row.ino !== canonical.ino)
721
732
  throw new Error('storage identity changed');
733
+ const prior = proof.get(row.name);
734
+ if (prior && (prior.dev !== row.dev || prior.ino !== row.ino))
735
+ throw new Error('conflicting opened identities');
736
+ // Retain the opened FD's identity, not a later sample of the pathname.
737
+ proof.set(row.name, Object.freeze({ path: row.name, dev: row.dev, ino: row.ino }));
722
738
  }
723
739
  catch {
724
740
  throw new AppServerFault('storage_binding_unverified', false);
725
741
  }
726
742
  }
727
743
  }
744
+ // The fixed WAL/SHM paths may not be opened yet. Retain their named presence
745
+ // and identity too, without claiming FD evidence for these additional paths.
746
+ for (const file of required)
747
+ for (const suffix of ['', '-wal', '-shm']) {
748
+ const path = join(home, file + suffix);
749
+ if (proof.has(path))
750
+ continue;
751
+ try {
752
+ const info = lstatSync(path, { bigint: true });
753
+ if (!info.isFile() || info.isSymbolicLink())
754
+ throw new Error();
755
+ proof.set(path, Object.freeze({ path, dev: info.dev, ino: info.ino }));
756
+ }
757
+ catch (error) {
758
+ if (error.code !== 'ENOENT')
759
+ throw new AppServerFault('storage_binding_unverified', false);
760
+ proof.set(path, Object.freeze({ path, dev: null, ino: null }));
761
+ }
762
+ }
763
+ return Object.freeze([...proof.values()]);
764
+ }
765
+ function revalidateSqliteBinding(proof) {
766
+ if (!proof)
767
+ throw new AppServerFault('storage_binding_unverified', false);
768
+ for (const expected of proof) {
769
+ try {
770
+ const info = lstatSync(expected.path, { bigint: true });
771
+ if (!info.isFile() || info.isSymbolicLink() || info.dev !== expected.dev || info.ino !== expected.ino)
772
+ throw new Error();
773
+ }
774
+ catch (error) {
775
+ if (expected.dev !== null || error.code !== 'ENOENT')
776
+ throw new AppServerFault('storage_binding_unverified', false);
777
+ }
778
+ }
728
779
  }
729
780
  // Synchronous native-profile I/O (executable digest, procfs walk) runs in an
730
781
  // owned worker. Supervisor refusal boundary for that worker only: run()
@@ -797,38 +848,7 @@ export async function verifyProcfsSqliteBinding(pid, home, deadlineMs, binary, r
797
848
  }
798
849
  if (performance.now() >= deadlineMs)
799
850
  throw new AppServerFault('deadline', false);
800
- verifyOpenedSqlite(files, home);
801
- }
802
- // lsof field output escapes backslashes and non-ASCII bytes even with NUL field
803
- // delimiters. Decode the protected system tool's filename representation, then
804
- // compare exact canonical paths; never accept a prefix/substring match.
805
- function lsofFilename(raw) {
806
- const bytes = [];
807
- for (let i = 0; i < raw.length; i++) {
808
- if (raw[i] !== '\\') {
809
- const char = String.fromCodePoint(raw.codePointAt(i));
810
- bytes.push(...Buffer.from(char));
811
- i += char.length - 1;
812
- continue;
813
- }
814
- const next = raw[++i];
815
- if (next === '\\') {
816
- bytes.push(92);
817
- continue;
818
- }
819
- if (next === 'x' && /^[0-9a-f]{2}$/i.test(raw.slice(i + 1, i + 3))) {
820
- bytes.push(parseInt(raw.slice(i + 1, i + 3), 16));
821
- i += 2;
822
- continue;
823
- }
824
- throw new AppServerFault('storage_binding_unverified', false);
825
- }
826
- try {
827
- return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(bytes));
828
- }
829
- catch {
830
- throw new AppServerFault('storage_binding_unverified', false);
831
- }
851
+ return verifyOpenedSqlite(files, home);
832
852
  }
833
853
  function executableIdentity(binary) {
834
854
  try {
@@ -870,21 +890,39 @@ export async function nativeQueueOnceWithProfiles(options, table) {
870
890
  // Reject malformed effect input before even a version probe or bootstrap can
871
891
  // start the binary and access/create native files in the selected home.
872
892
  validateQueueInput(options, false);
873
- // In the qualified versions config.sqlite_home precedes CODEX_SQLITE_HOME. Pin BOTH env and
874
- // a quoted CLI value so an ordinary config A->B->A load cannot redirect us.
875
- // Managed policy can still supersede the CLI pin, hence the FD-path check.
876
- const env = { ...(options.env ?? process.env), CODEX_HOME: original.codexHome,
877
- CODEX_SQLITE_HOME: original.codexHome };
878
893
  if (!await beforeDeadline(options.deadlineMs, () => options.verifyOwner(original), 'owner_changed'))
879
894
  throw new AppServerFault('owner_changed', false);
880
895
  if (performance.now() >= options.deadlineMs)
881
896
  throw new AppServerFault('deadline', false);
897
+ const consumerCwd = await codexConsumerCwd(original.codexHome, original.threadId).catch(() => {
898
+ throw new AppServerFault('storage_binding_unverified', false);
899
+ });
900
+ const checkStorage = (version) => {
901
+ const value = classifyCodexStorage({ home: original.codexHome, queueCwd: original.codexHome,
902
+ consumerCwds: [consumerCwd], ownedAppServer: true, version, environment: options.env ?? process.env });
903
+ if (value.status !== 'classified')
904
+ throw new AppServerFault('storage_binding_unverified', false);
905
+ return value;
906
+ };
907
+ const initialStorage = checkStorage();
908
+ const consumerDatabase = codexConsumerSnapshotSync(original.codexHome, original.threadId).database;
909
+ const revalidateStorage = async (version) => {
910
+ if (await codexConsumerCwd(original.codexHome, original.threadId).catch(() => '') !== consumerCwd ||
911
+ checkStorage(version).fingerprint !== initialStorage.fingerprint)
912
+ throw new AppServerFault('storage_binding_unverified', false);
913
+ };
914
+ // In the qualified versions config.sqlite_home precedes CODEX_SQLITE_HOME. Pin BOTH env and
915
+ // a quoted CLI value so an ordinary config A->B->A load cannot redirect us.
916
+ // Managed policy can still supersede the CLI pin, hence the FD-path check.
917
+ const inherited = Object.fromEntries(Object.entries(options.env ?? process.env).filter(([key]) => !['CODEX_HOME', 'CODEX_SQLITE_HOME'].includes(key.toUpperCase())));
918
+ const env = { ...inherited, CODEX_HOME: original.codexHome,
919
+ CODEX_SQLITE_HOME: original.codexHome, PWD: initialStorage.queueCwd };
882
920
  const binaryIdentity = executableIdentity(options.binary);
883
921
  const probeRemaining = options.deadlineMs - performance.now();
884
922
  if (probeRemaining <= 0)
885
923
  throw new AppServerFault('deadline', false);
886
924
  const version = await run(options.binary, ['--version'], {
887
- env, timeout: probeRemaining, limit: 4096,
925
+ env, cwd: initialStorage.queueCwd, timeout: probeRemaining, limit: 4096,
888
926
  });
889
927
  if (performance.now() >= options.deadlineMs)
890
928
  throw new AppServerFault('deadline', false);
@@ -894,6 +932,7 @@ export async function nativeQueueOnceWithProfiles(options, table) {
894
932
  throw new AppServerFault('unsupported_version', false);
895
933
  }
896
934
  verifyExecutableIdentity(options.binary, binaryIdentity);
935
+ await revalidateStorage(nativeVersion);
897
936
  if (performance.now() >= options.deadlineMs)
898
937
  throw new AppServerFault('deadline', false);
899
938
  if (profile.artifact) {
@@ -917,8 +956,9 @@ export async function nativeQueueOnceWithProfiles(options, table) {
917
956
  verifyOwnedSqliteBinding(pid, original.codexHome, options.deadlineMs);
918
957
  const transport = { qualification: 'native_queue_only_stdio',
919
958
  ...spawnOwnedStdio(options.binary, ['app-server', '--stdio', '-c', 'analytics.enabled=false',
920
- '-c', `sqlite_home=${JSON.stringify(original.codexHome)}`], env, original.codexHome) };
959
+ '-c', codexStoragePin(original.codexHome)], env, original.codexHome) };
921
960
  let client;
961
+ let lastBinding;
922
962
  try {
923
963
  verifyExecutableIdentity(options.binary, binaryIdentity);
924
964
  let effectGuarded = false;
@@ -927,12 +967,34 @@ export async function nativeQueueOnceWithProfiles(options, table) {
927
967
  if (valid && effectGuarded) {
928
968
  // Run after the LAST asynchronous owner verification. The durable guard
929
969
  // and owner probe can both await I/O and change canonical file bindings.
930
- verifyExecutableIdentity(options.binary, binaryIdentity);
931
- await bind(transport.pid);
970
+ try {
971
+ await options.verifyStorage?.();
972
+ await revalidateStorage(nativeVersion);
973
+ lastBinding = await bind(transport.pid);
974
+ }
975
+ catch (error) {
976
+ throw error instanceof AppServerFault ? error : new AppServerFault('storage_binding_unverified', false);
977
+ }
932
978
  }
933
979
  return valid;
934
- }, async () => { await options.beforeEffect(); effectGuarded = true; }, profile);
935
- await bind(transport.pid);
980
+ }, async () => { await options.beforeEffect(); effectGuarded = true; }, profile, () => {
981
+ // The effect writer calls this after its final await, before setting the
982
+ // attempted marker. No async callback follows these continuity checks.
983
+ try {
984
+ options.verifyStorageSync?.();
985
+ if (checkStorage(nativeVersion).fingerprint !== initialStorage.fingerprint)
986
+ throw new Error();
987
+ const current = codexConsumerSnapshotSync(original.codexHome, original.threadId);
988
+ if (current.database !== consumerDatabase || current.cwd !== consumerCwd)
989
+ throw new Error();
990
+ revalidateSqliteBinding(lastBinding);
991
+ verifyExecutableIdentity(options.binary, binaryIdentity);
992
+ }
993
+ catch (error) {
994
+ throw error instanceof AppServerFault ? error : new AppServerFault('storage_binding_unverified', false);
995
+ }
996
+ });
997
+ lastBinding = await bind(transport.pid);
936
998
  return await client.queueOnce({ clientUserMessageId: options.clientUserMessageId, message: options.message });
937
999
  }
938
1000
  finally {
@@ -0,0 +1,46 @@
1
+ export declare const STORAGE_LOADER_VERSIONS: readonly ["0.160.1", "0.162.1", "0.165.0"];
2
+ export declare function codexStoragePin(home: string): string;
3
+ type Layer = 'home' | 'system' | 'requirements' | 'legacy' | 'preferences' | 'project' | 'context' | 'daemon' | 'cloud';
4
+ export type StorageCheck = {
5
+ status: 'classified' | 'unsupported' | 'unknown';
6
+ code: string;
7
+ verification: 'local_loader_layers';
8
+ loaderVersion: string | null;
9
+ loaderVersionVerified: boolean;
10
+ localLoaderPlatformSupported: boolean;
11
+ layers: Layer[];
12
+ consumerContext: 'inspected' | 'not_provided';
13
+ cloudConfiguration: 'ineligible_by_metadata' | 'requires_owned_storage_binding' | 'unclassified';
14
+ fingerprint: string;
15
+ queueCwd?: string;
16
+ };
17
+ export type StorageOptions = {
18
+ home: string;
19
+ queueCwd?: string;
20
+ consumerCwds?: string[];
21
+ version?: string;
22
+ platform?: string;
23
+ ownedAppServer?: boolean;
24
+ systemBase?: string;
25
+ preferences?: () => {
26
+ forced: boolean;
27
+ value: unknown;
28
+ }[];
29
+ environment?: NodeJS.ProcessEnv;
30
+ };
31
+ export declare function managedStoragePreferences(): {
32
+ forced: boolean;
33
+ value: unknown;
34
+ }[];
35
+ export declare function storageDiagnostic(check: StorageCheck): Omit<StorageCheck, 'fingerprint' | 'queueCwd'>;
36
+ export declare function classifyCodexStorage(options: StorageOptions): StorageCheck;
37
+ export declare function codexStateIdentity(home: string): string;
38
+ export declare function codexConsumerSnapshotSync(home: string, threadId: string): {
39
+ cwd: string;
40
+ database: string;
41
+ };
42
+ export declare function codexConsumerCwd(home: string, threadId: string): Promise<string>;
43
+ export declare function codexWriterCwd(pid: number): string;
44
+ export declare function decodeLsofFilename(raw: string): string;
45
+ export declare function codexWriterStorage(pid: number, home: string): void;
46
+ export {};