@xrystal/core 3.55.69 → 3.55.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ import { getCliConfigTlsDir } from './xrystal-config.mjs'
6
+ import { resolveUserHome } from './xrystal-registry.mjs'
7
+
8
+ export function defaultCertificatesDir() {
9
+ return path.join(resolveUserHome(), 'certificates')
10
+ }
11
+
12
+ function expandHome(filePath) {
13
+ const raw = String(filePath ?? '').trim()
14
+ if (!raw) return raw
15
+ if (raw.startsWith('~/')) return path.join(os.homedir(), raw.slice(2))
16
+ if (raw === '~') return os.homedir()
17
+ return raw
18
+ }
19
+
20
+ export function isTlsTreeRoot(root) {
21
+ if (!root) return false
22
+ return fs.existsSync(path.join(root, 'root', 'ca.crt'))
23
+ }
24
+
25
+ export function isTlsFlatBundle(dir) {
26
+ if (!dir) return false
27
+ return fs.existsSync(path.join(dir, 'ca.crt'))
28
+ }
29
+
30
+ function tryTlsRoot(root) {
31
+ if (!root) return null
32
+ const resolved = path.resolve(expandHome(root))
33
+ if (isTlsTreeRoot(resolved)) return { kind: 'tree', root: resolved }
34
+ if (isTlsFlatBundle(resolved)) return { kind: 'flat', root: resolved }
35
+ return null
36
+ }
37
+
38
+ /**
39
+ * Operator SoT only — explicit env, config tlsDir, or ~/.xrystal/certificates (no repo fallbacks).
40
+ * @returns {{ kind: 'tree'|'flat', root: string } | null}
41
+ */
42
+ export function resolveTlsSource() {
43
+ const fromExplicit = tryTlsRoot(process.env.XRY_TLS_SOURCE || process.env.TELEPRESENCE_CERT_ROOT)
44
+ if (fromExplicit) return fromExplicit
45
+
46
+ const fromConfig = tryTlsRoot(getCliConfigTlsDir())
47
+ if (fromConfig) return fromConfig
48
+
49
+ const home = defaultCertificatesDir()
50
+ if (isTlsFlatBundle(home)) return { kind: 'flat', root: home }
51
+ if (isTlsTreeRoot(home)) return { kind: 'tree', root: home }
52
+ return null
53
+ }
54
+
55
+ const FLAT_FILES = [
56
+ ['ca.crt', ['root/ca.crt', 'ca.crt']],
57
+ ['mongodb.pem', ['services/mongodb/mongodb.pem', 'mongodb.pem']],
58
+ ['mongodb.crt', ['services/mongodb/mongodb.crt', 'mongodb.crt']],
59
+ ['redis.pem', ['services/redis/redis.pem', 'redis.pem']],
60
+ ['redis.crt', ['services/redis/redis.crt', 'redis.crt']],
61
+ ['kafka.crt', ['services/kafka/kafka.crt', 'kafka.crt']],
62
+ ['truststore.jks', ['services/kafka/truststore.jks', 'truststore.jks']],
63
+ ]
64
+
65
+ function resolveSourcePath(source, relPaths) {
66
+ for (const rel of relPaths) {
67
+ const p = path.join(source.root, rel)
68
+ if (fs.existsSync(p)) return p
69
+ }
70
+ return null
71
+ }
72
+
73
+ function bundleIsFreshAtDest(dest, source) {
74
+ const caSrc = resolveSourcePath(source, FLAT_FILES[0][1])
75
+ const caDest = path.join(dest, 'ca.crt')
76
+ if (!caSrc || !fs.existsSync(caDest)) return false
77
+ try {
78
+ if (fs.statSync(caDest).mtimeMs < fs.statSync(caSrc).mtimeMs) return false
79
+ } catch {
80
+ return false
81
+ }
82
+ for (const [destName, srcRels] of FLAT_FILES.slice(1)) {
83
+ const src = resolveSourcePath(source, srcRels)
84
+ if (!src) continue
85
+ const destFile = path.join(dest, destName)
86
+ if (!fs.existsSync(destFile)) return false
87
+ try {
88
+ if (fs.statSync(destFile).mtimeMs < fs.statSync(src).mtimeMs) return false
89
+ } catch {
90
+ return false
91
+ }
92
+ }
93
+ return true
94
+ }
95
+
96
+ export function syncTlsBundleFast(dest, source) {
97
+ fs.mkdirSync(dest, { recursive: true })
98
+ for (const [destName, srcRels] of FLAT_FILES) {
99
+ const src = resolveSourcePath(source, srcRels)
100
+ if (!src) continue
101
+ fs.copyFileSync(src, path.join(dest, destName))
102
+ }
103
+ }
104
+
105
+ export function needsTlsDestRefresh(dests, source) {
106
+ return dests.some((dest) => !bundleIsFreshAtDest(dest, source))
107
+ }
108
+
109
+ export const K8S_TLS_MOUNT = '/etc/tls/infra'
@@ -0,0 +1,16 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const BUNDLED_SCRIPT = path.join(
6
+ path.dirname(fileURLToPath(import.meta.url)),
7
+ '..',
8
+ 'scripts',
9
+ 'telepresence-client-install.sh',
10
+ )
11
+
12
+ export function resolveTelepresenceInstallScript() {
13
+ const resolved = path.resolve(BUNDLED_SCRIPT)
14
+ if (fs.existsSync(resolved)) return resolved
15
+ return null
16
+ }
@@ -12,9 +12,9 @@ TELEPRESENCE_INTERCEPT_HEADER=x-intercept-who
12
12
  # TELEPRESENCE_DEV_ID=your-id
