@gotcos/glasses-server 6.12.1 → 6.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example CHANGED
@@ -38,7 +38,7 @@ BIND_HOST=0.0.0.0
38
38
 
39
39
  # ── THE LLM (chat) ──────────────────────────────────────────────────────
40
40
  # Chat runs through your LOCAL agent CLI — NOT an API key:
41
- # Opus / Fable / Sonnet -> Claude Code CLI (https://claude.ai/download, then `claude login`)
41
+ # Opus / Fable / Sonnet -> Claude Code CLI (https://docs.anthropic.com/en/docs/claude-code/getting-started, then `claude auth login`)
42
42
  # GPT Frontier/Balanced -> Codex CLI (https://developers.openai.com/codex/, then `codex login`)
43
43
  # Install at least one. Pick the default model the glasses use:
44
44
  # COS_G2_DEFAULT_MODEL=sonnet # opus | fable | sonnet | codex-frontier | codex-balanced
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 6.12.2
4
+
5
+ First-install hardening for public `npx` users.
6
+
7
+ - **No nested install inside npm's cache.** The launcher resolves the declared
8
+ `tsx` dependency from npm's existing `npx` dependency tree and never runs a
9
+ second `npm install` from the ephemeral package directory.
10
+ - **Permission failures do not spread.** A broken or incomplete package fails
11
+ closed with a user-owned isolated-cache recovery command. COS never suggests
12
+ `sudo npm`, broad ownership changes, or writing through a root-owned cache.
13
+ - **Claude Desktop is no longer mistaken for Claude Code.** First-run guidance
14
+ explicitly requires the terminal CLI, keeps the scoped npm command on one
15
+ copyable line, forbids `sudo`, and explains the interactive sign-in step.
16
+ - **Known signed-out agents fail before startup.** Installed Claude/Codex
17
+ binaries are checked before first-query readiness. Older CLI versions whose
18
+ authentication state cannot be proven show a warning instead of a false
19
+ signed-in claim.
20
+ - **Local credentials are private.** `~/.cos-glasses` is repaired to `0700`;
21
+ the token and profile files are repaired to `0600`; symlinked credential
22
+ paths fail closed; auto-generated tokens are persisted with an atomic write.
23
+ - **Runtime behavior is unchanged.** Query, prompt recovery, meetings, media,
24
+ diagnostics, transcription, display, and server data contracts are untouched.
25
+
3
26
  ## 6.12.1
4
27
 
5
28
  Public-safe CLI diagnostics for the COS Glasses Recovery Center.
package/README.md CHANGED
@@ -8,7 +8,7 @@ API key is pasted into the phone for chat.
8
8
  ## Quick start
9
9
 
10
10
  ```bash
11
- npx @gotcos/glasses-server
11
+ npx --yes @gotcos/glasses-server@latest
12
12
  ```
13
13
 
14
14
  The launcher checks Node, finds your CLI, checks voice and image processing,
@@ -24,7 +24,10 @@ without silently losing completed replies.
24
24
  ## Requirements
25
25
 
26
26
  - **Node.js 20.11+** — https://nodejs.org
27
- - **Claude Code CLI** (Opus/Fable/Sonnet) https://claude.ai/download, then `claude login`
27
+ - **Claude Code CLI** (Opus/Fable/Sonnet). Claude Desktop alone does not install
28
+ the terminal command. Install it on one line with
29
+ `npm install -g @anthropic-ai/claude-code` (**never with `sudo`**), then run
30
+ `claude` and finish the browser sign-in
28
31
  _or_ **Codex CLI** (GPT Frontier/Balanced) — https://developers.openai.com/codex/, then `codex login`
29
32
  - **Even G2 glasses** + the **COS Glasses** app from the Even Hub
30
33
  - `brew install whisper-cpp` for free local voice (the launcher can download the model)
@@ -106,9 +109,20 @@ BIND_HOST=0.0.0.0 npm run start:server
106
109
 
107
110
  ## Troubleshooting
108
111
 
