@pi-chamber/web 0.9.0 → 0.9.3

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 (106) hide show
  1. package/README.md +24 -8
  2. package/bin/cli.js +11 -1
  3. package/bin/cli.test.js +18 -0
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +7 -3
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +28 -6
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-logs.js +22 -4
  12. package/bin/lib/commands-serve.js +10 -2
  13. package/bin/lib/commands-tunnel.js +14 -0
  14. package/bin/lib/commands-update.js +18 -14
  15. package/bin/lib/commands-update.test.js +2 -1
  16. package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DuGmiPZ5.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-CV-iReyY.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-DVd1MLPB.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CPnW4I90.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Dj_7hgX_.js} +3 -3
  21. package/dist/assets/JsonTreeView-Cyy0lEZR.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-C7dA3U29.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-qeik5qtT.js} +1 -1
  27. package/dist/assets/SettingsView-C57uV1YS.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Bbay2W76.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-CRTiN1CH.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-iqwryMNU.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-szfZ0Syc.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-BC3ie230.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-DbThKVSf.js} +1 -1
  36. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  37. package/dist/assets/{index-yWgKW2Fx.js → index-KIdiBFJs.js} +4 -4
  38. package/dist/assets/{index-D1IaU-Q7.js → index-v6K3L94m.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CbrmvrM6.js} +1 -1
  41. package/dist/assets/{main-DcAMXRSi.js → main-4PkIvzf4.js} +7 -7
  42. package/dist/assets/{main-DhvLreEl.js → main-DMyWi0qs.js} +2 -2
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-BD5WkOKU.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-CLMNhna4.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-rWMDwhtQ.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DLy2YoQg.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-CySRuLbN.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-DfuJVB15.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-jITqE8PV.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-C9wXMuCp.js} +2 -2
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +3 -3
  60. package/server/index.js +26 -7
  61. package/server/lib/client-auth/pairing.js +13 -2
  62. package/server/lib/client-auth/remote-clients.js +13 -2
  63. package/server/lib/fs/DOCUMENTATION.md +3 -1
  64. package/server/lib/fs/routes.test.js +74 -0
  65. package/server/lib/git/DOCUMENTATION.md +1 -1
  66. package/server/lib/git/identity-storage.js +10 -1
  67. package/server/lib/package-manager.js +1 -1
  68. package/server/lib/package-manager.test.js +11 -0
  69. package/server/lib/pi/archive-store.js +3 -2
  70. package/server/lib/pi/model-config-store.js +6 -2
  71. package/server/lib/pi/routes.js +46 -3
  72. package/server/lib/pi/routes.test.js +53 -0
  73. package/server/lib/pi/session-daemon/DOCUMENTATION.md +15 -9
  74. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  75. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  76. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  77. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  78. package/server/lib/pi/session-daemon/session-daemon.js +353 -66
  79. package/server/lib/pi/session-daemon/session-daemon.test.js +348 -0
  80. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  81. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  82. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  83. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  84. package/server/lib/pi/session-folders-store.js +20 -2
  85. package/server/lib/pi/session-folders-store.test.js +17 -0
  86. package/server/lib/pi/settings-store.js +3 -2
  87. package/server/lib/pi/snippets-store.js +4 -1
  88. package/server/lib/pi/ui-settings-store.js +130 -24
  89. package/server/lib/pi/ui-settings-store.test.js +58 -7
  90. package/server/lib/server/cross-process-lock.js +112 -0
  91. package/server/lib/server/cross-process-lock.test.js +70 -0
  92. package/server/lib/server/server-profile.js +110 -0
  93. package/server/lib/server/server-profile.test.js +58 -0
  94. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  95. package/server/lib/server/tunnel-service.js +8 -1
  96. package/server/lib/stt/config-store.js +3 -2
  97. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  98. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  99. package/server/lib/ui-auth/ui-auth.js +9 -2
  100. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  101. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  102. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  103. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  104. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  105. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  106. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+