13
13
  `
14
14
 
15
- const SERVICE_TELEPRESENCE_ENV = `# Auto-scaffolded for local intercept (xry tp intercept --ns dev)
15
+ /** Gitignored — Telepresence overwrites with cluster pod env on intercept; not hand-maintained dev .env */
16
+ const SERVICE_TELEPRESENCE_ENV = `# Scaffold only until first intercept — then Telepresence fills from cluster
16
17
  NS=dev
17
- NODE_ENV=dev
18
18
  TELEPRESENCE_INTERCEPT_HEADER=x-intercept-who
19
19
  `
20
20
 
@@ -28,6 +28,22 @@ export function writeWorkspaceTelepresenceFiles(workspaceRoot) {
28
28
  }
29
29
 
30
30
  export const SERVICE_TELEPRESENCE_ENV_REL = path.join('x', 'environments', '.env.telepresence')
31
+ export const SERVICE_LOCAL_ENV_REL = path.join('x', 'environments', '.env.local')
32
+
33
+ const SERVICE_LOCAL_ENV_SCAFFOLD = `# Local-only overrides (gitignored) — BM hosts, feature flags, extra keys
34
+ # Loaded after .env.telepresence on xry dev / start (laptop only)
35
+ `
36
+
37
+ export function ensureServiceLocalEnv(serviceRoot) {
38
+ const root = path.resolve(serviceRoot)
39
+ const envPath = path.join(root, SERVICE_LOCAL_ENV_REL)
40
+ fs.mkdirSync(path.dirname(envPath), { recursive: true })
41
+ const created = !fs.existsSync(envPath)
42
+ if (created) {
43
+ fs.writeFileSync(envPath, SERVICE_LOCAL_ENV_SCAFFOLD)
44
+ }
45
+ return { envPath, envRel: SERVICE_LOCAL_ENV_REL, created }
46
+ }
31
47
 