112
+ - *Claude Desktop is installed but COS says Claude Code is missing* — Desktop
113
+ and the terminal CLI are separate. Run
114
+ `npm install -g @anthropic-ai/claude-code` on one line without `sudo`, then
115
+ run `claude` and complete sign-in. Verify with `claude --version` before
116
+ starting COS again.
117
+ - *npm reports EACCES or a root-owned cache* — never run COS or npm with
118
+ `sudo`, and do not recursively change system ownership. Use a private COS
119
+ cache instead:
120
+ `npm_config_cache="$HOME/.cos-glasses/npm-cache" npx --yes @gotcos/glasses-server@latest`.
121
+ Version 6.12.2+ never runs a second install from inside npm's temporary cache.
109
122
  - *Phone can't connect* — check `BIND_HOST=0.0.0.0`, the same Tailscale account on both devices, and the correct `100.x` IP + token.
110
- - *Safari connects but the app does not* — confirm `npx @gotcos/glasses-server@latest` is 6.6.0+, then use the app's server reconnect/edit control to verify the current URL and token. Do not run a second source or `npx` server alongside it.
111
- - *AI queries fail* — run `claude --version` / `codex --version`, then `claude login` / `codex login`.
123
+ - *Safari connects but the app does not* — confirm `npx --yes @gotcos/glasses-server@latest` is 6.6.0+, then use the app's server reconnect/edit control to verify the current URL and token. Do not run a second source or `npx` server alongside it.
124
+ - *AI queries fail* — run `claude auth status` / `codex login status`, then
125
+ `claude auth login` / `codex login` when the provider reports signed out.
112
126
  - *Voice getting billed?* — voice is local-only by default in 6.12.0+. Confirm
113
127
  `/api/health` reports `capabilities.transcription.mode: "local-only"`. Remove
114
128
  `COS_OPENAI_WHISPER_FALLBACK` (or set it to `0`) to disable an earlier opt-in.
@@ -117,7 +131,7 @@ BIND_HOST=0.0.0.0 npm run start:server
117
131
  keeps compatible prompt/meeting audio available for retry instead of silently
118
132
  sending it to OpenAI.
119
133
  - *Photos unavailable?* — install `ffmpeg`, restart the server, and confirm `/api/health` reports `features.mediaProcessingReady: true`.
120
- - *Prompt recovery unavailable?* — update with `npx @gotcos/glasses-server@latest`, then confirm `/api/health` reports `features.promptRecovery: true`.
134
+ - *Prompt recovery unavailable?* — update with `npx --yes @gotcos/glasses-server@latest`, then confirm `/api/health` reports `features.promptRecovery: true`.
121
135
  - *Durable query recovery unavailable?* — build 204+ requires server 6.10.0+ and
122
136
  `COS_DURABLE_QUERY_JOBS=1`. Restart once, then confirm `/api/health` reports
123
137
  `features.durableQueryJobs: true`, protocol `1`, and state `ready`. To roll
package/bin/cli.cjs CHANGED
@@ -5,7 +5,17 @@
5
5
  // package — there is no clone. Config persists at ~/.cos-glasses/.
6
6
 
7
7
  const { execSync, spawn } = require('child_process')
8
- const { existsSync, mkdirSync, statSync, readFileSync, copyFileSync, unlinkSync, renameSync } = require('fs')
8
+ const {
9
+ existsSync,
10
+ mkdirSync,
11
+ statSync,
12
+ lstatSync,
13
+ readFileSync,
14
+ copyFileSync,
15
+ unlinkSync,
16
+ renameSync,
17
+ chmodSync,
18
+ } = require('fs')
9
19
  const { join, resolve } = require('path')
10
20
  const { homedir } = require('os')
11
21
 