5
+ const RETRYABLE_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY', 'EAGAIN']);
6
+ const FRESH_LOCK_MS = 250;
7
+
8
+ export class CrossProcessLockError extends Error {
9
+ constructor(code, message = 'The cross-process lock is unavailable.') {
10
+ super(message);
11
+ this.code = code;
12
+ }
13
+ }
14
+
15
+ const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
16
+
17
+ const isPidAlive = (processLike, pid) => {
18
+ try {
19
+ processLike.kill(pid, 0);
20
+ return true;
21
+ } catch (error) {
22
+ return error?.code === 'EPERM';
23
+ }
24
+ };
25
+
26
+ const readClaim = async (lockFile) => {
27
+ try {
28
+ const claim = JSON.parse(await readFile(lockFile, 'utf8'));
29
+ if (Number.isInteger(claim?.pid) && claim.pid > 0 && typeof claim.nonce === 'string' && claim.nonce.length > 0) {
30
+ return { claim };
31
+ }
32
+ return { malformed: true };
33
+ } catch (error) {
34
+ if (error?.code === 'ENOENT') return { missing: true };
35
+ return { malformed: true };
36
+ }
37
+ };
38
+
39
+ const isFreshLock = async (lockFile) => {
40
+ try {
41
+ const info = await stat(lockFile);
42
+ return Date.now() - info.mtimeMs < FRESH_LOCK_MS;
43
+ } catch (error) {
44
+ return error?.code !== 'ENOENT';
45
+ }
46
+ };
47
+
48
+ /**
49
+ * Serialize one critical section across processes sharing a filesystem.
50
+ *
51
+ * The lock file holds an owner pid plus a random nonce. Only the owner nonce
52
+ * may release the lock. A dead owner pid may be stolen; a live owner never is.
53
+ */
54
+ export const withCrossProcessLock = async (
55
+ lockFile,
56
+ operation,
57
+ { timeoutMs = 5_000, retryDelayMs = 50, processLike = process, wait = delay } = {},
58
+ ) => {
59
+ if (typeof lockFile !== 'string' || lockFile.length === 0) {
60
+ throw new CrossProcessLockError('INVALID_LOCK_FILE');
61
+ }
62
+ if (typeof operation !== 'function') {
63
+ throw new CrossProcessLockError('INVALID_OPERATION');
64
+ }
65
+ const deadline = Date.now() + timeoutMs;
66
+ await mkdir(dirname(lockFile), { recursive: true, mode: 0o700 });
67
+ const nonce = randomUUID();
68
+
69
+ while (true) {
70
+ try {
71
+ await writeFile(
72
+ lockFile,
73
+ JSON.stringify({ pid: processLike.pid, nonce, claimedAt: new Date().toISOString() }),
74
+ { flag: 'wx', mode: 0o600 },
75
+ );
76
+ } catch (error) {
77
+ if (!RETRYABLE_CODES.has(error?.code)) throw new CrossProcessLockError('LOCK_UNAVAILABLE');
78
+ const observed = await readClaim(lockFile);
79
+ if (observed.claim) {
80
+ if (isPidAlive(processLike, observed.claim.pid)) {
81
+ if (Date.now() >= deadline) throw new CrossProcessLockError('LOCK_TIMEOUT');
82
+ await wait(retryDelayMs);
83
+ continue;
84
+ }
85
+ await rm(lockFile, { force: true });
86
+ } else if (observed.malformed) {
87
+ if (await isFreshLock(lockFile)) {
88
+ if (Date.now() >= deadline) throw new CrossProcessLockError('LOCK_TIMEOUT');
89
+ await wait(retryDelayMs);
90
+ continue;
91
+ }
92
+ await rm(lockFile, { force: true });
93
+ }
94
+ if (Date.now() >= deadline) throw new CrossProcessLockError('LOCK_TIMEOUT');
95
+ await wait(retryDelayMs);
96
+ continue;
97
+ }
98
+
99
+ try {
100
+ return await operation();
101
+ } finally {
102
+ try {
103
+ const current = JSON.parse(await readFile(lockFile, 'utf8'));
104
+ if (current?.pid === processLike.pid && current?.nonce === nonce) {
105
+ await rm(lockFile, { force: true });
106
+ }
107
+ } catch {
108
+ // A missing, replaced, or unreadable lock must never remove another owner.
109
+ }
110
+ }
111
+ }
112
+ };
@@ -0,0 +1,70 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ import { withCrossProcessLock } from './cross-process-lock.js';
7
+
8
+ describe('cross-process lock', () => {
9
+ it('serializes concurrent critical sections', async () => {
10
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-lock-'));
11
+ const lockFile = join(root, 'write.lock');
12
+ let releaseFirst;
13
+ const firstMayFinish = new Promise((resolve) => { releaseFirst = resolve; });
14
+ let firstEntered;
15
+ const firstDidEnter = new Promise((resolve) => { firstEntered = resolve; });
16
+ let active = 0;
17
+ let maximumActive = 0;
18
+ const enter = async (waitFor) => {
19
+ active += 1;
20
+ maximumActive = Math.max(maximumActive, active);
21
+ firstEntered?.();
22
+ await waitFor;
23
+ active -= 1;
24
+ };
25
+
26
+ const first = withCrossProcessLock(lockFile, () => enter(firstMayFinish));
27
+ await firstDidEnter;
28
+ const second = withCrossProcessLock(lockFile, () => enter(Promise.resolve()));
29
+ await new Promise((resolve) => setTimeout(resolve, 20));
30
+ expect(maximumActive).toBe(1);
31
+ releaseFirst();
32
+ await Promise.all([first, second]);
33
+ expect(maximumActive).toBe(1);
34
+ });
35
+
36
+ it('does not remove a replacement lock owned by another nonce', async () => {
37
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-lock-'));
38
+ const lockFile = join(root, 'owner.lock');
39
+ const replacement = { pid: process.pid, nonce: 'replacement-owner' };
40
+ await withCrossProcessLock(lockFile, async () => {
41
+ const claim = JSON.parse(await readFile(lockFile, 'utf8'));
42
+ expect(claim.pid).toBe(process.pid);
43
+ expect(typeof claim.nonce).toBe('string');
44
+ await writeFile(lockFile, JSON.stringify(replacement));
45
+ });
46
+ await expect(readFile(lockFile, 'utf8')).resolves.toBe(JSON.stringify(replacement));
47
+ await rm(lockFile, { force: true });
48
+ });
49
+
50
+ it('reclaims a lock whose owner pid is dead', async () => {
51
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-lock-'));
52
+ const lockFile = join(root, 'dead.lock');
53
+ const deadPid = 987_654_321;
54
+ await writeFile(lockFile, JSON.stringify({ pid: deadPid, nonce: 'dead-owner' }));
55
+ const processLike = {
56
+ pid: process.pid,
57
+ kill(pid, signal) {
58
+ if (pid === deadPid && signal === 0) {
59
+ const error = new Error('ESRCH');
60
+ error.code = 'ESRCH';
61
+ throw error;
62
+ }
63
+ return process.kill(pid, signal);
64
+ },
65
+ };
66
+
67
+ await expect(withCrossProcessLock(lockFile, async () => 'acquired', { processLike })).resolves.toBe('acquired');
68
+ await expect(readFile(lockFile, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });
69
+ });
70
+ });
@@ -0,0 +1,110 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+
3
+ const PROFILE_KEY_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
4
+ const MAX_EXPLICIT_LENGTH = 128;
5
+
6
+ export const isValidProfileKey = (value) => typeof value === 'string' && PROFILE_KEY_PATTERN.test(value);
7
+
8
+ const hashSeed = (seed) => createHash('sha256').update(seed).digest('hex').slice(0, 16);
9
+
10
+ const sanitizePortSegment = (port) => {
11
+ if (port === 0) return 'pauto';
12
+ if (Number.isInteger(port) && port > 0 && port <= 65535) return `p${port}`;
13
+ return '';
14
+ };
15
+
16
+ const resolveRuntime = ({ env = {}, runtime } = {}) => {
17
+ const fromEnv = typeof env.PICHAMBER_RUNTIME === 'string' ? env.PICHAMBER_RUNTIME.trim() : '';
18
+ if (fromEnv === 'desktop' || fromEnv === 'web') return fromEnv;
19
+ if (runtime === 'desktop' || runtime === 'web') return runtime;
20
+ return 'web';
21
+ };
22
+
23
+ const isDesktopDev = ({ env = {} } = {}) => {
24
+ const flag = typeof env.PICHAMBER_ELECTRON_DEV === 'string' ? env.PICHAMBER_ELECTRON_DEV.trim().toLowerCase() : '';
25
+ return flag === '1' || flag === 'true';
26
+ };
27
+
28
+ const isWebDev = ({ env = {} } = {}) => {
29
+ const kind = typeof env.PICHAMBER_SERVER_PROFILE_KIND === 'string' ? env.PICHAMBER_SERVER_PROFILE_KIND.trim().toLowerCase() : '';
30
+ if (kind === 'dev') return true;
31
+ const legacy = typeof env.PICHAMBER_DEV_SERVER === 'string' ? env.PICHAMBER_DEV_SERVER.trim().toLowerCase() : '';
32
+ return legacy === '1' || legacy === 'true';
33
+ };
34
+
35
+ /**
36
+ * Resolve the stable daemon profile for one PiChamber server.
37
+ *
38
+ * The profile key is stable across restarts of the same logical server and
39
+ * distinct across development, installed, desktop, and port-separated web
40
+ * servers. The server instance id is unique per launch and is used to prove
41
+ * which server currently owns a profile daemon.
42
+ */
43
+ export const resolveServerProfile = ({
44
+ env = process.env,
45
+ port,
46
+ runtime,
47
+ version,
48
+ serverInstanceId,
49
+ } = {}) => {
50
+ const safeEnv = env && typeof env === 'object' ? env : {};
51
+ const explicit = typeof safeEnv.PICHAMBER_SERVER_PROFILE === 'string'
52
+ ? safeEnv.PICHAMBER_SERVER_PROFILE.trim()
53
+ : '';
54
+ const effectiveRuntime = resolveRuntime({ env: safeEnv, runtime });
55
+ const development = effectiveRuntime === 'desktop'
56
+ ? isDesktopDev({ env: safeEnv })
57
+ : isWebDev({ env: safeEnv });
58
+ const instanceId = typeof serverInstanceId === 'string' && serverInstanceId.length > 0
59
+ ? serverInstanceId
60
+ : randomUUID();
61
+ const buildId = typeof version === 'string' && version.trim().length > 0 ? version.trim() : 'unknown';
62
+
63
+ if (explicit.length > 0) {
64
+ if (explicit.length > MAX_EXPLICIT_LENGTH) {
65
+ throw new Error('PICHAMBER_SERVER_PROFILE is too long.');
66
+ }
67
+ return {
68
+ profileKey: `custom-${hashSeed(`explicit:${explicit}`)}`,
69
+ profileLabel: explicit.slice(0, MAX_EXPLICIT_LENGTH),
70
+ serverInstanceId: instanceId,
71
+ runtime: effectiveRuntime,
72
+ source: 'custom',
73
+ development,
74
+ port: Number.isInteger(port) ? port : null,
75
+ buildId,
76
+ };
77
+ }
78
+
79
+ if (effectiveRuntime === 'desktop') {
80
+ const dev = development;
81
+ return {
82
+ profileKey: dev ? 'desktop-dev' : 'desktop',
83
+ profileLabel: dev ? 'desktop development' : 'desktop',
84
+ serverInstanceId: instanceId,
85
+ runtime: 'desktop',
86
+ source: dev ? 'desktop-dev' : 'desktop-installed',
87
+ development: dev,
88
+ port: Number.isInteger(port) ? port : null,
89
+ buildId,
90
+ };
91
+ }
92
+
93
+ const dev = development;
94
+ const portSegment = sanitizePortSegment(port);
95
+ const base = dev ? 'web-dev' : 'web';
96
+ const profileKey = portSegment ? `${base}-${portSegment}` : base;
97
+ const numericPort = Number.isInteger(port) ? port : null;
98
+ return {
99
+ profileKey,
100
+ profileLabel: numericPort === null
101
+ ? `${dev ? 'web development' : 'web'} server`
102
+ : `${dev ? 'web development' : 'web'} server on port ${numericPort}`,
103
+ serverInstanceId: instanceId,
104
+ runtime: 'web',
105
+ source: dev ? 'web-dev' : 'web-installed',
106
+ development: dev,
107
+ port: numericPort,
108
+ buildId,
109
+ };
110
+ };
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { isValidProfileKey, resolveServerProfile } from './server-profile.js';
4
+
5
+ describe('server profile', () => {
6
+ it('separates installed and development web servers on the same port', () => {
7
+ const installed = resolveServerProfile({ env: {}, port: 3000, runtime: 'web', version: '0.9.0' });
8
+ const dev = resolveServerProfile({
9
+ env: { PICHAMBER_SERVER_PROFILE_KIND: 'dev' },
10
+ port: 3000,
11
+ runtime: 'web',
12
+ version: '0.9.0',
13
+ });
14
+ expect(installed.profileKey).toBe('web-p3000');
15
+ expect(dev.profileKey).toBe('web-dev-p3000');
16
+ expect(installed.profileKey).not.toBe(dev.profileKey);
17
+ expect(installed.serverInstanceId).not.toBe(dev.serverInstanceId);
18
+ });
19
+
20
+ it('separates web servers on different ports', () => {
21
+ const a = resolveServerProfile({ env: {}, port: 3000 });
22
+ const b = resolveServerProfile({ env: {}, port: 3902 });
23
+ expect(a.profileKey).not.toBe(b.profileKey);
24
+ });
25
+
26
+ it('uses stable desktop profiles without ports', () => {
27
+ const installed = resolveServerProfile({ env: { PICHAMBER_RUNTIME: 'desktop' } });
28
+ const dev = resolveServerProfile({ env: { PICHAMBER_RUNTIME: 'desktop', PICHAMBER_ELECTRON_DEV: '1' } });
29
+ expect(installed.profileKey).toBe('desktop');
30
+ expect(dev.profileKey).toBe('desktop-dev');
31
+ });
32
+
33
+ it('hashes explicit profile overrides instead of using them as paths', () => {
34
+ const profile = resolveServerProfile({ env: { PICHAMBER_SERVER_PROFILE: '../../evil' }, port: 3000 });
35
+ expect(isValidProfileKey(profile.profileKey)).toBe(true);
36
+ expect(profile.profileKey).toMatch(/^custom-[0-9a-f]{16}$/);
37
+ expect(profile.profileKey).not.toContain('.');
38
+ });
39
+
40
+ it('preserves development replacement behavior for explicit profiles', () => {
41
+ const profile = resolveServerProfile({
42
+ env: {
43
+ PICHAMBER_SERVER_PROFILE: 'isolated-dev',
44
+ PICHAMBER_SERVER_PROFILE_KIND: 'dev',
45
+ },
46
+ port: 3000,
47
+ });
48
+ expect(profile.source).toBe('custom');
49
+ expect(profile.development).toBe(true);
50
+ });
51
+
52
+ it('keeps the profile key stable for one logical server across launches', () => {
53
+ const first = resolveServerProfile({ env: {}, port: 3000 });
54
+ const second = resolveServerProfile({ env: {}, port: 3000 });
55
+ expect(first.profileKey).toBe(second.profileKey);
56
+ expect(first.serverInstanceId).not.toBe(second.serverInstanceId);
57
+ });
58
+ });
@@ -1,6 +1,6 @@
1
1
  # Cloudflare Tunnel Service