32
48
  export function ensureServiceTelepresenceEnv(serviceRoot) {
33
49
  const root = path.resolve(serviceRoot)
@@ -40,6 +56,13 @@ export function ensureServiceTelepresenceEnv(serviceRoot) {
40
56
  return { envPath, envRel: SERVICE_TELEPRESENCE_ENV_REL, created }
41
57
  }
42
58
 
59
+ /** Telepresence + `.env.local` only under x/environments (all gitignored). */
60
+ export function ensureServiceLaptopEnvs(serviceRoot) {
61
+ const telepresence = ensureServiceTelepresenceEnv(serviceRoot)
62
+ const local = ensureServiceLocalEnv(serviceRoot)
63
+ return { telepresence, local }
64
+ }
65
+
43
66
  /** Deploy name (configs.service.name) → workspace api folder name */
44
67
  export const TELEPRESENCE_DEPLOYMENTS = Object.freeze([
45
68
  'general',
@@ -3,8 +3,14 @@ import fs from 'node:fs'
3
3
  import os from 'node:os'
4
4
  import path from 'node:path'
5
5
 
6
- import { listInfraRootCandidates } from './resolve-infra-helper.mjs'
7
- import { getCliConfigInfraDir } from './xrystal-config.mjs'
6
+ import { ensureServiceLocalEnv, ensureServiceTelepresenceEnv } from './telepresence-layout.mjs'
7
+ import {
8
+ cleanupTelepresenceEnvFiles,
9
+ rewriteTelepresenceEnvFileInPlace,
10
+ } from './telepresence-tls-path-rewrite.mjs'
11
+ import { defaultCertificatesDir } from './resolve-tls-bundle.mjs'
12
+ import { getCliConfigKubeconfig } from './xrystal-config.mjs'
13
+ import { resolveUserHome } from './xrystal-registry.mjs'
8
14
  import { findWorkspaceRoot, resolveWorkspaceOuterTmp } from './workspace-resolve.mjs'
9
15
 
10
16
  const ALLOWED_NS = new Set(['dev', 'test'])
@@ -32,7 +38,7 @@ function parseKubeconfigLine(tmpPath) {
32
38
  return expandHome(value)
33
39
  }
34
40
 
35
- /** Laptop kubeconfig — no ansible-var; optional infra data/k3s path only as file fallback. */
41
+ /** Laptop kubeconfig — env / workspace tmp / ~/.xrystal config / ~/.kube only. */
36
42
  export function resolveKubeconfig(cwd = process.cwd()) {
37
43
  const fromEnv = process.env.KUBECONFIG
38
44
  if (fromEnv) {
@@ -51,16 +57,17 @@ export function resolveKubeconfig(cwd = process.cwd()) {
51
57
  }
52
58
  }
53
59
 
54
- const configuredInfra = getCliConfigInfraDir()
55
- if (configuredInfra) {
56
- const candidate = path.join(configuredInfra, 'data', 'k3s', 'cluster.kubeconfig')
57
- if (fs.existsSync(candidate)) return candidate
60
+ const fromEnvPath = process.env.XRY_KUBECONFIG
61
+ if (fromEnvPath) {
62
+ const candidate = expandHome(fromEnvPath)
63
+ if (candidate && fs.existsSync(candidate)) return candidate
58
64
  }
59
65
 
60
- for (const root of listInfraRootCandidates(cwd)) {
61
- const candidate = path.join(root, 'data', 'k3s', 'cluster.kubeconfig')
62
- if (fs.existsSync(candidate)) return candidate
63
- }
66
+ const fromConfig = getCliConfigKubeconfig()
67
+ if (fromConfig && fs.existsSync(fromConfig)) return fromConfig
68
+
69
+ const xrystalKube = path.join(resolveUserHome(), 'kubeconfig')
70
+ if (fs.existsSync(xrystalKube)) return xrystalKube
64
71
 
65
72
  const defaultPath = path.join(os.homedir(), '.kube', 'config')
66
73
  if (fs.existsSync(defaultPath)) return defaultPath
@@ -138,7 +145,7 @@ export function connectTelepresence({
138
145
  const kubeconfig = resolveKubeconfig(cwd)
139
146
  if (!kubeconfig) {
140
147
  throw new Error(
141
- 'Kubeconfig not found — set KUBECONFIG, workspace tmp kubeconfig:, make kubeconfig-sync, or ~/.kube/config',
148
+ 'Kubeconfig not found — set KUBECONFIG, workspace tmp kubeconfig:, xry config kubeconfig, or ~/.kube/config',
142
149
  )
143
150
  }
144
151
  resetDaemonIfExecutableMismatch()
@@ -154,7 +161,32 @@ export function connectTelepresence({
154
161
  return result.status ?? 1
155
162
  }
156
163
 
157
- export function quitTelepresence() {
164
+ /** Drop one intercept; keeps telepresence connect when possible. */
165
+ export function detachInterceptWorkload({ deploy, ns } = {}) {
166
+ const name = String(deploy ?? '').trim()
167
+ const namespace = String(ns ?? '').trim()
168
+ if (!name || !namespace) return
169
+ ensureTelepresenceOnPath()
170
+ try {
171
+ execSync(`telepresence leave ${name} --namespace ${namespace}`, {
172
+ stdio: 'ignore',
173
+ shell: true,
174
+ })
175
+ return
176
+ } catch {
177
+ /* fall through */
178
+ }
179
+ try {
180
+ execSync(`telepresence detach "${name}" --namespace "${namespace}"`, {
181
+ stdio: 'ignore',
182
+ shell: true,
183
+ })
184
+ } catch {
185
+ /* ignore */
186
+ }
187
+ }
188
+
189
+ export function detachAllIntercepts() {
158
190
  ensureTelepresenceOnPath()
159
191
  try {
160
192
  const json = execSync('telepresence list --output json 2>/dev/null', {
@@ -172,18 +204,16 @@ export function quitTelepresence() {
172
204
  const name = it?.name || it?.workload
173
205
  const itemNs = it?.namespace || 'dev'
174
206
  if (!name) continue
175
- try {
176
- execSync(`telepresence detach "${name}" --namespace "${itemNs}"`, {
177
- stdio: 'ignore',
178
- shell: true,
179
- })
180
- } catch {
181
- /* ignore */
182
- }
207
+ detachInterceptWorkload({ deploy: name, ns: itemNs })
183
208
  }
184
209
  } catch {
185
210
  /* no active intercepts */
186
211
  }
212
+ }
213
+
214
+ export function quitTelepresence({ cwd = process.cwd() } = {}) {
215
+ ensureTelepresenceOnPath()
216
+ detachAllIntercepts()
187
217
  try {
188
218
  execSync('telepresence quit -s', { stdio: 'ignore', shell: true })
189
219
  } catch {
@@ -193,63 +223,80 @@ export function quitTelepresence() {
193
223
  /* ignore */
194
224
  }
195
225
  }
226
+ const serviceRoot = path.resolve(cwd)
227
+ const envDir = path.join(serviceRoot, 'x', 'environments')
228
+ finishInterceptEnvSession({ envDir, serviceRoot })
196
229
  console.log('Telepresence stopped.')
197
230
  }
198
231
 
199
- function resolveCertificatesRoot(cwd) {
200
- if (process.env.TELEPRESENCE_CERT_ROOT) {
201
- const root = expandHome(process.env.TELEPRESENCE_CERT_ROOT)
202
- if (fs.existsSync(root)) return root
232
+ /** End intercept session: detach workload, remove cluster env snapshot, restore scaffold. */
233
+ export function leaveTelepresenceIntercept({ deploy, ns = 'dev', cwd = process.cwd() } = {}) {
234
+ assertNamespaceAllowed(ns)
235
+ const serviceRoot = path.resolve(cwd)
236
+ const envDir = path.join(serviceRoot, 'x', 'environments')
237
+ finishInterceptEnvSession({ envDir, serviceRoot, deploy, ns })
238
+ console.log(`Intercept ended (${deploy}, ns=${ns}). Cluster connect may still be active — use xry tp stop to quit.`)
239
+ }
240
+
241
+ function finishInterceptEnvSession({ envDir, serviceRoot, deploy, ns }) {
242
+ if (deploy && ns) {
243
+ detachInterceptWorkload({ deploy, ns })
203
244
  }
204
- const configuredInfra = getCliConfigInfraDir()
205
- if (configuredInfra) {
206
- const candidate = path.join(configuredInfra, 'data', 'certificates')
207
- if (fs.existsSync(candidate)) return candidate
245
+ if (fs.existsSync(envDir)) {
246
+ cleanupTelepresenceEnvFiles(envDir)
208
247
  }
209
- for (const root of listInfraRootCandidates(cwd)) {
210
- const candidate = path.join(root, 'data', 'certificates')
211
- if (fs.existsSync(candidate)) return candidate
248
+ if (serviceRoot) {
249
+ ensureServiceTelepresenceEnv(serviceRoot)
212
250
  }
213
- return null
214
251
  }
215
252
 
216
- function syncTlsForLocalIntercept(cwd) {
217
- const certRoot = resolveCertificatesRoot(cwd)
218
- if (!certRoot) {
219
- console.error('Skipping local TLS sync (set TELEPRESENCE_CERT_ROOT or xry config infra for make tls-copy-from-host)')
220
- return
253
+ function runInterceptSession({ envDir, serviceRoot, deploy, ns, run }) {
254
+ let status = 1
255
+ try {
256
+ status = run()
257
+ } finally {
258
+ finishInterceptEnvSession({ envDir, serviceRoot, deploy, ns })
221
259
  }
222
- const services = path.join(certRoot, 'services')
223
- const rootCa = path.join(certRoot, 'root')
224
- if (!fs.existsSync(rootCa) || !fs.existsSync(services)) {
225
- console.error(`Missing ${certRoot} — run: make tls-copy-from-host (infra repo)`)
226
- process.exit(1)
260
+ return status
261
+ }
262
+
263
+ export function runTelepresenceEnvRewrite(envFilePath) {
264
+ const abs = path.resolve(envFilePath)
265
+ const updated = rewriteTelepresenceEnvFileInPlace(abs)
266
+ if (updated) {
267
+ console.log(`Rewrote TLS paths in ${abs} → ${defaultCertificatesDir()}`)
227
268
  }
228
- const dest = process.env.TELEPRESENCE_TLS_DIR || '/etc/tls/infra'
229
- if (!fs.existsSync(dest)) {
230
- console.error(`Ensuring ${dest} (may ask sudo once)...`)
231
- execSync(`sudo mkdir -p "${dest}" && sudo chown "$(id -u):$(id -g)" "${dest}" && chmod 755 "${dest}"`, {
232
- shell: true,
233
- stdio: 'inherit',
234
- })
269
+ ensureServiceLocalEnvAfterIntercept(abs)
270
+ return updated
271
+ }
272
+
273
+ function ensureServiceLocalEnvAfterIntercept(envFilePath) {
274
+ if (!fs.existsSync(envFilePath)) return
275
+ const text = fs.readFileSync(envFilePath, 'utf8')
276
+ const assignmentLines = text.split(/\r?\n/).filter((line) => {
277
+ const t = line.trim()
278
+ return t && !t.startsWith('#') && t.includes('=')
279
+ })
280
+ if (assignmentLines.length < 3) return
281
+ const serviceRoot = path.resolve(path.dirname(envFilePath), '..', '..')
282
+ ensureServiceLocalEnv(serviceRoot)
283
+ }
284
+
285
+ function shellQuote(arg) {
286
+ const s = String(arg)
287
+ if (process.platform === 'win32') {
288
+ return `"${s.replace(/"/g, '\\"')}"`
235
289
  }
236
- const copy = (destName, src) => {
237
- if (!fs.existsSync(src)) {
238
- console.error(`Missing: ${src} — run: make tls-copy-from-host`)
239
- process.exit(1)
240
- }
241
- fs.copyFileSync(src, path.join(dest, destName))
242
- console.log(` ${path.join(dest, destName)} ← ${src}`)
290
+ return `'${s.replace(/'/g, `'\\''`)}'`
291
+ }
292
+
293
+ function buildInterceptLocalInvocation(cliName, absEnvFile, localCmd) {
294
+ const rewrite = `${cliName} tp rewrite-env ${shellQuote(absEnvFile)}`
295
+ const child = localCmd.map(shellQuote).join(' ')
296
+ if (process.platform === 'win32') {
297
+ return { file: 'cmd.exe', args: ['/d', '/s', '/c', `${rewrite} && ${child}`] }
243
298
  }
244
- console.log(`TLS from ${certRoot} → ${dest}`)
245
- copy('ca.crt', path.join(rootCa, 'ca.crt'))
246
- copy('mongodb.pem', path.join(services, 'mongodb', 'mongodb.pem'))
247
- copy('mongodb.crt', path.join(services, 'mongodb', 'mongodb.crt'))
248
- copy('redis.pem', path.join(services, 'redis', 'redis.pem'))
249
- copy('redis.crt', path.join(services, 'redis', 'redis.crt'))
250
- copy('kafka.crt', path.join(services, 'kafka', 'kafka.crt'))
251
- copy('truststore.jks', path.join(services, 'kafka', 'truststore.jks'))
252
- console.log(`TLS ready at ${dest}`)
299
+ return { file: 'sh', args: ['-c', `${rewrite} && exec ${child}`] }
253
300
  }
254
301
 
255
302
  function preflightReadyDeployment({ deploy, ns, cwd }) {
@@ -295,6 +342,7 @@ export function runTelepresenceIntercept({
295
342
  envFile,
296
343
  localCmd,
297
344
  cwd = process.cwd(),
345
+ cliName = process.env.XRY_CLI_NAME || 'xry',
298
346
  }) {
299
347
  assertNamespaceAllowed(ns)
300
348
  ensureTelepresenceOnPath()
@@ -311,7 +359,6 @@ export function runTelepresenceIntercept({
311
359
  }
312
360
 
313
361
  preflightReadyDeployment({ deploy, ns, cwd })
314
- syncTlsForLocalIntercept(cwd)
315
362
 
316
363
  const rawId = process.env.TELEPRESENCE_DEV_ID || process.env.USER || 'dev'
317
364
  const devId = process.env.TELEPRESENCE_DEV_ID ? rawId : rawId.replace(/\./g, '-')
@@ -339,11 +386,30 @@ export function runTelepresenceIntercept({
339
386
  absEnvFile,
340
387
  ]
341
388
 
342
- if (localCmd?.length) {
343
- const result = spawnSync('telepresence', [...tpArgs, '--', ...localCmd], { stdio: 'inherit', cwd, env: process.env })
344
- process.exit(result.status ?? 1)
345
- }
389
+ const envDir = path.dirname(absEnvFile)
390
+ const serviceRoot = path.resolve(cwd)
391
+
392
+ const status = runInterceptSession({
393
+ envDir,
394
+ serviceRoot,
395
+ deploy,
396
+ ns,
397
+ run: () => {
398
+ if (localCmd?.length) {
399
+ const wrap = buildInterceptLocalInvocation(cliName, absEnvFile, localCmd)
400
+ const result = spawnSync(
401
+ 'telepresence',
402
+ [...tpArgs, '--', wrap.file, ...wrap.args],
403
+ { stdio: 'inherit', cwd, env: process.env },
404
+ )
405
+ if (result.signal) return result.signal === 'SIGINT' ? 130 : 143
406
+ return result.status ?? 1
407
+ }
408
+ const result = spawnSync('telepresence', tpArgs, { stdio: 'inherit', cwd, env: process.env })
409
+ if (result.signal) return result.signal === 'SIGINT' ? 130 : 143
410
+ return result.status ?? 1
411
+ },
412
+ })
346
413
 
347
- const result = spawnSync('telepresence', tpArgs, { stdio: 'inherit', cwd, env: process.env })
348
- process.exit(result.status ?? 1)
414
+ process.exit(status)
349
415
  }
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ import { defaultCertificatesDir, isTlsFlatBundle, K8S_TLS_MOUNT } from './resolve-tls-bundle.mjs'
5
+
6
+ /** Retired sidecar — removed after in-place rewrite. */
7
+ export const TELEPRESENCE_PATHS_ENV = '.env.telepresence.paths'
8
+
9
+ const PEM_FILE_RE = /\/etc\/tls\/infra\/([A-Za-z0-9._-]+)/g
10
+
11
+ function localPemPath(fileName) {
12
+ return path.join(defaultCertificatesDir(), fileName).split(path.sep).join('/')
13
+ }
14
+
15
+ function pemExistsInHome(fileName) {
16
+ return fs.existsSync(path.join(defaultCertificatesDir(), fileName))
17
+ }
18
+
19
+ export function rewriteClusterTlsPathsInValue(value) {
20
+ const raw = String(value ?? '')
21
+ if (!raw.includes(K8S_TLS_MOUNT)) return raw
22
+ return raw.replace(PEM_FILE_RE, (match, file) => {
23
+ if (!pemExistsInHome(file)) return match
24
+ return localPemPath(file)
25
+ })
26
+ }
27
+
28
+ function rewriteLine(line) {
29
+ if (!line.includes(K8S_TLS_MOUNT)) return line
30
+ return rewriteClusterTlsPathsInValue(line)
31
+ }
32
+
33
+ export function removeLegacyTlsEnvSidecar(envDir) {
34
+ const legacy = path.join(path.resolve(envDir), TELEPRESENCE_PATHS_ENV)
35
+ if (fs.existsSync(legacy)) fs.unlinkSync(legacy)
36
+ }
37
+
38
+ /**
39
+ * Rewrite `/etc/tls/infra/<file>` → `~/.xrystal/certificates/<file>` in place when PEM exists (flat SoT).
40
+ * @returns {boolean} whether file was updated
41
+ */
42
+ export function rewriteTelepresenceEnvFileInPlace(envFilePath) {
43
+ const envPath = path.resolve(envFilePath)
44
+ if (!fs.existsSync(envPath)) return false
45
+
46
+ const certHome = defaultCertificatesDir()
47
+ if (!isTlsFlatBundle(certHome)) return false
48
+
49
+ const original = fs.readFileSync(envPath, 'utf8')
50
+ const next = original
51
+ .split(/\r?\n/)
52
+ .map((line) => rewriteLine(line))
53
+ .join('\n')
54
+
55
+ if (next === original) return false
56
+
57
+ fs.writeFileSync(envPath, next.endsWith('\n') ? next : `${next}\n`)
58
+ removeLegacyTlsEnvSidecar(path.dirname(envPath))
59
+ return true
60
+ }
61
+
62
+ /** After intercept ends — remove cluster snapshot + legacy sidecar. */
63
+ export function cleanupTelepresenceEnvFiles(envDir) {
64
+ const dir = path.resolve(envDir)
65
+ removeLegacyTlsEnvSidecar(dir)
66
+ const tpEnv = path.join(dir, '.env.telepresence')
67
+ if (fs.existsSync(tpEnv)) fs.unlinkSync(tpEnv)
68
+ }
69
+
@@ -24,7 +24,10 @@ export function scaffoldWorkspace(targetPath, projectName, {
24
24
 
25
25
  fs.writeFileSync(tmpPath, workspaceTmpTemplate(projectName))
26
26
  ensureTmpSchemaVersion(tmpPath)
27
- fs.writeFileSync(path.join(resolved, '.gitignore'), '.env.telepresence\n.env.local\n.env.private\nnode_modules/\n')
27
+ fs.writeFileSync(
28
+ path.join(resolved, '.gitignore'),
29
+ '.env.telepresence\n.env.telepresence.paths\n.env.local\n.env.private\nnode_modules/\n',
30
+ )
28
31
 
29
32
  writeWorkspaceTelepresenceFiles(resolved)
30
33
 
@@ -31,10 +31,12 @@ export function readXrystalConfig() {
31
31
  export function writeXrystalConfig(next) {
32
32
  ensureUserHome()
33
33
  const current = readXrystalConfig()
34
+ const { infraDir: _legacyInfra, ...cliBase } = current.cli ?? {}
35
+ const { infraDir: _dropInfra, ...cliNext } = next.cli ?? {}
34
36
  const merged = {
35
37
  version: CONFIG_VERSION,
36
38
  updatedAt: new Date().toISOString(),
37
- cli: { ...current.cli, ...(next.cli ?? {}) },
39
+ cli: { ...cliBase, ...cliNext },
38
40
  }
39
41
  fs.writeFileSync(configFilePath(), `${JSON.stringify(merged, null, 2)}\n`)
40
42
  return merged
@@ -52,28 +54,68 @@ export function setCliConfigLang(lang) {
52
54
  return normalized
53
55
  }
54
56
 
55
- export function getCliConfigInfraDir() {
56
- const infraDir = readXrystalConfig().cli?.infraDir
57
- if (!infraDir || typeof infraDir !== 'string') return null
58
- const trimmed = infraDir.trim()
57
+ function readCliPathKey(key) {
58
+ const value = readXrystalConfig().cli?.[key]
59
+ if (!value || typeof value !== 'string') return null
60
+ const trimmed = value.trim()
59
61
  return trimmed || null
60
62
  }
61
63
 
62
- export function setCliConfigInfraDir(infraDir) {
63
- const resolved = path.resolve(String(infraDir ?? '').trim())
64
+ export function getCliConfigTlsDir() {
65
+ return readCliPathKey('tlsDir')
66
+ }
67
+
68
+ export function getCliConfigKubeconfig() {
69
+ return readCliPathKey('kubeconfig')
70
+ }
71
+
72
+ export function getCliConfigSyncTlsFrom() {
73
+ return readCliPathKey('syncTlsFrom')
74
+ }
75
+
76
+ export function getCliConfigSyncKubeconfigFrom() {
77
+ return readCliPathKey('syncKubeconfigFrom')
78
+ }
79
+
80
+ export function setCliConfigSyncTlsFrom(syncTlsFrom) {
81
+ const resolved = path.resolve(String(syncTlsFrom ?? '').trim())
82
+ writeXrystalConfig({ cli: { syncTlsFrom: resolved } })
83
+ return resolved
84
+ }
85
+
86
+ export function setCliConfigSyncKubeconfigFrom(syncKubeconfigFrom) {
87
+ const resolved = path.resolve(String(syncKubeconfigFrom ?? '').trim())
88
+ writeXrystalConfig({ cli: { syncKubeconfigFrom: resolved } })
89
+ return resolved
90
+ }
91
+
92
+ export function setCliConfigTlsDir(tlsDir) {
93
+ const resolved = path.resolve(String(tlsDir ?? '').trim())
64
94
  if (!fs.existsSync(resolved)) {
65
- throw new Error(`Infra directory not found: ${resolved}`)
95
+ throw new Error(`TLS directory not found: ${resolved}`)
66
96
  }
67
- if (!fs.existsSync(path.join(resolved, 'scripts', 'helpers'))) {
68
- throw new Error(`Not an -infrastructure- repo (missing scripts/helpers): ${resolved}`)
97
+ writeXrystalConfig({ cli: { tlsDir: resolved } })
98
+ return resolved
99
+ }
100
+
101
+ export function setCliConfigKubeconfig(kubeconfigPath) {
102
+ const resolved = path.resolve(String(kubeconfigPath ?? '').trim())
103
+ if (!fs.existsSync(resolved)) {
104
+ throw new Error(`Kubeconfig not found: ${resolved}`)
69
105
  }
70
- writeXrystalConfig({ cli: { infraDir: resolved } })
106
+ writeXrystalConfig({ cli: { kubeconfig: resolved } })
71
107
  return resolved
72
108
  }
73
109
 
74
- export function clearCliConfigInfraDir() {
110
+ export function clearCliConfigTlsDir() {
111
+ const current = readXrystalConfig()
112
+ const { tlsDir: _removed, ...rest } = current.cli ?? {}
113
+ writeXrystalConfig({ cli: rest })
114
+ }
115
+
116
+ export function clearCliConfigKubeconfig() {
75
117
  const current = readXrystalConfig()
76
- const { infraDir: _removed, ...rest } = current.cli ?? {}
118
+ const { kubeconfig: _removed, ...rest } = current.cli ?? {}
77
119
  writeXrystalConfig({ cli: rest })
78
120
  }
79
121