@openchamber/web 1.13.3 → 1.13.5

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 (129) hide show
  1. package/bin/cli-output.js +2 -7
  2. package/bin/cli-output.test.js +36 -0
  3. package/bin/cli.js +132 -5548
  4. package/bin/cli.test.js +686 -0
  5. package/bin/lib/DOCUMENTATION.md +121 -0
  6. package/bin/lib/cli-args.js +726 -0
  7. package/bin/lib/cli-errors.js +18 -0
  8. package/bin/lib/cli-executables.js +54 -0
  9. package/bin/lib/cli-http.js +216 -0
  10. package/bin/lib/cli-lifecycle.js +421 -0
  11. package/bin/lib/cli-log-files.js +93 -0
  12. package/bin/lib/cli-network.js +154 -0
  13. package/bin/lib/cli-paths.js +113 -0
  14. package/bin/lib/cli-ports.js +51 -0
  15. package/bin/lib/cli-process.js +292 -0
  16. package/bin/lib/cli-startup.js +370 -0
  17. package/bin/lib/cli-tunnel-capabilities.js +9 -0
  18. package/bin/lib/cli-tunnel-profiles.js +366 -0
  19. package/bin/lib/cli-tunnel-utils.js +300 -0
  20. package/bin/lib/commands-connect-url.js +173 -0
  21. package/bin/lib/commands-lifecycle.js +396 -0
  22. package/bin/lib/commands-logs.js +110 -0
  23. package/bin/lib/commands-serve.js +396 -0
  24. package/bin/lib/commands-startup.js +64 -0
  25. package/bin/lib/commands-status.js +114 -0
  26. package/bin/lib/commands-tunnel.js +1761 -0
  27. package/bin/lib/commands-update.js +141 -0
  28. package/dist/assets/{DiagramView-BmHROYsX.js → DiagramView-Bbj-QI7h.js} +1 -1
  29. package/dist/assets/{MarkdownRendererImpl-DiJE-v5Q.js → MarkdownRendererImpl-BNr_9Jsb.js} +3 -3
  30. package/dist/assets/MultiRunWindow-DMMu53kw.js +1 -0
  31. package/dist/assets/NewWorktreeDialog-5TYBoMMA.js +167 -0
  32. package/dist/assets/{OnboardingScreen-DpBF8dKJ.js → OnboardingScreen-BucKVBD7.js} +1 -1
  33. package/dist/assets/{SessionSwitcherDropdown-1xaHUxPK.js → SessionSwitcherDropdown-B6kvduse.js} +1 -1
  34. package/dist/assets/{SettingsWindow-ChwLyQAe.js → SettingsWindow-BEfDro9b.js} +1 -1
  35. package/dist/assets/{TerminalView-DGEBNuAp.js → TerminalView-CMdqMpTy.js} +1 -1
  36. package/dist/assets/es-Bk-yR0w-.js +15 -0
  37. package/dist/assets/fr-f1ibV7QU.js +13 -0
  38. package/dist/assets/index-B82A6jBD.css +1 -0
  39. package/dist/assets/index-BsXkdBYx.js +3 -0
  40. package/dist/assets/ja-D9mS3zWP.js +15 -0
  41. package/dist/assets/ko-Cpl1IA3D.js +15 -0
  42. package/dist/assets/main-DOdUrt3s.js +214 -0
  43. package/dist/assets/{main-fm_8J7Lk.js → main-KEVf2Yak.js} +2 -2
  44. package/dist/assets/miniChat-Nlzqr3Df.js +2 -0
  45. package/dist/assets/mobile-BIhOFhia.js +2 -0
  46. package/dist/assets/pl-CYke_fxL.js +15 -0
  47. package/dist/assets/pt-BR-Clb6Z8up.js +15 -0
  48. package/dist/assets/renderElectronMiniChatApp-Cb1iUq8M.js +2 -0
  49. package/dist/assets/{renderMobileApp-6s0G1iIJ.js → renderMobileApp-7chEBHPK.js} +5 -5
  50. package/dist/assets/uk-CXn8cxXa.js +15 -0
  51. package/dist/assets/{useAppFontEffects-CV5C5O0r.js → useAppFontEffects-Bd0ks39c.js} +124 -119
  52. package/dist/assets/{vendor-.bun-CC_Xso_s.js → vendor-.bun-By2L9XvG.js} +1 -1
  53. package/dist/assets/zh-CN-BRwwlEdG.js +15 -0
  54. package/dist/assets/zh-TW-D5pg5Z8l.js +15 -0
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +4 -4
  57. package/dist/mobile.html +4 -4
  58. package/package.json +1 -1
  59. package/server/lib/cloudflare-tunnel.js +2 -2
  60. package/server/lib/event-stream/global-hub.js +1 -1
  61. package/server/lib/event-stream/index.js +0 -12
  62. package/server/lib/event-stream/runtime.js +1 -1
  63. package/server/lib/git/routes.test.js +4 -4
  64. package/server/lib/git/service.js +18 -0
  65. package/server/lib/git/service.test.js +48 -0
  66. package/server/lib/github/routes.js +1 -0
  67. package/server/lib/notifications/index.js +1 -4
  68. package/server/lib/opencode/agents.js +0 -6
  69. package/server/lib/opencode/commands.js +0 -5
  70. package/server/lib/opencode/config-entity-routes.js +39 -21
  71. package/server/lib/opencode/feature-routes-runtime.js +27 -62
  72. package/server/lib/opencode/lifecycle.js +13 -1
  73. package/server/lib/opencode/npm-registry.js +3 -3
  74. package/server/lib/opencode/proxy.js +3 -3
  75. package/server/lib/opencode/shared.js +0 -6
  76. package/server/lib/opencode/skills.js +0 -2
  77. package/server/lib/opencode/snippets.js +0 -2
  78. package/server/lib/package-manager.js +4 -4
  79. package/server/lib/package-manager.test.js +8 -1
  80. package/server/lib/projects/project-config.js +0 -8
  81. package/server/lib/quota/DOCUMENTATION.md +3 -1
  82. package/server/lib/quota/providers/claude.js +1 -1
  83. package/server/lib/quota/providers/codex.js +1 -1
  84. package/server/lib/quota/providers/copilot.js +1 -1
  85. package/server/lib/quota/providers/cursor.js +1 -1
  86. package/server/lib/quota/providers/google/auth.js +2 -2
  87. package/server/lib/quota/providers/google/index.js +14 -33
  88. package/server/lib/quota/providers/google/transforms.js +1 -1
  89. package/server/lib/quota/providers/index.js +4 -4
  90. package/server/lib/quota/providers/index.test.js +17 -0
  91. package/server/lib/quota/providers/kimi.js +1 -1
  92. package/server/lib/quota/providers/minimax-cn-coding-plan.js +1 -1
  93. package/server/lib/quota/providers/minimax-coding-plan.js +1 -1
  94. package/server/lib/quota/providers/nanogpt.js +1 -1
  95. package/server/lib/quota/providers/ollama-cloud.js +1 -1
  96. package/server/lib/quota/providers/openai.js +4 -4
  97. package/server/lib/quota/providers/openrouter.js +1 -1
  98. package/server/lib/quota/providers/wafer.js +1 -1
  99. package/server/lib/quota/providers/zai.js +1 -1
  100. package/server/lib/quota/providers/zhipuai-coding-plan.js +1 -1
  101. package/server/lib/skills-catalog/cache.js +0 -4
  102. package/server/lib/skills-catalog/clawdhub/api.js +0 -32
  103. package/server/lib/skills-catalog/clawdhub/scan.js +0 -52
  104. package/server/lib/skills-catalog/curated-sources.js +1 -1
  105. package/server/lib/skills-catalog/source.js +5 -0
  106. package/server/lib/terminal/runtime.js +11 -9
  107. package/server/lib/text/summarization.js +1 -1
  108. package/server/lib/tunnels/types.js +2 -2
  109. package/dist/assets/MultiRunWindow-yZoCT7F7.js +0 -1
  110. package/dist/assets/NewWorktreeDialog-CTMiE7Xd.js +0 -167
  111. package/dist/assets/es-CTE-E8we.js +0 -15
  112. package/dist/assets/fr-TVkZpyEo.js +0 -13
  113. package/dist/assets/index-B4pCDMbq.css +0 -1
  114. package/dist/assets/index-D9uMvTQF.js +0 -3
  115. package/dist/assets/ko-D_UCJIIL.js +0 -15
  116. package/dist/assets/main-eAd3a6tx.js +0 -214
  117. package/dist/assets/miniChat-Bbjg31IC.js +0 -2
  118. package/dist/assets/mobile-B3_j_DsB.js +0 -2
  119. package/dist/assets/pl-nDEkk-GZ.js +0 -15
  120. package/dist/assets/pt-BR-B_g2RcgU.js +0 -15
  121. package/dist/assets/renderElectronMiniChatApp-CB13zs6N.js +0 -2
  122. package/dist/assets/uk-CWLhnPGW.js +0 -15
  123. package/dist/assets/zh-CN-BFxe1b5m.js +0 -15
  124. package/dist/assets/zh-TW-n-d-xbGV.js +0 -15
  125. package/server/lib/opencode/index.js +0 -95
  126. package/server/lib/quota/providers/interface.js +0 -55
  127. package/server/lib/skills-catalog/clawdhub/index.js +0 -30
  128. package/server/lib/skills-catalog/index.js +0 -42
  129. package/server/lib/terminal/index.js +0 -31