2
2
 
3
- PiChamber exposes a PiChamber-hosted Cloudflare Tunnel that lets a browser or mobile client reach a private PiChamber server without opening inbound ports. The server dials outbound to Cloudflare with `cloudflared`; the public hostname then proxies to the local PiChamber HTTP endpoint.
3
+ PiChamber can manage a Cloudflare Tunnel that lets a browser or mobile client reach a private PiChamber server without opening inbound ports. The server dials outbound to Cloudflare with `cloudflared`; the public hostname then proxies to the local PiChamber HTTP endpoint.
4
4
 
5
5
  ## Modes
6
6
 
@@ -64,11 +64,10 @@ The PiChamber `pichamber.service` itself already supports both user (`~/.config/
64
64
  - `tunnel-service.test.js` covers validation (missing token/hostname, unsupported mode), status shape, secret redaction, and that `missing_dependency` is reported when `cloudflared` is absent.
65
65
  - Integration smoke against a real `cloudflared` binary is manual: install `cloudflared`, run `pichamber serve`, `curl /api/pichamber/tunnel/check`, start a quick tunnel, verify `status.url` appears and `curl -H "Host: $url-host"` reaches the server through the tunnel with `Authorization` still required.
66
66
 
67
- ## Cloudflare permissions for API-token flow
67
+ ## Cloudflare credentials
68
68
 
69
- If the operator wants PiChamber to create a tunnel automatically (rather than pasting a token), the Cloudflare API token needs:
70
-
71
- - `Zone:Read`, `DNS:Edit` on the zone that will host the hostname
72
- - `Account:Cloudflare Tunnel:Edit` (to create/list tunnels)
73
-
74
- PiChamber never asks for the Cloudflare account password. The manual token flow is the default; the API-token flow is an optional convenience that calls `https://api.cloudflare.com/client/v4/accounts/{accountId}/cfd_tunnel` with the scoped token. Secrets are still stored with `0600` and never returned in API responses.
69
+ PiChamber uses a manual Cloudflare tunnel token for `managed-remote` mode and
70
+ an existing `cloudflared` config for `managed-local` mode. It does not ask for a
71
+ Cloudflare account password and does not create tunnels through a Cloudflare
72
+ API-token wizard. Secrets are stored with `0600` and never returned in API
73
+ responses.
@@ -52,7 +52,14 @@ export const createTunnelService = ({
52
52
  const writeTokenStore = (token, hostname) => {
53
53
  try {
54
54
  fs.mkdirSync(path.dirname(tokenPath), { recursive: true, mode: 0o700 });
55
- fs.writeFileSync(tokenPath, JSON.stringify({ token, hostname }), { mode: 0o600 });
55
+ // Atomic replace so a concurrent server never reads a torn token.
56
+ const temporary = `${tokenPath}.tmp-${process.pid}-${Date.now()}`;
57
+ try {
58
+ fs.writeFileSync(temporary, JSON.stringify({ token, hostname }), { mode: 0o600 });
59
+ fs.renameSync(temporary, tokenPath);
60
+ } catch {
61
+ try { fs.rmSync(temporary, { force: true }); } catch {}
62
+ }
56
63
  } catch {}
57
64
  };
58
65
 
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
 
5
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
5
6
  import { DEFAULT_LOCAL_STT_MODEL, isLocalSttModelId } from './local/model-catalog.js';
6
7
 
7
8
  const DEFAULT_CONFIG = Object.freeze({ enabled: false, providerConfigId: 'local', language: '', localModelId: DEFAULT_LOCAL_STT_MODEL, providers: [] });
@@ -51,7 +52,7 @@ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rena
51
52
  catch (error) { if (error?.code === 'ENOENT') return { ...DEFAULT_CONFIG, providers: [] }; throw new Error('STT configuration is invalid'); }
52
53
  };
53
54
  const write = async (changes) => {
54
- const operation = mutation.then(async () => {
55
+ const operation = mutation.then(() => withCrossProcessLock(`${file}.lock`, async () => {
55
56
  const current = await read();
56
57
  let providers = current.providers;
57
58
  if (changes?.remoteProvider) {
@@ -73,7 +74,7 @@ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rena
73
74
  await fs.rm(temporary, { force: true }).catch(() => {});
74
75
  throw error;
75
76
  }
76
- });
77
+ }));
77
78
  mutation = operation.catch(() => {});
78
79
  return operation;
79
80
  };
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Ownership
4
4
 
5
- `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
5
+ `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron, hosted mobile, and Capacitor clients use this same server runtime through the shared authenticated transport.
6
6
 
7
7
  ## Protocol
8
8
 
@@ -1,32 +1,52 @@
1
- # Tunnels Module Documentation
1
+ # Tunnels module documentation
2
2
 
3
3
  ## Purpose
4
+
4
5
  This module contains the shared tunnel support surface for PiChamber: provider
5
- capability metadata, tunnel types/normalization helpers, cross-platform
6
+ capability metadata, tunnel types and normalization helpers, cross-platform
6
7
  executable discovery, and dependency install-help metadata.
7
8
 
8
- The tunnel start implementation lives in
9
- `packages/web/server/lib/cloudflare-tunnel.js`; CLI orchestration lives in
10
- `packages/web/bin/lib/commands-tunnel.js`.
9
+ The Cloudflare provider implementation lives in
10
+ `packages/web/server/lib/cloudflare-tunnel.js`. The server-owned lifecycle is
11
+ `packages/web/server/lib/server/tunnel-service.js`, and CLI orchestration lives
12
+ in `packages/web/bin/lib/commands-tunnel.js`.
11
13
 
12
- > Wiring note: the previous service orchestration entrypoint
13
- > (`tunnels/index.js`, `createTunnelService`) was removed as dead code — no
14
- > runtime entrypoint registered tunnel routes or started a tunnel service.
15
- > The remaining files are consumed by the CLI capability surface and by the
16
- > Cloudflare tunnel provider implementation, not by a tunnel orchestration runtime.
14
+ `startWebUiServer` creates the tunnel service and registers its authenticated
15
+ routes. Tunnel startup is intentionally separate from `pichamber serve` startup:
16
+ use `pichamber tunnel start` after the server is running.
17
17
 
18
18
  ## Entrypoints and structure
19
- - `packages/web/server/lib/tunnels/executable-search.js`: cross-platform executable discovery, including Windows Store app aliases. Consumed by the tunnel providers and `packages/web/server/lib/workspace/host.js`.
20
- - `packages/web/server/lib/tunnels/install-help.js`: provider/platform install command metadata (`getTunnelDependencyInstallInfo`) for missing tunnel dependencies.
21
- - `packages/web/server/lib/tunnels/types.js`: shared tunnel provider, mode, and intent constants plus the shared `TunnelServiceError` class.
19
+
20
+ - `executable-search.js` discovers provider executables across platforms,
21
+ including Windows Store app aliases. The workspace host and tunnel providers
22
+ use it.
23
+ - `install-help.js` provides provider and platform install guidance for missing
24
+ dependencies.
25
+ - `types.js` defines provider, mode, intent, and `TunnelServiceError` values.
26
+ - `../cloudflare-tunnel.js` starts Cloudflare Quick, Managed Remote, and Managed
27
+ Local children and reports their public hostname.
28
+ - `../server/tunnel-service.js` owns one active child, token storage, public URL
29
+ state, and tunnel-auth registration.
22
30
 
23
31
  ## Public exports
32
+
24
33
  - `install-help.js` → `getTunnelDependencyInstallInfo(provider, platform)`
25
- - `executable-search.js` → `getExecutableSearchDirectories`, `createExecutableSearchEnv`, `findExecutableOnPath`, `resolveExecutableLaunchTarget`
26
- - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`, `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`, `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`, `TunnelServiceError`
34
+ - `executable-search.js` → `getExecutableSearchDirectories`,
35
+ `createExecutableSearchEnv`, `findExecutableOnPath`,
36
+ `resolveExecutableLaunchTarget`
37
+ - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`,
38
+ `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`,
39
+ `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`,
40
+ `TunnelServiceError`
27
41
 
28
42
  ## Consumers
29
- - `packages/web/bin/lib/cli-tunnel-capabilities.js`: provider capability metadata for CLI tunnel commands (Cloudflare only).
30
- - `packages/web/server/lib/cloudflare-tunnel.js`: executable discovery, install-help metadata, and provider constants.
31
- - `packages/web/server/lib/workspace/host.js`: executable discovery.
32
43
 
44
+ - `packages/web/bin/lib/cli-tunnel-capabilities.js` provides Cloudflare
45
+ capability metadata to the CLI.
46
+ - `packages/web/bin/lib/commands-tunnel.js` validates flags, presents prompts,
47
+ and calls the server lifecycle routes.
48
+ - `packages/web/server/index.js` creates the tunnel service and registers the
49
+ authenticated routes.
50
+ - `packages/ui/src/components/sections/pichamber/tunnel/` renders status,
51
+ setup, profiles, and one-time connect links.
52
+ - `packages/electron/main.mjs` reads tunnel status for native quit-risk UI.
@@ -369,8 +369,15 @@ function getOrCreateJwtSecret() {
369
369
  const secret = crypto.randomBytes(32).toString('hex');
370
370
  try {
371
371
  fs.mkdirSync(PICHAMBER_DATA_DIR, { recursive: true });
372
- fs.writeFileSync(JWT_SECRET_FILE, secret, { mode: 0o600 });
373
- console.log('[JWT] Generated and persisted new secret to', JWT_SECRET_FILE);
372
+ // Exclusive create: a concurrent server creating its first secret at the
373
+ // same instant re-reads the winner instead of overwriting it.
374
+ try {
375
+ fs.writeFileSync(JWT_SECRET_FILE, secret, { mode: 0o600, flag: 'wx' });
376
+ console.log('[JWT] Generated and persisted new secret to', JWT_SECRET_FILE);
377
+ } catch (error) {
378
+ if (error?.code !== 'EEXIST') throw error;
379
+ return new TextEncoder().encode(fs.readFileSync(JWT_SECRET_FILE, 'utf8').trim());
380
+ }
374
381
  } catch (e) {
375
382
  console.warn('[JWT] Failed to persist secret:', e.message);
376
383
  }
@@ -126,7 +126,15 @@ export const createUiPasskeys = ({
126
126
 
127
127
  const persistStore = (store) => {
128
128
  ensureStoreDirectory();
129
- fs.writeFileSync(storeFile, JSON.stringify(store, null, 2));
129
+ // Atomic replace so a concurrent server never reads a torn store.
130
+ const temporary = `${storeFile}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
131
+ try {
132
+ fs.writeFileSync(temporary, JSON.stringify(store, null, 2), { mode: 0o600 });
133
+ fs.renameSync(temporary, storeFile);
134
+ } catch (error) {
135
+ try { fs.rmSync(temporary, { force: true }); } catch {}
136
+ throw error;
137
+ }
130
138
  };
131
139
 
132
140
  const createEmptyStore = () => ({