@@ -30,11 +40,11 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {
30
40
  console.log(bold(' COS Glasses Server'))
31
41
  console.log('')
32
42
  console.log(' Usage:')
33
- console.log(' npx @gotcos/glasses-server')
43
+ console.log(' npx --yes @gotcos/glasses-server@latest')
34
44
  console.log('')
35
45
  console.log(' Requirements:')
36
46
  console.log(' - Node.js 20.11+')
37
- console.log(' - Claude Code CLI (Opus / Fable / Sonnet) or Codex CLI (GPT Frontier / Balanced)')
47
+ console.log(' - Claude Code CLI (not Claude Desktop) or Codex CLI')
38
48
  console.log(' - Even G2 smart glasses + the COS Glasses app (Even Hub)')
39
49
  console.log('')
40
50
  console.log(' No API key is needed for chat — it runs through your installed CLI.')
@@ -72,52 +82,142 @@ function normalizeCodexVersion(raw) {
72
82
  const line = raw.split('\n').map((s) => s.trim()).find((s) => /^codex(?:-cli)?\s+/i.test(s)) || raw.split('\n')[0].trim()
73
83
  return line.replace(/^codex(?:-cli)?\s*/i, '') || line
74
84
  }
85
+ function commandResult(command) {
86
+ try {
87
+ return {
88
+ ok: true,
89
+ output: execSync(`${command} 2>&1`, { shell: '/bin/sh', stdio: 'pipe', timeout: 5000 }).toString().trim(),
90
+ }
91
+ } catch (err) {
92
+ return {
93
+ ok: false,
94
+ output: (err.stdout?.toString() || err.stderr?.toString() || '').trim(),
95
+ }
96
+ }
97
+ }
98
+ function claudeAuthState() {
99
+ const result = commandResult('claude auth status --json')
100
+ try {
101
+ const parsed = JSON.parse(result.output)
102
+ if (parsed.loggedIn === true) return 'ready'
103
+ if (parsed.loggedIn === false) return 'signed-out'
104
+ } catch { /* older CLIs may not support JSON status */ }
105
+ if (/not logged in|logged out|sign[ -]?in required/i.test(result.output)) return 'signed-out'
106
+ return 'unknown'
107
+ }
108
+ function codexAuthState() {
109
+ const result = commandResult('codex login status')
110
+ if (/logged in/i.test(result.output) && !/not logged in/i.test(result.output)) return 'ready'
111
+ if (/not logged in|logged out|sign[ -]?in required/i.test(result.output)) return 'signed-out'
112
+ return 'unknown'
113
+ }
75
114
  const claudeVersion = getCliVersion('claude')
76
115
  const codexVersion = getCliVersion('codex')
116
+ const claudeAuth = claudeVersion ? claudeAuthState() : null
117
+ const codexAuth = codexVersion ? codexAuthState() : null
77
118
  if (claudeVersion) {
78
- console.log(green('') + ` Claude Code ${claudeVersion} ` + dim('(Opus / Fable / Sonnet)'))
119
+ if (claudeAuth === 'signed-out') {
120
+ console.log(yellow(' ⚠') + ` Claude Code ${claudeVersion} installed — sign-in required`)
121
+ console.log(' Run: ' + bold('claude auth login'))
122
+ } else if (claudeAuth === 'unknown') {
123
+ console.log(yellow(' ⚠') + ` Claude Code ${claudeVersion} installed — sign-in status unavailable`)
124
+ console.log(' Verify: ' + bold('claude auth status'))
125
+ } else {
126
+ console.log(green(' ✓') + ` Claude Code ${claudeVersion} ` + dim('(Opus / Fable / Sonnet)'))
127
+ }
79
128
  } else {
80
129
  console.log(yellow(' ⚠') + ' Claude Code CLI not found ' + dim('— Opus/Fable/Sonnet unavailable'))
81
- console.log(' Install: ' + bold('https://claude.ai/download'))
130
+ console.log(' Claude Desktop does not install the terminal CLI.')
131
+ console.log(' Install (no sudo): ' + bold('npm install -g @anthropic-ai/claude-code'))
132
+ console.log(' Then run: ' + bold('claude') + ' and finish sign-in')
82
133
  }
83
134
  if (codexVersion) {
84
- console.log(green(' ✓') + ` Codex CLI ${normalizeCodexVersion(codexVersion)} ` + dim('(GPT Frontier / Balanced)'))
135
+ if (codexAuth === 'signed-out') {
136
+ console.log(yellow(' ⚠') + ` Codex CLI ${normalizeCodexVersion(codexVersion)} installed — sign-in required`)
137
+ console.log(' Run: ' + bold('codex login'))
138
+ } else if (codexAuth === 'unknown') {
139
+ console.log(yellow(' ⚠') + ` Codex CLI ${normalizeCodexVersion(codexVersion)} installed — sign-in status unavailable`)
140
+ console.log(' Verify: ' + bold('codex login status'))
141
+ } else {
142
+ console.log(green(' ✓') + ` Codex CLI ${normalizeCodexVersion(codexVersion)} ` + dim('(GPT Frontier / Balanced)'))
143
+ }
85
144
  } else {
86
145
  console.log(yellow(' ⚠') + ' Codex CLI not found ' + dim('— GPT Frontier/Balanced unavailable'))
87
146
  }
88
- if (!claudeVersion && !codexVersion) {
147
+ const hasUsableAgent = (claudeVersion && claudeAuth !== 'signed-out') || (codexVersion && codexAuth !== 'signed-out')
148
+ if (!hasUsableAgent) {
89
149
  console.log('')
90
- console.log(red(' ✗ No supported agent CLI found'))
91
- console.log(' Install Claude Code: ' + bold('https://claude.ai/download'))
150
+ console.log(red(' ✗ No signed-in agent CLI is ready'))
151
+ console.log(' Claude Desktop alone is not enough; COS needs a terminal CLI.')
152
+ console.log(' Install Claude Code (no sudo): ' + bold('npm install -g @anthropic-ai/claude-code'))
153
+ console.log(' Then run: ' + bold('claude auth login'))
92
154
  console.log(' or Codex CLI: ' + bold('https://developers.openai.com/codex/') + ' then ' + bold('codex login'))
155
+ console.log(' Setup help: ' + bold('https://www.gotcos.com/wizard/'))
93
156
  console.log('')
94
157
  process.exit(1)
95
158
  }
96
159
 
97
- // Step 3: dependencies only when run from a git clone without node_modules.
98
- // `npx` already installed the package's deps alongside it.
99
- if (!existsSync(join(PKG_ROOT, 'node_modules'))) {
160
+ // Step 3: resolve the dependency npm already installed. With `npx`, dependency
161
+ // packages are siblings in npm's temporary node_modules tree rather than under
162
+ // PKG_ROOT/node_modules. Running a second `npm install` from inside that cache
163
+ // is both unnecessary and unsafe: a prior sudo-based npm install can make the
164
+ // shared cache root-owned and turn an otherwise valid first launch into EACCES.
165
+ let tsxImport
166
+ try {
167
+ tsxImport = require.resolve('tsx/esm', { paths: [PKG_ROOT] })
168
+ } catch {
100
169
  console.log('')
101
- console.log(` ${yellow('⟳')} Installing dependencies...`)
102
- try {
103
- execSync('npm install', { cwd: PKG_ROOT, stdio: 'pipe', timeout: 300000 })
104
- console.log(green('') + ' Dependencies installed')
105
- } catch (err) {
106
- console.log(red(' ✗ npm install failed'))
107
- console.log(` ${err.stderr?.toString().slice(0, 200) || err.message}`)
108
- process.exit(1)
109
- }
170
+ console.log(red(' COS package dependencies are incomplete'))
171
+ console.log(' Do not use sudo. Retry with an isolated user-owned npm cache:')
172
+ console.log(' ' + bold('npm_config_cache="$HOME/.cos-glasses/npm-cache" npx --yes @gotcos/glasses-server@latest'))
173
+ console.log(' Source installs only: run ' + bold('npm install') + ' in the cloned repository.')
174
+ process.exit(1)
110
175
  }
111
176
 
112
177
  // Step 4: persistent config at ~/.cos-glasses/ (survives npx cache churn)
113
- mkdirSync(CONFIG_DIR, { recursive: true })
178
+ function securePrivateDirectory(dir) {
179
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
180
+ const stats = lstatSync(dir)
181
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
182
+ throw new Error(`${dir} must be a private directory, not a symlink`)
183
+ }
184
+ chmodSync(dir, 0o700)
185
+ }
186
+
187
+ function securePrivateFile(file) {
188
+ if (!existsSync(file)) return
189
+ const stats = lstatSync(file)
190
+ if (stats.isSymbolicLink() || !stats.isFile()) {
191
+ throw new Error(`${file} must be a regular file, not a symlink`)
192
+ }
193
+ chmodSync(file, 0o600)
194
+ }
195
+
196
+ try {
197
+ securePrivateDirectory(CONFIG_DIR)
198
+ } catch (err) {
199
+ console.log('')
200
+ console.log(red(' ✗ COS config directory is unsafe'))
201
+ console.log(` ${err.message}`)
202
+ console.log(' Move it aside and rerun COS; do not use sudo or broad ownership changes.')
203
+ process.exit(1)
204
+ }
114
205
  const ENV_FILE = join(CONFIG_DIR, '.env')
115
206
  const ENV_EXAMPLE = join(PKG_ROOT, '.env.example')
116
207
  if (!existsSync(ENV_FILE) && existsSync(ENV_EXAMPLE)) {
117
208
  copyFileSync(ENV_EXAMPLE, ENV_FILE)
209
+ chmodSync(ENV_FILE, 0o600)
118
210
  console.log(green(' ✓') + ` Created config at ${dim(ENV_FILE)}`)
119
211
  }
120
212
  if (existsSync(ENV_FILE)) {
213
+ try {
214
+ securePrivateFile(ENV_FILE)
215
+ } catch (err) {
216
+ console.log('')
217
+ console.log(red(' ✗ COS config file is unsafe'))
218
+ console.log(` ${err.message}`)
219
+ process.exit(1)
220
+ }
121
221
  try {
122
222
  for (const line of readFileSync(ENV_FILE, 'utf-8').split('\n')) {
123
223
  const m = line.match(/^\s*([A-Z_][A-Z0-9_]*)=(.*)$/)
@@ -130,6 +230,15 @@ const PROFILE_FILE = join(CONFIG_DIR, '.cos-profile.json')
130
230
  const PROFILE_EXAMPLE = join(PKG_ROOT, '.cos-profile.example.json')
131
231
  if (!existsSync(PROFILE_FILE) && existsSync(PROFILE_EXAMPLE)) {
132
232
  copyFileSync(PROFILE_EXAMPLE, PROFILE_FILE)
233
+ chmodSync(PROFILE_FILE, 0o600)
234
+ }
235
+ try {
236
+ securePrivateFile(PROFILE_FILE)
237
+ } catch (err) {
238
+ console.log('')
239
+ console.log(red(' ✗ COS profile is unsafe'))
240
+ console.log(` ${err.message}`)
241
+ process.exit(1)
133
242
  }
134
243
  if (!process.env.COS_PROFILE_PATH) process.env.COS_PROFILE_PATH = PROFILE_FILE
135
244
 
@@ -156,14 +265,15 @@ function isValidWhisperModel(p) {
156
265
  }
157
266
  const whisperCliPath = findWhisperCli()
158
267
  const hasValidModel = isValidWhisperModel(WHISPER_MODEL_PATH)
268
+ let localVoiceReady = Boolean(whisperCliPath && hasValidModel)
159
269
  if (whisperCliPath && hasValidModel) {
160
270
  console.log(green(' ✓') + ' whisper.cpp + model ready ' + dim('— voice = local (FREE)'))
161
271
  } else if (whisperCliPath && !hasValidModel) {
162
272
  if (existsSync(WHISPER_MODEL_PATH)) { try { unlinkSync(WHISPER_MODEL_PATH) } catch {} }
163
273
  if (existsSync(WHISPER_MODEL_PARTIAL)) { try { unlinkSync(WHISPER_MODEL_PARTIAL) } catch {} }
164
274
  console.log(yellow(' ⚠') + ' whisper.cpp installed but model missing')
165
- console.log(' ' + dim('Downloading ggml-large-v3-turbo (~1.5 GB). Ctrl-C to skip (voice remains unavailable by default).'))
166
- console.log(' ' + dim('Skip permanently: SKIP_WHISPER_DOWNLOAD=1 npx @gotcos/glasses-server'))
275
+ console.log(' ' + dim('Downloading ggml-large-v3-turbo (~1.5 GB).'))
276
+ console.log(' ' + dim('Skip: SKIP_WHISPER_DOWNLOAD=1 npx --yes @gotcos/glasses-server@latest'))
167
277
  if (process.env.SKIP_WHISPER_DOWNLOAD === '1') {
168
278
  console.log(yellow(' ⚠') + ' SKIP_WHISPER_DOWNLOAD=1 — local voice unavailable')
169
279
  } else {
@@ -173,6 +283,7 @@ if (whisperCliPath && hasValidModel) {
173
283
  const stats = statSync(WHISPER_MODEL_PARTIAL)
174
284
  if (stats.size < WHISPER_MODEL_MIN_BYTES) throw new Error(`Downloaded file too small: ${stats.size} bytes`)
175
285
  renameSync(WHISPER_MODEL_PARTIAL, WHISPER_MODEL_PATH)
286
+ localVoiceReady = true
176
287
  console.log(green(' ✓') + ' Model downloaded ' + dim('— voice = local (FREE)'))
177
288
  } catch (err) {
178
289
  try { unlinkSync(WHISPER_MODEL_PARTIAL) } catch {}
@@ -215,17 +326,23 @@ try {
215
326
  console.log(green(' ✓') + ` COS detected in ${dim(ld)} — glasses chat will load its brain`)
216
327
  }
217
328
  } catch { /* detection is best-effort */ }
329
+ if (!localVoiceReady) {
330
+ console.log('')
331
+ console.log(yellow(' ⚠ LOCAL VOICE NOT READY'))
332
+ console.log(' Text chat can start. Under the default local-only policy, voice prompts remain unavailable.')
333
+ console.log(' Install: ' + bold('brew install whisper-cpp'))
334
+ console.log(' Then stop COS with Ctrl-C and rerun: ' + bold('npx --yes @gotcos/glasses-server@latest'))
335
+ }
218
336
  console.log('')
219
337
  console.log(dim(' Starting server...'))
220
338
  console.log('')
221
339
  const serverProc = spawn(
222
340
  process.execPath,
223
- ['--import', 'tsx/esm', 'server/index.ts'],
341
+ ['--import', tsxImport, 'server/index.ts'],
224
342
  { cwd: PKG_ROOT, stdio: 'inherit', env: { ...process.env } }
225
343
  )
226
344
  serverProc.on('error', (err) => {
227
345
  console.error(red(` Server failed to start: ${err.message}`))
228
- if (err.message.includes('tsx')) console.error(' Try: cd ' + PKG_ROOT + ' && npm install')
229
346
  process.exit(1)
230
347
  })
231
348
  serverProc.on('exit', (code) => process.exit(code ?? 0))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gotcos/glasses-server",
3
- "version": "6.12.1",
3
+ "version": "6.12.2",
4
4
  "description": "COS Glasses — self-hosted AI heads-up-display server for Even G2 smart glasses, powered by your local Claude Code or Codex CLI",
5
5
  "type": "module",
6
6
  "bin": {
package/server/index.ts CHANGED
@@ -7,7 +7,7 @@ import path from 'node:path'
7
7
  import { fileURLToPath } from 'node:url'
8
8
  import { createServer as createHttpsServer } from 'node:https'
9
9
  import { createServer as createHttpServer } from 'node:http'
10
- import { readFileSync, existsSync, appendFileSync, mkdirSync } from 'node:fs'
10
+ import { readFileSync, existsSync } from 'node:fs'
11
11
  import { networkInterfaces, homedir } from 'node:os'
12
12
  import { join } from 'node:path'
13
13
  import { execSync } from 'node:child_process'
@@ -44,6 +44,7 @@ import { getMediaStore } from './lib/media-store.js'
44
44
  import { listenRequiredServers, type RequiredListener } from './lib/listener-startup.js'
45
45
  import { serverMetrics } from './lib/server-metrics.js'
46
46
  import { initializeServerInstanceId } from './lib/server-instance-id.js'
47
+ import { appendPrivateEnvBlock, UnsafeUserConfigPathError } from './lib/secure-user-config.js'
47
48
  import { createQueryJobsRouter } from './routes/query-jobs.js'
48
49
  import {
49
50
  initQueryJobRuntime,
@@ -76,10 +77,16 @@ let API_TOKEN_PERSISTED = false
76
77
  if (API_TOKEN_AUTO) {
77
78
  try {
78
79
  const envDir = join(homedir(), '.cos-glasses')
79
- mkdirSync(envDir, { recursive: true })
80
- appendFileSync(join(envDir, '.env'), `\n# auto-generated by the server so the app token survives restarts\nCOS_API_TOKEN=${API_TOKEN}\n`)
80
+ appendPrivateEnvBlock(
81
+ join(envDir, '.env'),
82
+ `# auto-generated by the server so the app token survives restarts\nCOS_API_TOKEN=${API_TOKEN}\n`,
83
+ )
81
84
  API_TOKEN_PERSISTED = true
82
- } catch { /* read-only home — token stays per-session */ }
85
+ } catch (error) {
86
+ // Read-only homes may continue with a per-session token, but an unsafe
87
+ // symlinked credential path must fail closed instead of being ignored.
88
+ if (error instanceof UnsafeUserConfigPathError) throw error
89
+ }
83
90
  }
84
91
 
85
92
  // IP allowlist — only accept connections from localhost, meshnet, and private networks.
@@ -294,7 +301,7 @@ listenRequiredServers(listeners).then(() => {
294
301
  claudeAvailable = true
295
302
  console.log('[COS API] Claude Code CLI detected')
296
303
  } catch {
297
- console.warn('[COS API] Claude Code CLI not found — install from https://claude.ai/download')
304
+ console.warn('[COS API] Claude Code CLI not found — install from https://docs.anthropic.com/en/docs/claude-code/getting-started')
298
305
  console.warn('[COS API] Claude models unavailable; Codex models still work when Codex CLI is installed')
299
306
  }
300
307
 
@@ -0,0 +1,64 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ unlinkSync,
9
+ writeFileSync,
10
+ } from 'node:fs'
11
+ import { basename, dirname, join } from 'node:path'
12
+
13
+ export class UnsafeUserConfigPathError extends Error {
14
+ constructor(message: string) {
15
+ super(message)
16
+ this.name = 'UnsafeUserConfigPathError'
17
+ }
18
+ }
19
+
20
+ export function securePrivateDirectory(dir: string): void {
21
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
22
+ const stats = lstatSync(dir)
23
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
24
+ throw new UnsafeUserConfigPathError(`${dir} must be a private directory, not a symlink`)
25
+ }
26
+ chmodSync(dir, 0o700)
27
+ }
28
+
29
+ export function secureExistingPrivateFile(file: string): void {
30
+ if (!existsSync(file)) return
31
+ const stats = lstatSync(file)
32
+ if (stats.isSymbolicLink() || !stats.isFile()) {
33
+ throw new UnsafeUserConfigPathError(`${file} must be a regular file, not a symlink`)
34
+ }
35
+ chmodSync(file, 0o600)
36
+ }
37
+
38
+ /**
39
+ * Append an env block without ever following a symlink or exposing a partially
40
+ * written credential file. The replacement is created beside the destination
41
+ * at 0600 and atomically renamed into place.
42
+ */
43
+ export function appendPrivateEnvBlock(file: string, block: string): void {
44
+ const dir = dirname(file)
45
+ securePrivateDirectory(dir)
46
+ secureExistingPrivateFile(file)
47
+
48
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : ''
49
+ const separator = current.length > 0 && !current.endsWith('\n') ? '\n' : ''
50
+ const temp = join(dir, `.${basename(file)}.${process.pid}.${Date.now()}.tmp`)
51
+ try {
52
+ writeFileSync(temp, `${current}${separator}${block}`, {
53
+ encoding: 'utf8',
54
+ flag: 'wx',
55
+ mode: 0o600,
56
+ })
57
+ chmodSync(temp, 0o600)
58
+ renameSync(temp, file)
59
+ chmodSync(file, 0o600)
60
+ } catch (error) {
61
+ try { unlinkSync(temp) } catch { /* best-effort cleanup */ }
62
+ throw error
63
+ }
64
+ }