@@ -0,0 +1,366 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import crypto from 'crypto';
4
+ import {
5
+ getTunnelProfilesFilePath,
6
+ getLegacyCloudflareManagedRemoteFilePath,
7
+ } from './cli-paths.js';
8
+
9
+ const TUNNEL_PROFILES_VERSION = 1;
10
+ const MAX_TOKEN_FILE_BYTES = 8 * 1024;
11
+
12
+ function normalizeProfileProvider(value) {
13
+ if (typeof value !== 'string') return '';
14
+ return value.trim().toLowerCase();
15
+ }
16
+
17
+ function normalizeProfileMode(value) {
18
+ if (typeof value !== 'string') return '';
19
+ return value.trim().toLowerCase();
20
+ }
21
+
22
+ function normalizeProfileName(value) {
23
+ if (typeof value !== 'string') return '';
24
+ return value.trim();
25
+ }
26
+
27
+ function normalizeProfileHostname(value) {
28
+ if (typeof value !== 'string') return '';
29
+ return value.trim();
30
+ }
31
+
32
+ function normalizeProfileToken(value) {
33
+ if (typeof value !== 'string') return '';
34
+ return value.trim();
35
+ }
36
+
37
+ function suggestProfileNameFromHostname(hostname) {
38
+ const normalizedHost = normalizeProfileHostname(hostname);
39
+ if (!normalizedHost) return 'prod-main';
40
+ const firstLabel = normalizedHost.split('.')[0] || normalizedHost;
41
+ const sanitized = firstLabel.replace(/[^a-zA-Z0-9-_]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
42
+ return sanitized || 'prod-main';
43
+ }
44
+
45
+ function maskToken(token) {
46
+ if (typeof token !== 'string' || token.length === 0) {
47
+ return '***';
48
+ }
49
+ if (token.length <= 4) {
50
+ return '*'.repeat(token.length);
51
+ }
52
+ return `${'*'.repeat(Math.max(4, token.length - 4))}${token.slice(-4)}`;
53
+ }
54
+
55
+ function readTokenFromFileSafely(tokenFilePath) {
56
+ const absolutePath = path.resolve(tokenFilePath);
57
+ let realPath;
58
+ try {
59
+ realPath = fs.realpathSync(absolutePath);
60
+ } catch (error) {
61
+ if (error?.code === 'ENOENT') {
62
+ throw new Error(`Token file '${absolutePath}' not found.`);
63
+ }
64
+ if (error?.code === 'EACCES') {
65
+ throw new Error(`Token file '${absolutePath}' is not readable. Check file permissions.`);
66
+ }
67
+ throw error;
68
+ }
69
+
70
+ let stats;
71
+ try {
72
+ stats = fs.statSync(realPath);
73
+ } catch (error) {
74
+ if (error?.code === 'EACCES') {
75
+ throw new Error(`Token file '${absolutePath}' is not readable. Check file permissions.`);
76
+ }
77
+ throw error;
78
+ }
79
+
80
+ if (!stats.isFile()) {
81
+ throw new Error(`Token file '${absolutePath}' must be a regular file.`);
82
+ }
83
+ if (stats.size <= 0) {
84
+ throw new Error(`Token file '${absolutePath}' is empty.`);
85
+ }
86
+ if (stats.size > MAX_TOKEN_FILE_BYTES) {
87
+ throw new Error(`Token file '${absolutePath}' is too large (max ${MAX_TOKEN_FILE_BYTES} bytes).`);
88
+ }
89
+
90
+ const raw = fs.readFileSync(realPath, 'utf8');
91
+ if (raw.includes('\u0000')) {
92
+ throw new Error(`Token file '${absolutePath}' appears to be binary. Use a plain text token file.`);
93
+ }
94
+
95
+ const value = raw.trim();
96
+ if (!value) {
97
+ throw new Error(`Token file '${absolutePath}' is empty.`);
98
+ }
99
+ return value;
100
+ }
101
+
102
+ function resolveToken(options) {
103
+ const sources = [
104
+ options.tokenStdin ? 'stdin' : null,
105
+ options.tokenFile ? 'file' : null,
106
+ options.token ? 'flag' : null,
107
+ ].filter(Boolean);
108
+
109
+ if (sources.length > 1) {
110
+ throw new Error(`Multiple token sources specified (${sources.join(', ')}). Use only one of --token, --token-file, or --token-stdin.`);
111
+ }
112
+
113
+ if (options.tokenStdin) {
114
+ const fd = fs.openSync('/dev/stdin', 'r');
115
+ try {
116
+ const buf = Buffer.alloc(65536);
117
+ const bytesRead = fs.readSync(fd, buf, 0, buf.length, null);
118
+ const value = buf.slice(0, bytesRead).toString('utf8').trim();
119
+ if (!value) {
120
+ throw new Error('No token received from stdin.');
121
+ }
122
+ return value;
123
+ } finally {
124
+ fs.closeSync(fd);
125
+ }
126
+ }
127
+
128
+ if (options.tokenFile) {
129
+ return readTokenFromFileSafely(options.tokenFile);
130
+ }
131
+
132
+ return typeof options.token === 'string' ? options.token.trim() : undefined;
133
+ }
134
+
135
+ function redactProfileForOutput(profile, showSecrets = false) {
136
+ if (!profile || typeof profile !== 'object') {
137
+ return profile;
138
+ }
139
+ return {
140
+ ...profile,
141
+ token: showSecrets ? profile.token : maskToken(profile.token),
142
+ };
143
+ }
144
+
145
+ function redactProfilesForOutput(profiles, showSecrets = false) {
146
+ if (!Array.isArray(profiles)) {
147
+ return profiles;
148
+ }
149
+ return profiles.map((entry) => redactProfileForOutput(entry, showSecrets));
150
+ }
151
+
152
+ function formatProfileTokenStatus(profile, showSecrets = false) {
153
+ const token = typeof profile?.token === 'string' ? profile.token.trim() : '';
154
+ if (!token) {
155
+ return 'token:missing';
156
+ }
157
+ if (showSecrets) {
158
+ return `token:${token}`;
159
+ }
160
+ return 'token:present';
161
+ }
162
+
163
+ function sanitizeTunnelProfilesData(data) {
164
+ const parsed = data && typeof data === 'object' ? data : {};
165
+ const list = Array.isArray(parsed.profiles) ? parsed.profiles : [];
166
+ const seen = new Set();
167
+ const profiles = [];
168
+ for (const entry of list) {
169
+ if (!entry || typeof entry !== 'object') continue;
170
+ const id = typeof entry.id === 'string' && entry.id.trim().length > 0 ? entry.id.trim() : crypto.randomUUID();
171
+ const provider = normalizeProfileProvider(entry.provider);
172
+ const mode = normalizeProfileMode(entry.mode);
173
+ const name = normalizeProfileName(entry.name);
174
+ const hostname = normalizeProfileHostname(entry.hostname);
175
+ const token = normalizeProfileToken(entry.token);
176
+ if (!provider || !mode || !name || !hostname || !token) continue;
177
+ const key = `${provider}::${name.toLowerCase()}`;
178
+ if (seen.has(key)) continue;
179
+ seen.add(key);
180
+ profiles.push({
181
+ id,
182
+ name,
183
+ provider,
184
+ mode,
185
+ hostname,
186
+ token,
187
+ createdAt: Number.isFinite(entry.createdAt) ? entry.createdAt : Date.now(),
188
+ updatedAt: Number.isFinite(entry.updatedAt) ? entry.updatedAt : Date.now(),
189
+ });
190
+ }
191
+ return { version: TUNNEL_PROFILES_VERSION, profiles };
192
+ }
193
+
194
+ function warnIfUnsafeFilePermissions(filePath, { shouldWarn = true } = {}) {
195
+ if (process.platform === 'win32') {
196
+ return;
197
+ }
198
+ if (!shouldWarn) {
199
+ return;
200
+ }
201
+ try {
202
+ const stats = fs.statSync(filePath);
203
+ const perms = stats.mode & 0o777;
204
+ if (perms & 0o077) {
205
+ const octal = perms.toString(8).padStart(3, '0');
206
+ console.warn(
207
+ `Warning: Profile file '${filePath}' has permissions ${octal} (should be 600). ` +
208
+ `Other users may be able to read tunnel tokens. Fix with: chmod 600 '${filePath}'`
209
+ );
210
+ }
211
+ } catch {
212
+ // File may not exist yet — not an error
213
+ }
214
+ }
215
+
216
+ function readTunnelProfilesFromDisk(options = {}) {
217
+ const filePath = getTunnelProfilesFilePath();
218
+ try {
219
+ warnIfUnsafeFilePermissions(filePath, options);
220
+ const raw = fs.readFileSync(filePath, 'utf8');
221
+ return sanitizeTunnelProfilesData(JSON.parse(raw));
222
+ } catch {
223
+ return { version: TUNNEL_PROFILES_VERSION, profiles: [] };
224
+ }
225
+ }
226
+
227
+ function writeTunnelProfilesToDisk(data) {
228
+ const filePath = getTunnelProfilesFilePath();
229
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
230
+ fs.writeFileSync(filePath, JSON.stringify(sanitizeTunnelProfilesData(data), null, 2), { encoding: 'utf8', mode: 0o600 });
231
+ }
232
+
233
+ function writeManagedRemotePairsToDiskFromProfiles(profilesData) {
234
+ const profiles = sanitizeTunnelProfilesData(profilesData).profiles;
235
+ const cloudflareManagedRemote = profiles.filter(
236
+ (entry) => entry.provider === 'cloudflare' && entry.mode === 'managed-remote'
237
+ );
238
+
239
+ const tunnels = cloudflareManagedRemote.map((entry) => ({
240
+ id: entry.id,
241
+ name: entry.name,
242
+ hostname: entry.hostname,
243
+ token: entry.token,
244
+ updatedAt: Number.isFinite(entry.updatedAt) ? entry.updatedAt : Date.now(),
245
+ }));
246
+
247
+ const filePath = getLegacyCloudflareManagedRemoteFilePath();
248
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
249
+ fs.writeFileSync(filePath, JSON.stringify({ version: 1, tunnels }, null, 2), { encoding: 'utf8', mode: 0o600 });
250
+ }
251
+
252
+ function readLegacyManagedRemoteEntries() {
253
+ try {
254
+ const raw = fs.readFileSync(getLegacyCloudflareManagedRemoteFilePath(), 'utf8');
255
+ const parsed = JSON.parse(raw);
256
+ const tunnels = Array.isArray(parsed?.tunnels) ? parsed.tunnels : [];
257
+ return tunnels
258
+ .map((entry) => {
259
+ if (!entry || typeof entry !== 'object') return null;
260
+ const id = typeof entry.id === 'string' && entry.id.trim().length > 0 ? entry.id.trim() : crypto.randomUUID();
261
+ const name = normalizeProfileName(entry.name);
262
+ const hostname = normalizeProfileHostname(entry.hostname);
263
+ const token = normalizeProfileToken(entry.token);
264
+ if (!name || !hostname || !token) return null;
265
+ return {
266
+ id,
267
+ name,
268
+ provider: 'cloudflare',
269
+ mode: 'managed-remote',
270
+ hostname,
271
+ token,
272
+ createdAt: Number.isFinite(entry.updatedAt) ? entry.updatedAt : Date.now(),
273
+ updatedAt: Number.isFinite(entry.updatedAt) ? entry.updatedAt : Date.now(),
274
+ };
275
+ })
276
+ .filter(Boolean);
277
+ } catch {
278
+ return [];
279
+ }
280
+ }
281
+
282
+ function makeUniqueProfileName(provider, desiredName, existingProfiles) {
283
+ const normalizedDesired = normalizeProfileName(desiredName);
284
+ if (!normalizedDesired) {
285
+ return '';
286
+ }
287
+ const existingNames = new Set(
288
+ existingProfiles
289
+ .filter((entry) => entry.provider === provider)
290
+ .map((entry) => entry.name.toLowerCase())
291
+ );
292
+
293
+ if (!existingNames.has(normalizedDesired.toLowerCase())) {
294
+ return normalizedDesired;
295
+ }
296
+
297
+ let index = 2;
298
+ while (true) {
299
+ const candidate = `${normalizedDesired}-${index}`;
300
+ if (!existingNames.has(candidate.toLowerCase())) {
301
+ return candidate;
302
+ }
303
+ index += 1;
304
+ }
305
+ }
306
+
307
+ function ensureTunnelProfilesMigrated(options = {}) {
308
+ const current = readTunnelProfilesFromDisk(options);
309
+ if (current.profiles.length > 0) {
310
+ return current;
311
+ }
312
+
313
+ const legacyEntries = readLegacyManagedRemoteEntries();
314
+ if (legacyEntries.length === 0) {
315
+ return current;
316
+ }
317
+
318
+ const migratedProfiles = [];
319
+ for (const entry of legacyEntries) {
320
+ const name = makeUniqueProfileName(entry.provider, entry.name, migratedProfiles);
321
+ migratedProfiles.push({ ...entry, name });
322
+ }
323
+
324
+ const migrated = sanitizeTunnelProfilesData({ version: TUNNEL_PROFILES_VERSION, profiles: migratedProfiles });
325
+ writeTunnelProfilesToDisk(migrated);
326
+ writeManagedRemotePairsToDiskFromProfiles(migrated);
327
+ return migrated;
328
+ }
329
+
330
+ function resolveProfileByName(profiles, profileName, provider) {
331
+ const normalizedName = normalizeProfileName(profileName).toLowerCase();
332
+ const normalizedProvider = normalizeProfileProvider(provider);
333
+ const matches = profiles.filter((entry) => {
334
+ if (entry.name.toLowerCase() !== normalizedName) return false;
335
+ if (!normalizedProvider) return true;
336
+ return entry.provider === normalizedProvider;
337
+ });
338
+
339
+ if (matches.length === 0) {
340
+ return { profile: null, error: `No tunnel profile found for name '${profileName}'. Run 'openchamber tunnel profile list'.` };
341
+ }
342
+ if (matches.length > 1) {
343
+ return { profile: null, error: `Profile name '${profileName}' exists for multiple providers. Use --provider <id>.` };
344
+ }
345
+ return { profile: matches[0], error: null };
346
+ }
347
+
348
+
349
+ export {
350
+ normalizeProfileProvider,
351
+ normalizeProfileMode,
352
+ normalizeProfileName,
353
+ normalizeProfileHostname,
354
+ normalizeProfileToken,
355
+ suggestProfileNameFromHostname,
356
+ maskToken,
357
+ resolveToken,
358
+ redactProfileForOutput,
359
+ redactProfilesForOutput,
360
+ formatProfileTokenStatus,
361
+ warnIfUnsafeFilePermissions,
362
+ writeTunnelProfilesToDisk,
363
+ writeManagedRemotePairsToDiskFromProfiles,
364
+ ensureTunnelProfilesMigrated,
365
+ resolveProfileByName,
366
+ };
@@ -0,0 +1,300 @@
1
+ import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
2
+ import { canPrompt, select as clackSelect, text as clackText, cancel as clackCancel, isCancel as clackIsCancel } from '../cli-output.js';
3
+
4
+ const TUNNEL_BOOTSTRAP_TTL_DEFAULT_MS = 30 * 60 * 1000;
5
+ const TUNNEL_BOOTSTRAP_TTL_MIN_MS = 60 * 1000;
6
+ const TUNNEL_BOOTSTRAP_TTL_MAX_MS = 24 * 60 * 60 * 1000;
7
+ const TUNNEL_SESSION_TTL_DEFAULT_MS = 8 * 60 * 60 * 1000;
8
+ const TUNNEL_SESSION_TTL_MIN_MS = 5 * 60 * 1000;
9
+ const TUNNEL_SESSION_TTL_MAX_MS = 30 * 24 * 60 * 60 * 1000;
10
+ const CONNECT_TTL_PICKER_OPTIONS = [
11
+ { value: String(3 * 60 * 1000), label: '3m' },
12
+ { value: String(TUNNEL_BOOTSTRAP_TTL_DEFAULT_MS), label: '30m' },
13
+ { value: String(2 * 60 * 60 * 1000), label: '2h' },
14
+ { value: String(8 * 60 * 60 * 1000), label: '8h' },
15
+ { value: String(24 * 60 * 60 * 1000), label: '24h' },
16
+ { value: '__custom__', label: 'Custom' },
17
+ ];
18
+ const SESSION_TTL_PICKER_OPTIONS = [
19
+ { value: String(60 * 60 * 1000), label: '1h' },
20
+ { value: String(TUNNEL_SESSION_TTL_DEFAULT_MS), label: '8h' },
21
+ { value: String(12 * 60 * 60 * 1000), label: '12h' },
22
+ { value: String(24 * 60 * 60 * 1000), label: '24h' },
23
+ { value: String(7 * 24 * 60 * 60 * 1000), label: '1w' },
24
+ { value: String(30 * 24 * 60 * 60 * 1000), label: '30d' },
25
+ { value: '__custom__', label: 'Custom' },
26
+ ];
27
+
28
+ function parseHumanDurationToMs(value) {
29
+ if (typeof value === 'number' && Number.isFinite(value)) {
30
+ return Math.round(value);
31
+ }
32
+ if (typeof value !== 'string') {
33
+ return null;
34
+ }
35
+
36
+ const trimmed = value.trim().toLowerCase();
37
+ if (!trimmed) {
38
+ return null;
39
+ }
40
+
41
+ if (/^\d+$/.test(trimmed)) {
42
+ return Number.parseInt(trimmed, 10);
43
+ }
44
+
45
+ const normalized = trimmed.replace(/\s+/g, '');
46
+ const pattern = /(\d+)(ms|s|m|h|d)/g;
47
+ let cursor = 0;
48
+ let total = 0;
49
+ let match;
50
+ while ((match = pattern.exec(normalized)) !== null) {
51
+ if (match.index !== cursor) {
52
+ return null;
53
+ }
54
+ cursor = pattern.lastIndex;
55
+ const amount = Number.parseInt(match[1], 10);
56
+ const unit = match[2];
57
+ const unitMs = unit === 'ms'
58
+ ? 1
59
+ : unit === 's'
60
+ ? 1000
61
+ : unit === 'm'
62
+ ? 60 * 1000
63
+ : unit === 'h'
64
+ ? 60 * 60 * 1000
65
+ : 24 * 60 * 60 * 1000;
66
+ total += amount * unitMs;
67
+ }
68
+
69
+ if (cursor !== normalized.length) {
70
+ return null;
71
+ }
72
+
73
+ return total;
74
+ }
75
+
76
+ function parseTtlMsOrThrow(rawValue, {
77
+ flagName,
78
+ minMs,
79
+ maxMs,
80
+ } = {}) {
81
+ const parsed = parseHumanDurationToMs(rawValue);
82
+ if (!Number.isFinite(parsed) || parsed <= 0) {
83
+ throw new TunnelCliError(
84
+ `Invalid value for ${flagName}. Use a positive duration like 30m, 24h, 1d, or milliseconds.`,
85
+ EXIT_CODE.USAGE_ERROR,
86
+ );
87
+ }
88
+ if (parsed < minMs || parsed > maxMs) {
89
+ throw new TunnelCliError(
90
+ `${flagName} must be between ${minMs}ms and ${maxMs}ms.`,
91
+ EXIT_CODE.USAGE_ERROR,
92
+ );
93
+ }
94
+ return parsed;
95
+ }
96
+
97
+ function formatDurationForCli(ms) {
98
+ if (!Number.isFinite(ms) || ms <= 0) {
99
+ return null;
100
+ }
101
+ const value = Math.round(ms);
102
+ if (value % (24 * 60 * 60 * 1000) === 0) return `${value / (24 * 60 * 60 * 1000)}d`;
103
+ if (value % (60 * 60 * 1000) === 0) return `${value / (60 * 60 * 1000)}h`;
104
+ if (value % (60 * 1000) === 0) return `${value / (60 * 1000)}m`;
105
+ if (value % 1000 === 0) return `${value / 1000}s`;
106
+ return `${value}ms`;
107
+ }
108
+
109
+ function shellQuote(value) {
110
+ const text = String(value);
111
+ if (/^[A-Za-z0-9._\-/:=]+$/.test(text)) {
112
+ return text;
113
+ }
114
+ return `'${text.replace(/'/g, `'"'"'`)}'`;
115
+ }
116
+
117
+ function buildTunnelStartReplayCommand({
118
+ port,
119
+ provider,
120
+ mode,
121
+ profileName,
122
+ configPath,
123
+ hostname,
124
+ connectTtlMs,
125
+ sessionTtlMs,
126
+ qr,
127
+ noQr,
128
+ includeTokenPlaceholder,
129
+ tokenViaStdin,
130
+ tokenFileProvided,
131
+ }) {
132
+ const parts = ['openchamber', 'tunnel', 'start'];
133
+ if (Number.isFinite(port) && port > 0) {
134
+ parts.push('--port', String(port));
135
+ }
136
+ if (profileName) {
137
+ parts.push('--profile', shellQuote(profileName));
138
+ }
139
+ if (provider) {
140
+ parts.push('--provider', shellQuote(provider));
141
+ }
142
+ if (mode) {
143
+ parts.push('--mode', shellQuote(mode));
144
+ }
145
+ if (typeof configPath === 'string' && configPath.trim().length > 0) {
146
+ parts.push('--config', shellQuote(configPath));
147
+ }
148
+ if (typeof hostname === 'string' && hostname.trim().length > 0) {
149
+ parts.push('--hostname', shellQuote(hostname));
150
+ }
151
+ const connectTtl = formatDurationForCli(connectTtlMs);
152
+ if (connectTtl) {
153
+ parts.push('--connect-ttl', connectTtl);
154
+ }
155
+ const sessionTtl = formatDurationForCli(sessionTtlMs);
156
+ if (sessionTtl) {
157
+ parts.push('--session-ttl', sessionTtl);
158
+ }
159
+ if (qr) parts.push('--qr');
160
+ if (noQr) parts.push('--no-qr');
161
+
162
+ if (includeTokenPlaceholder) {
163
+ if (tokenViaStdin) {
164
+ parts.push('--token-stdin');
165
+ } else if (tokenFileProvided) {
166
+ parts.push('--token-file', '<redacted>');
167
+ } else {
168
+ parts.push('--token', '<redacted>');
169
+ }
170
+ }
171
+
172
+ return parts.join(' ');
173
+ }
174
+
175
+ function buildTunnelProfileAddCommand({ provider, hostname }) {
176
+ const parts = [
177
+ 'openchamber',
178
+ 'tunnel',
179
+ 'profile',
180
+ 'add',
181
+ '--provider',
182
+ shellQuote(provider || 'cloudflare'),
183
+ '--mode',
184
+ 'managed-remote',
185
+ '--name',
186
+ '<name>',
187
+ '--hostname',
188
+ shellQuote(hostname || '<hostname>'),
189
+ '--token',
190
+ '<token>',
191
+ ];
192
+ return parts.join(' ');
193
+ }
194
+
195
+ async function resolveTunnelTtlOverrides(options) {
196
+ let connectTtlRaw = typeof options.connectTtl === 'string' ? options.connectTtl : undefined;
197
+ let sessionTtlRaw = typeof options.sessionTtl === 'string' ? options.sessionTtl : undefined;
198
+
199
+ const shouldPrompt = !connectTtlRaw
200
+ && !sessionTtlRaw
201
+ && canPrompt(options);
202
+
203
+ if (shouldPrompt) {
204
+ const connectChoice = await clackSelect({
205
+ message: 'Select connect-link TTL',
206
+ options: CONNECT_TTL_PICKER_OPTIONS,
207
+ });
208
+ if (clackIsCancel(connectChoice)) {
209
+ clackCancel('Tunnel start cancelled.');
210
+ return null;
211
+ }
212
+ if (connectChoice === '__custom__') {
213
+ const enteredConnect = await clackText({
214
+ message: 'Enter connect-link TTL (e.g. 30m, 2h, 1d)',
215
+ placeholder: '30m',
216
+ validate(value) {
217
+ try {
218
+ parseTtlMsOrThrow(value, {
219
+ flagName: '--connect-ttl',
220
+ minMs: TUNNEL_BOOTSTRAP_TTL_MIN_MS,
221
+ maxMs: TUNNEL_BOOTSTRAP_TTL_MAX_MS,
222
+ });
223
+ return undefined;
224
+ } catch (error) {
225
+ return error instanceof Error ? error.message : 'Invalid TTL value';
226
+ }
227
+ },
228
+ });
229
+ if (clackIsCancel(enteredConnect)) {
230
+ clackCancel('Tunnel start cancelled.');
231
+ return null;
232
+ }
233
+ connectTtlRaw = enteredConnect.trim();
234
+ } else {
235
+ connectTtlRaw = connectChoice;
236
+ }
237
+
238
+ const sessionChoice = await clackSelect({
239
+ message: 'Select session TTL',
240
+ options: SESSION_TTL_PICKER_OPTIONS,
241
+ });
242
+ if (clackIsCancel(sessionChoice)) {
243
+ clackCancel('Tunnel start cancelled.');
244
+ return null;
245
+ }
246
+ if (sessionChoice === '__custom__') {
247
+ const enteredSession = await clackText({
248
+ message: 'Enter session TTL (e.g. 8h, 24h, 1d)',
249
+ placeholder: '8h',
250
+ validate(value) {
251
+ try {
252
+ parseTtlMsOrThrow(value, {
253
+ flagName: '--session-ttl',
254
+ minMs: TUNNEL_SESSION_TTL_MIN_MS,
255
+ maxMs: TUNNEL_SESSION_TTL_MAX_MS,
256
+ });
257
+ return undefined;
258
+ } catch (error) {
259
+ return error instanceof Error ? error.message : 'Invalid TTL value';
260
+ }
261
+ },
262
+ });
263
+ if (clackIsCancel(enteredSession)) {
264
+ clackCancel('Tunnel start cancelled.');
265
+ return null;
266
+ }
267
+ sessionTtlRaw = enteredSession.trim();
268
+ } else {
269
+ sessionTtlRaw = sessionChoice;
270
+ }
271
+ }
272
+
273
+ const connectTtlMs = connectTtlRaw !== undefined
274
+ ? parseTtlMsOrThrow(connectTtlRaw, {
275
+ flagName: '--connect-ttl',
276
+ minMs: TUNNEL_BOOTSTRAP_TTL_MIN_MS,
277
+ maxMs: TUNNEL_BOOTSTRAP_TTL_MAX_MS,
278
+ })
279
+ : undefined;
280
+
281
+ const sessionTtlMs = sessionTtlRaw !== undefined
282
+ ? parseTtlMsOrThrow(sessionTtlRaw, {
283
+ flagName: '--session-ttl',
284
+ minMs: TUNNEL_SESSION_TTL_MIN_MS,
285
+ maxMs: TUNNEL_SESSION_TTL_MAX_MS,
286
+ })
287
+ : undefined;
288
+
289
+ return {
290
+ connectTtlMs,
291
+ sessionTtlMs,
292
+ };
293
+ }
294
+
295
+
296
+ export {
297
+ buildTunnelStartReplayCommand,
298
+ buildTunnelProfileAddCommand,
299
+ resolveTunnelTtlOverrides,
300
+ };