aegiscode 7.0.14 → 7.0.16
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/SOURCE-OFFER.txt +9 -0
- package/package.json +4 -7
- package/scripts/check.mjs +1 -52
- package/scripts/demo.mjs +1 -94
- package/scripts/predist.mjs +1 -75
- package/scripts/runtests.mjs +1 -56
- package/scripts/seal-gate.mjs +1 -74
- package/src/agents.js +1 -139
- package/src/app.js +1 -2932
- package/src/art.js +1 -289
- package/src/chatflow.js +1 -3020
- package/src/checkpoint.js +1 -90
- package/src/clipboard.js +1 -424
- package/src/cloudsync.js +1 -528
- package/src/commands.js +1 -4003
- package/src/config.js +1 -581
- package/src/connect.js +1 -349
- package/src/credentials.js +1 -33
- package/src/deps.js +1 -232
- package/src/devrun.js +1 -187
- package/src/diff.js +1 -333
- package/src/diffview.js +1 -296
- package/src/engine.js +1 -297
- package/src/entitlement.js +1 -355
- package/src/events.js +1 -707
- package/src/export.js +1 -67
- package/src/fingerprint.js +1 -592
- package/src/format.js +1 -259
- package/src/fuzzy.js +1 -119
- package/src/history.js +1 -401
- package/src/init.js +1 -175
- package/src/input.js +1 -139
- package/src/keys.js +1 -183
- package/src/markdown.js +1 -306
- package/src/models.js +1 -487
- package/src/naming.js +1 -229
- package/src/overlays.js +1 -461
- package/src/panels.js +1 -1418
- package/src/ping.js +1 -226
- package/src/presence.js +1 -238
- package/src/render.js +1 -515
- package/src/screen.js +1 -518
- package/src/screens.js +1 -896
- package/src/secret.js +1 -59
- package/src/securefs.js +1 -359
- package/src/settings.js +1 -155
- package/src/shared.js +1 -52
- package/src/sharedpaths.js +1 -53
- package/src/signup.js +1 -156
- package/src/summarize.js +1 -95
- package/src/sysdiag.js +1 -585
- package/src/system.js +1 -40
- package/src/theme.js +1 -570
- package/src/title.js +1 -220
- package/src/todos.js +1 -115
- package/src/tokens.js +1 -263
- package/src/topup.js +1 -210
- package/src/update.js +1 -181
- package/vendor/client/aegis.js +1 -2179
- package/vendor/client/attest.js +1 -442
- package/vendor/client/authorship-key.js +1 -410
- package/vendor/client/auto-provision.js +1 -134
- package/vendor/client/brain-catalog.js +1 -268
- package/vendor/client/byok-catalog.js +1 -230
- package/vendor/client/credentials.js +1 -494
- package/vendor/client/device-fingerprint.js +1 -141
- package/vendor/client/drive-connect.js +1 -110
- package/vendor/client/drive-upload.js +1 -174
- package/vendor/client/env-file.js +1 -1273
- package/vendor/client/fingerprint.js +1 -1064
- package/vendor/client/foreign-memory.js +1 -669
- package/vendor/client/google-signin.js +1 -133
- package/vendor/client/hooks.js +1 -430
- package/vendor/client/model-discovery.js +1 -373
- package/vendor/client/platform.js +1 -937
- package/vendor/client/prefs.js +1 -351
- package/vendor/client/presence-constants.js +1 -107
- package/vendor/client/presence.js +1 -438
- package/vendor/client/record-vault.js +3 -1055
- package/vendor/client/session-store.js +1 -548
- package/vendor/client/topup.js +1 -297
- package/vendor/client/touch.js +1 -458
- package/vendor/client/update.js +1 -704
- package/vendor/client/user-models.js +1 -381
- package/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/desktop/lib/local/claude-pro.js +1 -993
- package/vendor/desktop/lib/local/context.js +1 -95
- package/vendor/desktop/lib/local/engine.js +1 -3301
- package/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/desktop/lib/local/local.js +1 -2135
- package/vendor/desktop/lib/local/prompt.js +1 -275
- package/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/desktop/lib/local/session-rounds.js +1 -208
- package/vendor/desktop/lib/local/shell.js +1 -680
- package/vendor/desktop/lib/local/tools.js +1 -1238
- package/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/desktop/lib/settings.js +1 -890
- package/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/hosts/install.js +1 -638
- package/vendor/hosts/openai-shim.js +1 -515
- package/vendor/hosts/spec.js +1 -164
- package/vendor/hosts/targets.js +1 -346
- package/vendor/mcp/server.js +1 -221
- package/vendor/mcp/tools.js +1 -408
- package/vendor/one/src/child.js +1 -285
- package/vendor/one/src/permissions.js +1 -369
|
@@ -1,1275 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
// AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* The shared `~/.aegiscode/.env` store — the one file holding every key this
|
|
10
|
-
* product family can use, for every host:
|
|
11
|
-
*
|
|
12
|
-
* AEGIS_API_KEY=aegis_…
|
|
13
|
-
* OPENAI_API_KEY=sk-…
|
|
14
|
-
* DEEPSEEK_API_KEY=sk-…
|
|
15
|
-
*
|
|
16
|
-
* Before this module each host read `process.env` only, which meant a key was
|
|
17
|
-
* configured if — and only if — the user had exported it in the shell that
|
|
18
|
-
* happened to launch the app. That is why the byok flow needed a separate
|
|
19
|
-
* `/byok-key <provider>` step and an encrypted per-provider store: the file was
|
|
20
|
-
* never read. Reading it into `process.env` at startup makes the instruction
|
|
21
|
-
* the same in the CLI and the desktop — "put it in ~/.aegiscode/.env" — and it
|
|
22
|
-
* needs no other change in either, because `AEGIS_API_KEY` is already the FIRST
|
|
23
|
-
* entry in `client/credentials.js`'s documented resolution order.
|
|
24
|
-
*
|
|
25
|
-
* READING still obeys two rules this module started with:
|
|
26
|
-
*
|
|
27
|
-
* 1. A variable already present in the environment is never overwritten. The
|
|
28
|
-
* file is a convenience for the common case, not a way for a stale file to
|
|
29
|
-
* shadow an explicit `AEGIS_API_KEY=… aegiscode` in CI.
|
|
30
|
-
* 2. A load never rewrites anything. If the file the user made is readable by
|
|
31
|
-
* other accounts we say so rather than fixing it silently.
|
|
32
|
-
*
|
|
33
|
-
* WRITING was added later, because the file being read-only was the reason the
|
|
34
|
-
* key a user typed at the model picker did not survive the session: the only
|
|
35
|
-
* place a host could put it was its own encrypted store, so the CLI and the
|
|
36
|
-
* desktop each held a private key for the same provider and the user had to
|
|
37
|
-
* enter it twice. The demand is one key, entered once at the model picker,
|
|
38
|
-
* stored where BOTH hosts already look. So `setEnvValue` is the single writer:
|
|
39
|
-
*
|
|
40
|
-
* - the variable name is validated (`/^[A-Za-z_][A-Za-z0-9_]*$/`) and the
|
|
41
|
-
* value may not contain a newline, so a key can never inject a second line
|
|
42
|
-
* (or an unrelated variable) into a file every host sources at start-up;
|
|
43
|
-
* - an existing line with the same name is REPLACED in place — including its
|
|
44
|
-
* `export ` prefix, which is preserved — so comments, ordering and every
|
|
45
|
-
* other key in the file survive untouched, and a hand-written file is not
|
|
46
|
-
* reformatted;
|
|
47
|
-
* - duplicate definitions of the same name are collapsed to the one that was
|
|
48
|
-
* just written. Two `OPENAI_API_KEY=` lines is the "which one won?" bug,
|
|
49
|
-
* and the answer would otherwise depend on the reader's merge order;
|
|
50
|
-
* - the file is created 0600 and written through a same-directory temp file
|
|
51
|
-
* + rename, so a crash mid-write cannot leave a half-written key file, and
|
|
52
|
-
* a write never widens permissions on a file that was already tighter. A
|
|
53
|
-
* file that WAS group/world-readable is tightened, and the caller is told
|
|
54
|
-
* (`tightened: true`) rather than the change going unmentioned;
|
|
55
|
-
* - the value is applied to `process.env` as well, so the selection that
|
|
56
|
-
* triggered the write runs on the key it just stored;
|
|
57
|
-
* - the value is never returned, logged or echoed by anything in here.
|
|
58
|
-
*
|
|
59
|
-
* THE SECOND FILE — `~/.aegiscode/secrets.env`, and why the split exists.
|
|
60
|
-
*
|
|
61
|
-
* One file for every key the family can use was right while the keys were all
|
|
62
|
-
* HOST credentials: a provider key or the account key is read by the CLI, the
|
|
63
|
-
* desktop and the MCP plugin, so one file is what makes "enter the key once"
|
|
64
|
-
* true. It was never right for the variables that are not host credentials at
|
|
65
|
-
* all — `STRIPE_SECRET_KEY` (the billing rail of the aegis1/server product),
|
|
66
|
-
* `PYPI_API_TOKEN`, `CLAUDE_CODE_OAUTH_TOKEN` — which had been poured into the
|
|
67
|
-
* same file by hand. Those are loaded into `process.env` by every host at
|
|
68
|
-
* start-up, so they were inherited by every child process and visible to any
|
|
69
|
-
* account that can read `/proc/<pid>/environ`, for a key no host ever reads.
|
|
70
|
-
* That is exposure with no function behind it.
|
|
71
|
-
*
|
|
72
|
-
* The split keeps the sharing that matters and removes the sharing that does
|
|
73
|
-
* not:
|
|
74
|
-
*
|
|
75
|
-
* - `.env` still holds every host credential, still loaded by every host,
|
|
76
|
-
* still written by `setEnvValue`, still the answer to "where do I put my
|
|
77
|
-
* API key". Nothing about that changed.
|
|
78
|
-
* - `secrets.env` holds the foreign production secrets. It is NOT read at
|
|
79
|
-
* host start-up. `loadForeignSecrets()` reads it explicitly, for the one
|
|
80
|
-
* process that genuinely needs a billing token, so the value is available
|
|
81
|
-
* without being ambient. `setEnvValue` refuses to write a foreign name at
|
|
82
|
-
* all (see FOREIGN_SECRET_NAMES below), so the file cannot silently
|
|
83
|
-
* re-acquire one.
|
|
84
|
-
* - `splitForeignSecrets()` performs the migration: it moves the foreign
|
|
85
|
-
* names out of `.env` into `secrets.env` (0600), preserving comments,
|
|
86
|
-
* ordering and every other line, and is idempotent — a second run moves
|
|
87
|
-
* nothing. `tools/split-env-secrets.mjs` is its command line.
|
|
88
|
-
*
|
|
89
|
-
* Reading is what changed, and only for the names on that list.
|
|
90
|
-
*/
|
|
91
|
-
|
|
92
|
-
const fs = require('node:fs');
|
|
93
|
-
const path = require('node:path');
|
|
94
|
-
const credentials = require('./credentials.js');
|
|
95
|
-
// `hasPosixModes()` — on Windows fs.stat's mode is synthesised from the read-only
|
|
96
|
-
// attribute, so 0o666 comes back for every file and the group/other test below is
|
|
97
|
-
// always true. Reporting a Windows user's .env as world-readable on every single
|
|
98
|
-
// load is a false alarm they cannot act on.
|
|
99
|
-
const platform = require('./platform.js');
|
|
100
|
-
|
|
101
|
-
const ENV_FILE = '.env';
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* The file for production secrets that are NOT host credentials. Read only by
|
|
105
|
-
* an explicit `loadForeignSecrets()` call — never at host start-up — so a
|
|
106
|
-
* billing or publishing token stops being ambient in every process.
|
|
107
|
-
*/
|
|
108
|
-
const SECRETS_FILE = 'secrets.env';
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Names that belong to another product and are never loaded into a host's
|
|
112
|
-
* environment, however they got into the file.
|
|
113
|
-
*
|
|
114
|
-
* The list is deliberately a *deny* list and not an allow list. An allow list
|
|
115
|
-
* would have to be updated every time a provider is added, and a key missing
|
|
116
|
-
* from it would stop working — the failure mode of the one feature this module
|
|
117
|
-
* exists to provide. A deny list can only ever make a host *less* exposed, so
|
|
118
|
-
* it fails in the safe direction: the worst case is a foreign secret that stays
|
|
119
|
-
* in `.env` and keeps being loaded, which is exactly today's behaviour.
|
|
120
|
-
*
|
|
121
|
-
* `STRIPE_` is a prefix rather than four names because the rail has grown a
|
|
122
|
-
* price id per plan; a new one must not be able to re-enter the shared file by
|
|
123
|
-
* being new.
|
|
124
|
-
*/
|
|
125
|
-
const FOREIGN_SECRET_PREFIXES = Object.freeze(['STRIPE_']);
|
|
126
|
-
|
|
127
|
-
const FOREIGN_SECRET_NAMES = Object.freeze([
|
|
128
|
-
// Billing — the aegis1/server product's rail, not a host credential.
|
|
129
|
-
'STRIPE_SECRET_KEY',
|
|
130
|
-
'STRIPE_WEBHOOK_SECRET',
|
|
131
|
-
'STRIPE_PRODUCT',
|
|
132
|
-
'STRIPE_PRO_PRICE_ID',
|
|
133
|
-
'STRIPE_S_PRICE_ID',
|
|
134
|
-
'STRIPE_MEMORY_PRICE_ID',
|
|
135
|
-
// Publishing.
|
|
136
|
-
'PYPI_API_TOKEN',
|
|
137
|
-
'TWINE_PASSWORD',
|
|
138
|
-
// Claude Code's own OAuth token: a credential for a different CLI, which
|
|
139
|
-
// reads it from its own environment. No host in this repo does.
|
|
140
|
-
'CLAUDE_CODE_OAUTH_TOKEN',
|
|
141
|
-
]);
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Is this variable one that must never be loaded into a host process?
|
|
145
|
-
*
|
|
146
|
-
* @param {string} name
|
|
147
|
-
* @returns {boolean}
|
|
148
|
-
*/
|
|
149
|
-
function isForeignSecret(name) {
|
|
150
|
-
const n = String(name == null ? '' : name).trim();
|
|
151
|
-
if (!n) return false;
|
|
152
|
-
if (FOREIGN_SECRET_NAMES.includes(n)) return true;
|
|
153
|
-
return FOREIGN_SECRET_PREFIXES.some((p) => n.startsWith(p));
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** Permissions for a file holding secrets: owner read/write, nothing else. */
|
|
157
|
-
const SECRET_FILE_MODE = 0o600;
|
|
158
|
-
|
|
159
|
-
/** A directory we create for a secret file: owner only. */
|
|
160
|
-
const SECRET_DIR_MODE = 0o700;
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* provider id -> the env var a BYOK key is conventionally exported as, for the
|
|
164
|
-
* ids where the generic rule below would spell the wrong name. The generic rule
|
|
165
|
-
* is `ID_API_KEY` in upper snake case, which already covers openai, anthropic,
|
|
166
|
-
* deepseek, groq, mistral, openrouter, together and most of the catalogue — so
|
|
167
|
-
* this table is only the exceptions, kept short on purpose.
|
|
168
|
-
*/
|
|
169
|
-
const ALIASES = Object.freeze({
|
|
170
|
-
google: 'GEMINI_API_KEY',
|
|
171
|
-
gemini: 'GEMINI_API_KEY',
|
|
172
|
-
'google-ai': 'GEMINI_API_KEY',
|
|
173
|
-
xai: 'XAI_API_KEY',
|
|
174
|
-
'x-ai': 'XAI_API_KEY',
|
|
175
|
-
grok: 'XAI_API_KEY',
|
|
176
|
-
huggingface: 'HF_TOKEN',
|
|
177
|
-
together: 'TOGETHER_API_KEY',
|
|
178
|
-
'together-ai': 'TOGETHER_API_KEY',
|
|
179
|
-
fireworks: 'FIREWORKS_API_KEY',
|
|
180
|
-
'azure-openai': 'AZURE_OPENAI_API_KEY',
|
|
181
|
-
'voyage-ai': 'VOYAGE_API_KEY',
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
/** The variable that carries an AEGIS Cloud account key (see credentials.js). */
|
|
185
|
-
const ACCOUNT_ENV_VAR = 'AEGIS_API_KEY';
|
|
186
|
-
|
|
187
|
-
/** The file this host would read, honouring `$AEGISCODE_HOME`. */
|
|
188
|
-
function envFileFor(dir) {
|
|
189
|
-
return path.join(dir || credentials.aegisHome(), ENV_FILE);
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* The foreign-secrets file beside `envFileFor()`, honouring the same
|
|
194
|
-
* `$AEGISCODE_HOME`. Never read implicitly.
|
|
195
|
-
*/
|
|
196
|
-
function secretEnvFileFor(dir) {
|
|
197
|
-
return path.join(dir || credentials.aegisHome(), SECRETS_FILE);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* The env var one BYOK provider's key is read from.
|
|
202
|
-
*
|
|
203
|
-
* @param {string} providerId e.g. 'openai', 'deepseek', 'Google'
|
|
204
|
-
* @returns {string} e.g. 'OPENAI_API_KEY' — '' when there is no usable id
|
|
205
|
-
*/
|
|
206
|
-
function envVarFor(providerId) {
|
|
207
|
-
const id = String(providerId || '').trim().toLowerCase();
|
|
208
|
-
if (!id) return '';
|
|
209
|
-
// A `byok:` prefixed row is the same provider — accept it so callers can pass
|
|
210
|
-
// whatever spelling they hold without stripping it first.
|
|
211
|
-
const bare = id.startsWith('byok:') ? id.slice('byok:'.length).trim() : id;
|
|
212
|
-
if (!bare) return '';
|
|
213
|
-
if (ALIASES[bare]) return ALIASES[bare];
|
|
214
|
-
const name = bare.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
|
|
215
|
-
return name ? `${name}_API_KEY` : '';
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/** A fragment of a token/secret: no whitespace, no dotenv punctuation around it. */
|
|
219
|
-
const ENV_TOKENISH = /^[A-Za-z0-9_+/.-]+$/;
|
|
220
|
-
|
|
221
|
-
/** A value long enough that a keyless line after it is a wrap, not junk. */
|
|
222
|
-
const ENV_WRAP_MIN_VALUE = 32;
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* Fold a hard-wrapped value back onto its `KEY=` line.
|
|
226
|
-
*
|
|
227
|
-
* A long secret pasted into a wrapping editor leaves its tail on the next
|
|
228
|
-
* physical line. Dotenv semantics would keep the head as the value and discard
|
|
229
|
-
* the keyless tail, so the credential loads as a TRUNCATED string that looks
|
|
230
|
-
* present and fails deep in a provider call — a 108-char Claude Code OAuth
|
|
231
|
-
* token lost its last 9 chars this way and every request 401'd with "OAuth
|
|
232
|
-
* access token is invalid" while the env var looked set.
|
|
233
|
-
*
|
|
234
|
-
* A fold requires the tail to be unambiguously a token fragment: no whitespace,
|
|
235
|
-
* no `=`, not a comment, and either indented (the wrap signature a wrapped paste
|
|
236
|
-
* leaves behind) or following a value already long enough to be a secret. The
|
|
237
|
-
* head must itself be a plain unquoted token, so an inline ` # comment` can
|
|
238
|
-
* never be glued to the next line. A short value plus a bare word ("x" then
|
|
239
|
-
* "NOEQ") is left alone — that is a junk line, and gluing it on would corrupt
|
|
240
|
-
* the real value.
|
|
241
|
-
*
|
|
242
|
-
* @param {string[]} lines every physical line of the file
|
|
243
|
-
* @param {number} i index of the `KEY=` line
|
|
244
|
-
* @param {string} head the trimmed value on that line
|
|
245
|
-
* @returns {{value:string, i:number}} the folded value and the last line consumed
|
|
246
|
-
*/
|
|
247
|
-
function foldWrappedEnvValue(lines, i, head) {
|
|
248
|
-
let value = head;
|
|
249
|
-
// Only an unquoted, comment-free, token-shaped head may absorb a tail: any
|
|
250
|
-
// other head is a value with structure worth preserving verbatim.
|
|
251
|
-
if (value.startsWith('"') || value.startsWith("'")) return { value, i };
|
|
252
|
-
while (i + 1 < lines.length) {
|
|
253
|
-
const nextRaw = lines[i + 1];
|
|
254
|
-
const next = nextRaw.trim();
|
|
255
|
-
if (!next || next.startsWith('#') || next.includes('=')) break;
|
|
256
|
-
if (!ENV_TOKENISH.test(next)) break;
|
|
257
|
-
const indented = /^[ \t]/.test(nextRaw);
|
|
258
|
-
// The non-indented branch is the risky one (a bare word after a value), so
|
|
259
|
-
// it additionally demands the head be one unbroken token AND long enough to
|
|
260
|
-
// be a secret before it is allowed to swallow the line.
|
|
261
|
-
if (!indented && (value.length < ENV_WRAP_MIN_VALUE || !ENV_TOKENISH.test(value))) break;
|
|
262
|
-
value += next;
|
|
263
|
-
i += 1;
|
|
264
|
-
// Once a tail has been absorbed the head is only longer, so a further
|
|
265
|
-
// indented fragment keeps folding; a non-indented one now clears the length
|
|
266
|
-
// bar on its own.
|
|
267
|
-
}
|
|
268
|
-
return { value, i };
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/**
|
|
272
|
-
* Parse dotenv text. Deliberately small and total: an unparseable line is
|
|
273
|
-
* skipped rather than thrown, so one bad line cannot stop the rest of the file
|
|
274
|
-
* (and a stray `#` comment or a blank line is normal, not an error).
|
|
275
|
-
*
|
|
276
|
-
* Handles `export `, `KEY=value`, `KEY="value"`, `KEY='value'` and a trailing
|
|
277
|
-
* ` # comment` on an unquoted value. A double-quoted value is unescaped (`\"`,
|
|
278
|
-
* `\\`) because that is what `quoteEnvValue` writes and what dotenv readers do;
|
|
279
|
-
* a single-quoted value is literal.
|
|
280
|
-
*
|
|
281
|
-
* A hard-wrapped paste is folded back together (see `foldWrappedEnvValue`).
|
|
282
|
-
* This is not cosmetic: a 108-char Claude Code OAuth token pasted into a
|
|
283
|
-
* wrapping editor landed as a 99-char head plus an indented keyless tail, and
|
|
284
|
-
* the head loaded as a TRUNCATED credential that looked present and 401'd deep
|
|
285
|
-
* in a provider call. The same fold exists in `src/env.js` of the engine repo
|
|
286
|
-
* (`parseEnvFile`) so both readers agree on a wrapped file.
|
|
287
|
-
*/
|
|
288
|
-
function parseEnvText(text) {
|
|
289
|
-
const out = {};
|
|
290
|
-
const lines = String(text == null ? '' : text).split(/\r?\n/);
|
|
291
|
-
for (let i = 0; i < lines.length; i++) {
|
|
292
|
-
const line = lines[i].trim();
|
|
293
|
-
if (!line || line.startsWith('#')) continue;
|
|
294
|
-
const eq = line.indexOf('=');
|
|
295
|
-
if (eq <= 0) continue;
|
|
296
|
-
let name = line.slice(0, eq).trim();
|
|
297
|
-
if (name.startsWith('export ')) name = name.slice('export '.length).trim();
|
|
298
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
|
|
299
|
-
const folded = foldWrappedEnvValue(lines, i, line.slice(eq + 1).trim());
|
|
300
|
-
let value = folded.value;
|
|
301
|
-
i = folded.i;
|
|
302
|
-
const doubleQuoted = value.startsWith('"') && value.endsWith('"') && value.length >= 2;
|
|
303
|
-
const singleQuoted = value.startsWith("'") && value.endsWith("'") && value.length >= 2;
|
|
304
|
-
if (doubleQuoted) {
|
|
305
|
-
// Double quotes are the one form that carries escapes, so they are the
|
|
306
|
-
// one form that must be unescaped — `\"` and `\\`, exactly what
|
|
307
|
-
// `quoteEnvValue` writes and what every dotenv reader does. Without this
|
|
308
|
-
// the writer's escaping was one-way: a value containing a quote or a
|
|
309
|
-
// backslash was stored doubled and read back mangled, so a key survived
|
|
310
|
-
// the session it was typed in but not the next one. Single quotes stay
|
|
311
|
-
// literal (`'C:\keys'` is a backslash, not an escape), which is the
|
|
312
|
-
// convention that makes the two quote styles mean something different.
|
|
313
|
-
value = value.slice(1, -1).replace(/\\(["\\])/g, '$1');
|
|
314
|
-
} else if (singleQuoted) {
|
|
315
|
-
value = value.slice(1, -1);
|
|
316
|
-
} else {
|
|
317
|
-
const hash = value.indexOf(' #');
|
|
318
|
-
if (hash !== -1) value = value.slice(0, hash).trim();
|
|
319
|
-
}
|
|
320
|
-
out[name] = value;
|
|
321
|
-
}
|
|
322
|
-
return out;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* Read the env file into `process.env` (or `o.env`), without overwriting
|
|
327
|
-
* anything already set.
|
|
328
|
-
*
|
|
329
|
-
* @param {object} [o]
|
|
330
|
-
* @param {object} [o.env] defaults to process.env
|
|
331
|
-
* @param {string} [o.dir] defaults to aegisHome()
|
|
332
|
-
* @param {string} [o.file] an explicit path, for tests
|
|
333
|
-
* @returns {{ok:boolean, file:string, loaded:string[], kept:string[],
|
|
334
|
-
* reason:string, loose:boolean, mode:number}}
|
|
335
|
-
* `loaded` — names taken from the file. `kept` — names the environment
|
|
336
|
-
* already had, left alone (a real export always wins).
|
|
337
|
-
*/
|
|
338
|
-
/**
|
|
339
|
-
* Provenance of every value this process took from `~/.aegiscode/.env`.
|
|
340
|
-
*
|
|
341
|
-
* Keyed off the env object itself (a WeakMap, so an injected `{ env }` in a
|
|
342
|
-
* test is tracked without leaking and `process.env` needs no extra property).
|
|
343
|
-
* See `isFromEnvFile`.
|
|
344
|
-
*/
|
|
345
|
-
const ENV_SOURCED = new WeakMap();
|
|
346
|
-
|
|
347
|
-
function sourcedFrom(env) {
|
|
348
|
-
let map = ENV_SOURCED.get(env);
|
|
349
|
-
if (!map) {
|
|
350
|
-
map = new Map();
|
|
351
|
-
ENV_SOURCED.set(env, map);
|
|
352
|
-
}
|
|
353
|
-
return map;
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/**
|
|
357
|
-
* Was `name`'s CURRENT value in `env` one this process took from the shared env
|
|
358
|
-
* file, rather than something the launching shell exported?
|
|
359
|
-
*
|
|
360
|
-
* This is the distinction the file's own rule 1 depends on and could not
|
|
361
|
-
* previously express. The file is documented as a *convenience for the common
|
|
362
|
-
* case, not a way for a stale file to shadow an explicit export* — but once a
|
|
363
|
-
* value is copied into `process.env` the two are the same thing, so every
|
|
364
|
-
* env-first reader (`client/credentials.js`) treated a line in the file exactly
|
|
365
|
-
* like a deliberate export and let it win forever. Concretely: a user runs
|
|
366
|
-
* `aegiscode login`, the key is written to `credentials.json` (0600) and
|
|
367
|
-
* reported as saved, and every request since then authenticates with whatever
|
|
368
|
-
* `AEGIS_API_KEY=` line the file still carries — the "it says saved but the key
|
|
369
|
-
* is wrong" report. A real export still wins; a file value is a fallback.
|
|
370
|
-
*
|
|
371
|
-
* `value` is checked as well as the name: a shell export that replaced the
|
|
372
|
-
* loaded value is no longer file-sourced, and neither is a later `setEnvValue`
|
|
373
|
-
* (which applies the value it just wrote and marks it accordingly).
|
|
374
|
-
*
|
|
375
|
-
* @param {string} name
|
|
376
|
-
* @param {string} [value] the current value, to confirm it is still the one the
|
|
377
|
-
* file provided. Omit to ask about the name alone.
|
|
378
|
-
* @param {object} [o] `env`, for tests and injected environments
|
|
379
|
-
*/
|
|
380
|
-
function isFromEnvFile(name, value, o = {}) {
|
|
381
|
-
const env = o.env || process.env;
|
|
382
|
-
const map = ENV_SOURCED.get(env);
|
|
383
|
-
if (!map || !map.has(name)) return false;
|
|
384
|
-
if (value === undefined) return true;
|
|
385
|
-
return map.get(name) === String(value);
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
function loadEnvFile(o = {}) {
|
|
389
|
-
const env = o.env || process.env;
|
|
390
|
-
const file = o.file || envFileFor(o.dir);
|
|
391
|
-
// Names this process took from the FILE, with the value it took. Kept so a
|
|
392
|
-
// consumer can tell the two sources apart: rule 1 above makes the file a
|
|
393
|
-
// fallback, but the moment its value lands in `process.env` it is otherwise
|
|
394
|
-
// indistinguishable from an explicit `AEGIS_API_KEY=… aegiscode` export, and
|
|
395
|
-
// `client/credentials.js`'s resolution order is env-first. Without this
|
|
396
|
-
// marker a leftover line in a file every host sources at start-up outranks
|
|
397
|
-
// the key the user explicitly saved — see `isFromEnvFile()` below.
|
|
398
|
-
const sourced = sourcedFrom(env);
|
|
399
|
-
const result = {
|
|
400
|
-
ok: false, file, loaded: [], kept: [], refused: [], reason: '', loose: false, mode: 0,
|
|
401
|
-
};
|
|
402
|
-
|
|
403
|
-
let text;
|
|
404
|
-
try {
|
|
405
|
-
text = fs.readFileSync(file, 'utf8');
|
|
406
|
-
} catch (e) {
|
|
407
|
-
result.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
|
|
408
|
-
return result;
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
try {
|
|
412
|
-
const st = fs.statSync(file);
|
|
413
|
-
result.mode = st.mode & 0o777;
|
|
414
|
-
// Group- or world-readable: worth one line to the user, never a rewrite of
|
|
415
|
-
// a file we did not create. Only asked where the answer can be true or false
|
|
416
|
-
// (see the platform require above).
|
|
417
|
-
result.loose = platform.hasPosixModes() && (st.mode & 0o077) !== 0;
|
|
418
|
-
} catch { /* stat is advisory only */ }
|
|
419
|
-
|
|
420
|
-
const parsed = parseEnvText(text);
|
|
421
|
-
for (const [name, value] of Object.entries(parsed)) {
|
|
422
|
-
// A foreign secret is neither loaded nor "kept": it is refused, and named
|
|
423
|
-
// in `refused` so a caller can tell the user it is in the wrong file
|
|
424
|
-
// instead of silently ignoring it.
|
|
425
|
-
if (isForeignSecret(name)) {
|
|
426
|
-
result.refused.push(name);
|
|
427
|
-
continue;
|
|
428
|
-
}
|
|
429
|
-
if (env[name] === undefined || env[name] === '') {
|
|
430
|
-
env[name] = value;
|
|
431
|
-
// Provenance: this value is the FILE's, not the launching shell's. An
|
|
432
|
-
// env-first reader must treat it as the fallback the file is documented
|
|
433
|
-
// to be, not as an explicit export that outranks a saved key.
|
|
434
|
-
sourced.set(name, value);
|
|
435
|
-
result.loaded.push(name);
|
|
436
|
-
} else {
|
|
437
|
-
// A real export wins (rule 1) and is deliberately NOT marked: it is the
|
|
438
|
-
// one source allowed to outrank `credentials.json`.
|
|
439
|
-
result.kept.push(name);
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
result.ok = true;
|
|
443
|
-
return result;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
/**
|
|
447
|
-
* Read the foreign-secrets file into an environment, on purpose.
|
|
448
|
-
*
|
|
449
|
-
* The counterpart of the refusal inside `loadEnvFile`: a process that actually
|
|
450
|
-
* needs a billing or publishing token asks for it by name, and it is documented
|
|
451
|
-
* at the call site. Nothing calls this at host start-up — that is the point of
|
|
452
|
-
* the split — and unlike `loadEnvFile` it does NOT treat an already-set variable
|
|
453
|
-
* as a reason to skip: a caller who asks for the secrets file gets the file's
|
|
454
|
-
* values, in a fresh object unless one is passed.
|
|
455
|
-
*
|
|
456
|
-
* @param {object} [o]
|
|
457
|
-
* @param {object} [o.env]
|
|
458
|
-
* @param {string} [o.dir]
|
|
459
|
-
* @param {string} [o.file]
|
|
460
|
-
* @param {string[]} [o.only] restrict to these names
|
|
461
|
-
* @returns {{ok:boolean, file:string, loaded:string[], reason:string,
|
|
462
|
-
* mode:number, loose:boolean}}
|
|
463
|
-
*/
|
|
464
|
-
function loadForeignSecrets(o = {}) {
|
|
465
|
-
const env = o.env || process.env;
|
|
466
|
-
const file = o.file || secretEnvFileFor(o.dir);
|
|
467
|
-
const result = { ok: false, file, loaded: [], reason: '', mode: 0, loose: false };
|
|
468
|
-
const only = Array.isArray(o.only) && o.only.length
|
|
469
|
-
? o.only.filter(isForeignSecret)
|
|
470
|
-
: null;
|
|
471
|
-
|
|
472
|
-
let text;
|
|
473
|
-
try {
|
|
474
|
-
text = fs.readFileSync(file, 'utf8');
|
|
475
|
-
} catch (e) {
|
|
476
|
-
result.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
|
|
477
|
-
return result;
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
try {
|
|
481
|
-
const st = fs.statSync(file);
|
|
482
|
-
result.mode = st.mode & 0o777;
|
|
483
|
-
result.loose = platform.hasPosixModes() && (st.mode & 0o077) !== 0;
|
|
484
|
-
} catch { /* advisory */ }
|
|
485
|
-
|
|
486
|
-
const parsed = parseEnvText(text);
|
|
487
|
-
for (const [name, value] of Object.entries(parsed)) {
|
|
488
|
-
if (only && !only.includes(name)) continue;
|
|
489
|
-
env[name] = value;
|
|
490
|
-
result.loaded.push(name);
|
|
491
|
-
}
|
|
492
|
-
result.ok = true;
|
|
493
|
-
return result;
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
/**
|
|
497
|
-
* One foreign secret, read without exporting it into an environment.
|
|
498
|
-
*
|
|
499
|
-
* @returns {string} '' when the file does not exist or does not hold the name
|
|
500
|
-
*/
|
|
501
|
-
function foreignSecretValue(name, o = {}) {
|
|
502
|
-
if (!isForeignSecret(name)) return '';
|
|
503
|
-
const file = o.file || secretEnvFileFor(o.dir);
|
|
504
|
-
try {
|
|
505
|
-
const parsed = parseEnvText(fs.readFileSync(file, 'utf8'));
|
|
506
|
-
const v = parsed[String(name)];
|
|
507
|
-
return typeof v === 'string' ? v : '';
|
|
508
|
-
} catch {
|
|
509
|
-
return '';
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
/**
|
|
514
|
-
* One foreign secret's value, from every place a user might actually have put
|
|
515
|
-
* it — built for `CLAUDE_CODE_OAUTH_TOKEN`, which lived in plain `.env` before
|
|
516
|
-
* this split existed and is not necessarily migrated on any given machine.
|
|
517
|
-
*
|
|
518
|
-
* Checked in the order that keeps an explicit export authoritative, same as
|
|
519
|
-
* `loadEnvFile`'s rule 1:
|
|
520
|
-
*
|
|
521
|
-
* 1. `o.env` (default `process.env`) — a real shell export is the user's own
|
|
522
|
-
* doing and always wins, exactly as it does for a host key.
|
|
523
|
-
* 2. `secrets.env` (`foreignSecretValue`) — the file the split moves this
|
|
524
|
-
* name to, and the only one `setForeignSecret` below ever writes.
|
|
525
|
-
* 3. `.env`, parsed directly — covers a name that has not been migrated yet.
|
|
526
|
-
*
|
|
527
|
-
* Never applies the value to any env object: the whole point of the split is
|
|
528
|
-
* that this name stays OUT of `process.env` unless the caller that actually
|
|
529
|
-
* needs it (the Claude Code Pro transport) asks for it by name, right before
|
|
530
|
-
* it is used.
|
|
531
|
-
*
|
|
532
|
-
* @param {string} name
|
|
533
|
-
* @param {object} [o] `env`, `dir`, `file` — same meaning as `foreignSecretValue`
|
|
534
|
-
* @returns {string} '' when no source has it, or `name` is not a foreign secret
|
|
535
|
-
*/
|
|
536
|
-
function resolveForeignSecret(name, o = {}) {
|
|
537
|
-
if (!isForeignSecret(name)) return '';
|
|
538
|
-
const env = o.env || process.env;
|
|
539
|
-
const direct = env && env[name];
|
|
540
|
-
if (typeof direct === 'string' && direct.trim()) return direct.trim();
|
|
541
|
-
const fromSecrets = foreignSecretValue(name, o);
|
|
542
|
-
if (fromSecrets && fromSecrets.trim()) return fromSecrets.trim();
|
|
543
|
-
try {
|
|
544
|
-
const parsed = parseEnvText(fs.readFileSync(envFileFor(o.dir), 'utf8'));
|
|
545
|
-
const v = parsed[String(name)];
|
|
546
|
-
return typeof v === 'string' ? v.trim() : '';
|
|
547
|
-
} catch {
|
|
548
|
-
return '';
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/** Write a secrets file with the right permissions and no half-written state. */
|
|
553
|
-
function writeSecretFile(file, text) {
|
|
554
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
|
|
555
|
-
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
556
|
-
fs.writeFileSync(tmp, text, { mode: SECRET_FILE_MODE });
|
|
557
|
-
fs.renameSync(tmp, file);
|
|
558
|
-
// rename preserves the temp file's mode, which the umask may have loosened on
|
|
559
|
-
// a machine with a permissive one — so the mode is asserted after the move.
|
|
560
|
-
fs.chmodSync(file, SECRET_FILE_MODE);
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
/**
|
|
564
|
-
* Store one foreign secret in `~/.aegiscode/secrets.env` — the counterpart of
|
|
565
|
-
* `setEnvValue`, for the file that one exists to keep out of.
|
|
566
|
-
*
|
|
567
|
-
* The guard is the mirror image of `setEnvValue`'s: that function refuses a
|
|
568
|
-
* foreign name so `.env` cannot re-acquire one, and this one refuses anything
|
|
569
|
-
* that is NOT a foreign name, so `secrets.env` cannot become a second place a
|
|
570
|
-
* host credential is written (and therefore a second place to look for one).
|
|
571
|
-
*
|
|
572
|
-
* Deliberately has no `apply` option and never touches any env object: a
|
|
573
|
-
* foreign secret's whole point is staying out of `process.env` until the one
|
|
574
|
-
* caller that needs it asks by name (`resolveForeignSecret`), right before use.
|
|
575
|
-
*
|
|
576
|
-
* @param {string} name one of FOREIGN_SECRET_NAMES (or a FOREIGN_SECRET_PREFIXES match)
|
|
577
|
-
* @param {string} value the secret. Never returned, never logged.
|
|
578
|
-
* @param {object} [o]
|
|
579
|
-
* @param {string} [o.dir] defaults to aegisHome()
|
|
580
|
-
* @param {string} [o.file] an explicit path, for tests
|
|
581
|
-
* @returns {{ok:boolean, file:string, name:string, changed:boolean,
|
|
582
|
-
* created:boolean, replaced:boolean, mode:number, tightened:boolean,
|
|
583
|
-
* error:string}}
|
|
584
|
-
*/
|
|
585
|
-
function setForeignSecret(name, value, o = {}) {
|
|
586
|
-
const file = o.file || secretEnvFileFor(o.dir);
|
|
587
|
-
const out = {
|
|
588
|
-
ok: false, file, name: String(name || ''), changed: false, created: false,
|
|
589
|
-
replaced: false, mode: 0, tightened: false, error: '',
|
|
590
|
-
};
|
|
591
|
-
|
|
592
|
-
if (!isWritableName(name)) {
|
|
593
|
-
out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
|
|
594
|
-
return out;
|
|
595
|
-
}
|
|
596
|
-
if (!isForeignSecret(name)) {
|
|
597
|
-
out.error = `refusing to write ${name} to ${SECRETS_FILE} — it is a host credential, not a `
|
|
598
|
-
+ `foreign secret; use setEnvValue (${ENV_FILE}) instead`;
|
|
599
|
-
return out;
|
|
600
|
-
}
|
|
601
|
-
const secret = String(value == null ? '' : value).trim();
|
|
602
|
-
if (!secret) {
|
|
603
|
-
out.error = `refusing to write an empty ${name}`;
|
|
604
|
-
return out;
|
|
605
|
-
}
|
|
606
|
-
if (/[\r\n]/.test(String(value))) {
|
|
607
|
-
out.error = `refusing to write ${name} — the value contains a line break`;
|
|
608
|
-
return out;
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
let before = '';
|
|
612
|
-
let previousMode = 0;
|
|
613
|
-
out.created = true;
|
|
614
|
-
try {
|
|
615
|
-
before = fs.readFileSync(file, 'utf8');
|
|
616
|
-
out.created = false;
|
|
617
|
-
try {
|
|
618
|
-
previousMode = fs.statSync(file).mode & 0o777;
|
|
619
|
-
} catch { /* advisory */ }
|
|
620
|
-
} catch (e) {
|
|
621
|
-
if (e && e.code !== 'ENOENT') {
|
|
622
|
-
out.error = `could not read ${file}: ${e.code || e.message}`;
|
|
623
|
-
return out;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
const aligned = String(before).replace(/\r\n/g, '\n');
|
|
628
|
-
if (!out.created && parseEnvText(aligned)[name] === secret) {
|
|
629
|
-
// Same value already stored: leave the file (its mtime, its mode) alone.
|
|
630
|
-
out.ok = true;
|
|
631
|
-
out.changed = false;
|
|
632
|
-
out.replaced = true;
|
|
633
|
-
out.mode = previousMode || SECRET_FILE_MODE;
|
|
634
|
-
return out;
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
const { text, replaced } = upsertEnvText(aligned, name, secret);
|
|
638
|
-
try {
|
|
639
|
-
writeSecretFile(file, text);
|
|
640
|
-
} catch (e) {
|
|
641
|
-
out.error = `could not write ${file}: ${e.code || e.message}`;
|
|
642
|
-
return out;
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
out.ok = true;
|
|
646
|
-
out.changed = true;
|
|
647
|
-
out.replaced = replaced;
|
|
648
|
-
out.mode = SECRET_FILE_MODE;
|
|
649
|
-
out.tightened =
|
|
650
|
-
platform.hasPosixModes() && !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
|
|
651
|
-
return out;
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* Move every foreign secret out of `~/.aegiscode/.env` into `secrets.env`.
|
|
656
|
-
*
|
|
657
|
-
* Idempotent by construction: the names moved are the ones the parse finds in
|
|
658
|
-
* `.env`, and a second run finds none. A name already present in `secrets.env`
|
|
659
|
-
* is not overwritten — the destination is the authority once it exists, so a
|
|
660
|
-
* migration can never silently revert a value someone rotated there.
|
|
661
|
-
*
|
|
662
|
-
* Every other line of `.env` — comments, order, unrelated keys, `export`
|
|
663
|
-
* prefixes — survives verbatim, because both edits go through the same
|
|
664
|
-
* `upsertEnvText`/`removeEnvText` pair the writers use.
|
|
665
|
-
*
|
|
666
|
-
* @param {object} [o]
|
|
667
|
-
* @param {boolean} [o.apply=false] without it, nothing is written (dry run)
|
|
668
|
-
* @returns {{ok:boolean, moved:string[], kept:string[], envFile:string,
|
|
669
|
-
* secretsFile:string, apply:boolean, reason?:string}}
|
|
670
|
-
*/
|
|
671
|
-
function splitForeignSecrets(o = {}) {
|
|
672
|
-
const env = o.env || process.env;
|
|
673
|
-
const envFile = o.file || envFileFor(o.dir);
|
|
674
|
-
const secretsFile = o.secretsFile || secretEnvFileFor(o.dir);
|
|
675
|
-
const apply = o.apply === true;
|
|
676
|
-
const out = { ok: false, moved: [], kept: [], envFile, secretsFile, apply };
|
|
677
|
-
|
|
678
|
-
let envText;
|
|
679
|
-
try {
|
|
680
|
-
envText = fs.readFileSync(envFile, 'utf8');
|
|
681
|
-
} catch (e) {
|
|
682
|
-
out.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
|
|
683
|
-
return out;
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
const parsed = parseEnvText(envText);
|
|
687
|
-
const names = Object.keys(parsed).filter(isForeignSecret).sort();
|
|
688
|
-
if (!names.length) {
|
|
689
|
-
out.ok = true;
|
|
690
|
-
return out;
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
let secretsText = '';
|
|
694
|
-
try {
|
|
695
|
-
secretsText = fs.readFileSync(secretsFile, 'utf8');
|
|
696
|
-
} catch { /* the file is created below */ }
|
|
697
|
-
const already = parseEnvText(secretsText);
|
|
698
|
-
|
|
699
|
-
for (const name of names) {
|
|
700
|
-
if (Object.prototype.hasOwnProperty.call(already, name)) {
|
|
701
|
-
out.kept.push(name);
|
|
702
|
-
continue;
|
|
703
|
-
}
|
|
704
|
-
secretsText = upsertEnvText(secretsText, name, parsed[name]).text;
|
|
705
|
-
out.moved.push(name);
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
if (apply) {
|
|
709
|
-
for (const name of names) {
|
|
710
|
-
envText = removeEnvText(envText, name).text;
|
|
711
|
-
}
|
|
712
|
-
if (out.moved.length) writeSecretFile(secretsFile, secretsText);
|
|
713
|
-
writeSecretFile(envFile, envText);
|
|
714
|
-
// And out of the live environment of THIS process, or a running host would
|
|
715
|
-
// keep the value it had already loaded until it restarted.
|
|
716
|
-
for (const name of names) {
|
|
717
|
-
if (env[name] === parsed[name]) delete env[name];
|
|
718
|
-
}
|
|
719
|
-
} else if (out.moved.length) {
|
|
720
|
-
// A dry run still shows the destination, without creating it.
|
|
721
|
-
out.secretsFile = secretsFile;
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
out.ok = true;
|
|
725
|
-
return out;
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
/**
|
|
729
|
-
* The shortest value that can be a real vendor credential.
|
|
730
|
-
*
|
|
731
|
-
* Not a shape check on any one vendor's format — deliberately. The vendors this
|
|
732
|
-
* file serves disagree about their prefixes (`sk-ant-api03-`, `sk-proj-`,
|
|
733
|
-
* `aegis_`, `gsk_`, a bare opaque string for a custom gateway), and a prefix
|
|
734
|
-
* allow-list here would refuse a valid key for a provider added tomorrow. What
|
|
735
|
-
* every one of them agrees on is the FLOOR: no vendor issues a credential that
|
|
736
|
-
* is a handful of characters. A value below this is not a key somebody typed
|
|
737
|
-
* wrongly-shaped, it is a paste that lost its payload or an answer typed into
|
|
738
|
-
* the wrong prompt, and the difference matters because the two failure modes
|
|
739
|
-
* look nothing alike to the user (see `providerKeyFromEnv`, and the upstream
|
|
740
|
-
* 401 that a 2-character value produced).
|
|
741
|
-
*
|
|
742
|
-
* Eight is the floor rather than something larger on purpose: it is below every
|
|
743
|
-
* real credential by orders of magnitude, so it can only ever reject values
|
|
744
|
-
* that are provably not keys, and it cannot reject one that is.
|
|
745
|
-
*/
|
|
746
|
-
const MIN_CREDENTIAL_LEN = 8;
|
|
747
|
-
|
|
748
|
-
/** Whether `value` is long enough to be a credential at all. See the floor above. */
|
|
749
|
-
function credentialLooksUsable(value) {
|
|
750
|
-
return typeof value === 'string' && value.trim().length >= MIN_CREDENTIAL_LEN;
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
/**
|
|
754
|
-
* The BYOK key for a provider out of the environment, if the env file (or the
|
|
755
|
-
* shell) supplies one. Returns '' when it does not — the encrypted store then
|
|
756
|
-
* remains the only source, exactly as before.
|
|
757
|
-
*/
|
|
758
|
-
function providerKeyFromEnv(providerId, env) {
|
|
759
|
-
const name = envVarFor(providerId);
|
|
760
|
-
if (!name) return { key: '', env: '', rejected: null };
|
|
761
|
-
const raw = (env || process.env)[name];
|
|
762
|
-
const key = typeof raw === 'string' ? raw.trim() : '';
|
|
763
|
-
if (key === '') return { key: '', env: name, rejected: null };
|
|
764
|
-
if (!credentialLooksUsable(key)) {
|
|
765
|
-
// A value that CANNOT be a vendor credential is not one, and returning it
|
|
766
|
-
// as `key` is how a junk entry became an upstream 401 instead of a prompt.
|
|
767
|
-
// Measured on this machine 2026-10-14: `~/.aegiscode/.env` held
|
|
768
|
-
// `ANTHROPIC_API_KEY=he` (2 characters — a paste that lost its value, or an
|
|
769
|
-
// answer typed into the wrong prompt). Every reader below took it as a key,
|
|
770
|
-
// the picker painted the `anthropic:*` rows as `configured`, the turn
|
|
771
|
-
// forwarded `X-Provider-Key: he` to the relay, and Anthropic answered
|
|
772
|
-
// `{"type":"error","error":{"type":"authentication_error","message":
|
|
773
|
-
// "Invalid bearer token"}}` — surfaced to the user as "Anthropic auth
|
|
774
|
-
// failed", which reads as "your Anthropic account is broken" when the
|
|
775
|
-
// truth is "this file holds two characters". Rejecting it here makes the
|
|
776
|
-
// row read as keyless, so `/model` prompts for the key again and the engine
|
|
777
|
-
// raises its own actionable "No key for …" instead of echoing a vendor 401.
|
|
778
|
-
return { key: '', env: name, rejected: `${name} holds ${key.length} character${key.length === 1 ? '' : 's'}, which cannot be a credential` };
|
|
779
|
-
}
|
|
780
|
-
return { key, env: name, rejected: null };
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
/** A variable name this module is willing to write. */
|
|
784
|
-
function isWritableName(name) {
|
|
785
|
-
return typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
/**
|
|
789
|
-
* Quote a value the way `parseEnvText` (and every dotenv reader) will read back
|
|
790
|
-
* byte-identically. Unquoted when it is safe; double-quoted with backslashes and
|
|
791
|
-
* quotes escaped when it is not. A newline is refused by the caller, never
|
|
792
|
-
* escaped here: escaping it would hide a malformed key behind a file that
|
|
793
|
-
* still looks right.
|
|
794
|
-
*/
|
|
795
|
-
function quoteEnvValue(value) {
|
|
796
|
-
const s = String(value);
|
|
797
|
-
if (s === '') return '';
|
|
798
|
-
if (!/[\s"'#\\]/.test(s)) return s;
|
|
799
|
-
return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
/**
|
|
803
|
-
* Apply `name=value` to dotenv text: replace the first existing definition in
|
|
804
|
-
* place (keeping an `export ` prefix and any trailing comment-less formatting),
|
|
805
|
-
* drop later duplicates, and append when the name is new. Every other line —
|
|
806
|
-
* comments, blanks, unrelated keys, their order — is preserved verbatim.
|
|
807
|
-
*
|
|
808
|
-
* Pure, and exported for tests: this is the part worth pinning, because a bug
|
|
809
|
-
* here silently destroys a file the user also edits by hand.
|
|
810
|
-
*
|
|
811
|
-
* @returns {{text:string, replaced:boolean}}
|
|
812
|
-
*/
|
|
813
|
-
function upsertEnvText(text, name, value) {
|
|
814
|
-
const src = String(text == null ? '' : text);
|
|
815
|
-
// Split without keeping the terminator, then re-join with '\n' and restore a
|
|
816
|
-
// final newline only if the file had one — so a write never adds a dangling
|
|
817
|
-
// blank line to a file that ended cleanly.
|
|
818
|
-
const hadFinalNewline = src === '' ? true : src.endsWith('\n');
|
|
819
|
-
const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
|
|
820
|
-
// An EMPTY file is zero lines, not one empty line: `''.split('\n')` is `['']`,
|
|
821
|
-
// and that stray element survives to `out` because the pop above only fires
|
|
822
|
-
// when `trailingBlank` is true (forced false for an empty source). The result
|
|
823
|
-
// was a first-ever write that opened the file with a leading blank line —
|
|
824
|
-
// `'\nNAME=secret\n'` — breaking the contract the comment two lines up
|
|
825
|
-
// states and the round-trip guarantee below. The common case is exactly this
|
|
826
|
-
// one: a fresh ~/.aegiscode/.env on a new machine.
|
|
827
|
-
const lines = src === '' ? [] : src.split('\n');
|
|
828
|
-
if (trailingBlank) lines.pop();
|
|
829
|
-
|
|
830
|
-
const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
|
|
831
|
-
const out = [];
|
|
832
|
-
let replaced = false;
|
|
833
|
-
for (const line of lines) {
|
|
834
|
-
const m = re.exec(line);
|
|
835
|
-
if (!m) {
|
|
836
|
-
out.push(line);
|
|
837
|
-
continue;
|
|
838
|
-
}
|
|
839
|
-
if (replaced) continue; // a second definition of the same name: collapse it
|
|
840
|
-
out.push(`${m[1]}${name}=${quoteEnvValue(value)}`);
|
|
841
|
-
replaced = true;
|
|
842
|
-
}
|
|
843
|
-
if (!replaced) out.push(`${name}=${quoteEnvValue(value)}`);
|
|
844
|
-
|
|
845
|
-
let joined = out.join('\n');
|
|
846
|
-
if (joined !== '' && (hadFinalNewline || trailingBlank)) joined += '\n';
|
|
847
|
-
return { text: joined, replaced };
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
/**
|
|
851
|
-
* Store one variable in `~/.aegiscode/.env`, creating the file (0600) and the
|
|
852
|
-
* directory (0700) when needed, and apply it to the live environment so the
|
|
853
|
-
* action that triggered the write runs on it.
|
|
854
|
-
*
|
|
855
|
-
* The one writer for every host: the CLI calls it when a model is selected and
|
|
856
|
-
* its key is missing, and the desktop calls the same function through the same
|
|
857
|
-
* staged file, which is what makes a key entered once usable in both.
|
|
858
|
-
*
|
|
859
|
-
* @param {string} name an env var name, e.g. 'OPENAI_API_KEY'
|
|
860
|
-
* @param {string} value the secret. Never returned, never logged.
|
|
861
|
-
* @param {object} [o]
|
|
862
|
-
* @param {string} [o.dir] defaults to aegisHome()
|
|
863
|
-
* @param {string} [o.file] an explicit path, for tests
|
|
864
|
-
* @param {object} [o.env] defaults to process.env
|
|
865
|
-
* @param {boolean} [o.apply=true] set it in `o.env`/process.env as well
|
|
866
|
-
* @returns {{ok:boolean, file:string, name:string, changed:boolean,
|
|
867
|
-
* created:boolean, replaced:boolean, mode:number, tightened:boolean,
|
|
868
|
-
* error:string}}
|
|
869
|
-
* `changed` is false when the file already held that exact value — a re-save
|
|
870
|
-
* of an unchanged key must not rewrite the file.
|
|
871
|
-
*/
|
|
872
|
-
function setEnvValue(name, value, o = {}) {
|
|
873
|
-
const env = o.env || process.env;
|
|
874
|
-
const file = o.file || envFileFor(o.dir);
|
|
875
|
-
const out = {
|
|
876
|
-
ok: false, file, name: String(name || ''), changed: false, created: false,
|
|
877
|
-
replaced: false, mode: 0, tightened: false, error: '',
|
|
878
|
-
};
|
|
879
|
-
|
|
880
|
-
if (!isWritableName(name)) {
|
|
881
|
-
out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
|
|
882
|
-
return out;
|
|
883
|
-
}
|
|
884
|
-
// The lock on the split: this file holds host keys, so a name that is not a
|
|
885
|
-
// host key is refused rather than written. Saying so is the point — the
|
|
886
|
-
// alternative (writing it and declining to load it) would recreate the exact
|
|
887
|
-
// state the split removed, with the value still on disk in the shared file.
|
|
888
|
-
if (isForeignSecret(name)) {
|
|
889
|
-
out.error = `refusing to write ${name} to ${ENV_FILE} — it is a production secret, not a host key;`
|
|
890
|
-
+ ` put it in ${SECRETS_FILE} (or use loadForeignSecrets)`;
|
|
891
|
-
return out;
|
|
892
|
-
}
|
|
893
|
-
const secret = String(value == null ? '' : value).trim();
|
|
894
|
-
if (!secret) {
|
|
895
|
-
out.error = `refusing to write an empty ${name}`;
|
|
896
|
-
return out;
|
|
897
|
-
}
|
|
898
|
-
// The one injection this file must not accept: a value carrying a newline
|
|
899
|
-
// would append a line, and the file is sourced by every host at start-up.
|
|
900
|
-
if (/[\r\n]/.test(String(value))) {
|
|
901
|
-
out.error = `refusing to write ${name} — the value contains a line break`;
|
|
902
|
-
return out;
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
let before = '';
|
|
906
|
-
let previousMode = 0;
|
|
907
|
-
out.created = true;
|
|
908
|
-
try {
|
|
909
|
-
before = fs.readFileSync(file, 'utf8');
|
|
910
|
-
out.created = false;
|
|
911
|
-
try {
|
|
912
|
-
previousMode = fs.statSync(file).mode & 0o777;
|
|
913
|
-
} catch { /* advisory */ }
|
|
914
|
-
} catch (e) {
|
|
915
|
-
if (e && e.code !== 'ENOENT') {
|
|
916
|
-
out.error = `could not read ${file}: ${e.code || e.message}`;
|
|
917
|
-
return out;
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
const aligned = String(before).replace(/\r\n/g, '\n');
|
|
922
|
-
if (!out.created && parseEnvText(aligned)[name] === secret) {
|
|
923
|
-
// Same key already stored: leave the file (its mtime, its mode) alone.
|
|
924
|
-
out.ok = true;
|
|
925
|
-
out.changed = false;
|
|
926
|
-
out.replaced = true;
|
|
927
|
-
out.mode = previousMode || SECRET_FILE_MODE;
|
|
928
|
-
if (o.apply !== false) {
|
|
929
|
-
env[name] = secret;
|
|
930
|
-
// Applied, and the file carries it: file-sourced, so an env-first reader
|
|
931
|
-
// treats it as the fallback it is (see isFromEnvFile).
|
|
932
|
-
sourcedFrom(env).set(name, secret);
|
|
933
|
-
}
|
|
934
|
-
return out;
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
const { text, replaced } = upsertEnvText(aligned, name, secret);
|
|
938
|
-
const tmp = `${file}.tmp-${process.pid}`;
|
|
939
|
-
try {
|
|
940
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
|
|
941
|
-
fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: SECRET_FILE_MODE });
|
|
942
|
-
// The rename carries the temp file's 0600 onto the destination, so a file
|
|
943
|
-
// that was group-readable ends up owner-only. Say so rather than tightening
|
|
944
|
-
// a file behind the user's back.
|
|
945
|
-
fs.chmodSync(tmp, SECRET_FILE_MODE);
|
|
946
|
-
fs.renameSync(tmp, file);
|
|
947
|
-
} catch (e) {
|
|
948
|
-
try { fs.unlinkSync(tmp); } catch {}
|
|
949
|
-
out.error = `could not write ${file}: ${e.code || e.message}`;
|
|
950
|
-
return out;
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
out.ok = true;
|
|
954
|
-
out.changed = true;
|
|
955
|
-
out.replaced = replaced;
|
|
956
|
-
out.mode = SECRET_FILE_MODE;
|
|
957
|
-
out.tightened =
|
|
958
|
-
platform.hasPosixModes() && !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
|
|
959
|
-
if (o.apply !== false) {
|
|
960
|
-
env[name] = secret;
|
|
961
|
-
// Just written to the file and applied here: file-sourced (see above).
|
|
962
|
-
sourcedFrom(env).set(name, secret);
|
|
963
|
-
}
|
|
964
|
-
return out;
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
/**
|
|
968
|
-
* Delete every definition of `name` from an env file's text, leaving every
|
|
969
|
-
* other line — comments, blanks, unrelated keys, their order, `export `
|
|
970
|
-
* prefixes — byte-identical.
|
|
971
|
-
*
|
|
972
|
-
* Removing a key is NOT the same as storing an empty one: `parseEnvText` reads
|
|
973
|
-
* `NAME=""` back as a present-but-empty variable, so an empty write leaves the
|
|
974
|
-
* old value's line in the file and a stale key can still win later. A remover
|
|
975
|
-
* has to delete the line.
|
|
976
|
-
*
|
|
977
|
-
* Pure, and exported for tests: like `upsertEnvText`, a bug here silently
|
|
978
|
-
* damages a file the user also edits by hand.
|
|
979
|
-
*
|
|
980
|
-
* @returns {{text:string, removed:number, changed:boolean}}
|
|
981
|
-
*/
|
|
982
|
-
function removeEnvText(text, name) {
|
|
983
|
-
const src = String(text == null ? '' : text);
|
|
984
|
-
const hadFinalNewline = src === '' ? true : src.endsWith('\n');
|
|
985
|
-
const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
|
|
986
|
-
// Zero lines for an empty source — see upsertEnvText. Here it is defensive
|
|
987
|
-
// rather than observable (a remover on an empty file writes nothing either
|
|
988
|
-
// way), but the two functions must split identically or a later change to one
|
|
989
|
-
// starts disagreeing with the other about what a line is.
|
|
990
|
-
const lines = src === '' ? [] : src.split('\n');
|
|
991
|
-
if (trailingBlank) lines.pop();
|
|
992
|
-
|
|
993
|
-
// Same definition matcher as upsertEnvText, so the two can never disagree
|
|
994
|
-
// about which lines count as this variable.
|
|
995
|
-
const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
|
|
996
|
-
const out = [];
|
|
997
|
-
let removed = 0;
|
|
998
|
-
for (const line of lines) {
|
|
999
|
-
if (re.test(line)) {
|
|
1000
|
-
removed += 1; // every definition goes, so duplicates cannot survive
|
|
1001
|
-
continue;
|
|
1002
|
-
}
|
|
1003
|
-
out.push(line);
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
let joined = out.join('\n');
|
|
1007
|
-
if (joined !== '' && (hadFinalNewline || trailingBlank)) joined += '\n';
|
|
1008
|
-
return { text: joined, removed, changed: removed > 0 };
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
/**
|
|
1012
|
-
* Remove one variable from `~/.aegiscode/.env` and from the live environment.
|
|
1013
|
-
*
|
|
1014
|
-
* The counterpart of `setEnvValue`, and the reason a provider key deleted in
|
|
1015
|
-
* the desktop app stops being in force: without it, the key survives in the
|
|
1016
|
-
* shared file and the desktop's own "removed" state disagrees with what the CLI
|
|
1017
|
-
* reads next session.
|
|
1018
|
-
*
|
|
1019
|
-
* A file that never mentioned the name is left untouched — no stray empty
|
|
1020
|
-
* variable, no rewritten mtime.
|
|
1021
|
-
*
|
|
1022
|
-
* @returns {{ok:boolean, file:string, name:string, changed:boolean,
|
|
1023
|
-
* removed:number, mode:number, error:string}}
|
|
1024
|
-
*/
|
|
1025
|
-
function clearEnvValue(name, o = {}) {
|
|
1026
|
-
const env = o.env || process.env;
|
|
1027
|
-
const file = o.file || envFileFor(o.dir);
|
|
1028
|
-
const out = {
|
|
1029
|
-
ok: false, file, name: String(name || ''), changed: false, removed: 0,
|
|
1030
|
-
mode: 0, error: '',
|
|
1031
|
-
};
|
|
1032
|
-
|
|
1033
|
-
if (!isWritableName(name)) {
|
|
1034
|
-
out.error = `refusing to clear "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
|
|
1035
|
-
return out;
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
let before = '';
|
|
1039
|
-
let missing = false;
|
|
1040
|
-
let previousMode = 0;
|
|
1041
|
-
try {
|
|
1042
|
-
before = fs.readFileSync(file, 'utf8');
|
|
1043
|
-
try {
|
|
1044
|
-
previousMode = fs.statSync(file).mode & 0o777;
|
|
1045
|
-
} catch { /* advisory */ }
|
|
1046
|
-
} catch (e) {
|
|
1047
|
-
if (e && e.code === 'ENOENT') missing = true;
|
|
1048
|
-
else {
|
|
1049
|
-
out.error = `could not read ${file}: ${e.code || e.message}`;
|
|
1050
|
-
return out;
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
|
|
1054
|
-
const { text, removed, changed } = missing
|
|
1055
|
-
? { text: '', removed: 0, changed: false }
|
|
1056
|
-
: removeEnvText(before, name);
|
|
1057
|
-
|
|
1058
|
-
if (!changed) {
|
|
1059
|
-
// Nothing in the file to remove. Still unset the live variable: the caller
|
|
1060
|
-
// asked for the key to stop being used, and a shell export would otherwise
|
|
1061
|
-
// keep serving it for the rest of this process.
|
|
1062
|
-
out.ok = true;
|
|
1063
|
-
out.mode = previousMode || SECRET_FILE_MODE;
|
|
1064
|
-
if (o.apply !== false) delete env[String(name)];
|
|
1065
|
-
return out;
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
const tmp = `${file}.tmp-${process.pid}`;
|
|
1069
|
-
try {
|
|
1070
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
|
|
1071
|
-
fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: SECRET_FILE_MODE });
|
|
1072
|
-
fs.chmodSync(tmp, SECRET_FILE_MODE);
|
|
1073
|
-
fs.renameSync(tmp, file);
|
|
1074
|
-
} catch (e) {
|
|
1075
|
-
try { fs.unlinkSync(tmp); } catch {}
|
|
1076
|
-
out.error = `could not write ${file}: ${e.code || e.message}`;
|
|
1077
|
-
return out;
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
out.ok = true;
|
|
1081
|
-
out.changed = true;
|
|
1082
|
-
out.removed = removed;
|
|
1083
|
-
out.mode = SECRET_FILE_MODE;
|
|
1084
|
-
if (o.apply !== false) delete env[String(name)];
|
|
1085
|
-
return out;
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
/**
|
|
1089
|
-
* Whether the key a route needs is already stored, and where that answer came
|
|
1090
|
-
* from. Read-only; the caller uses it to decide whether to prompt.
|
|
1091
|
-
*
|
|
1092
|
-
* `inFile` is the distinction that matters for the model picker: a key in the
|
|
1093
|
-
* process environment belongs to the shell that launched this host and is gone
|
|
1094
|
-
* next session (and invisible to the desktop), where a key in the file is the
|
|
1095
|
-
* durable, cross-host one.
|
|
1096
|
-
*
|
|
1097
|
-
* @returns {{name:string, present:boolean, inFile:boolean, source:string}}
|
|
1098
|
-
* `source` — 'shell' | 'file' | 'both' | 'none'
|
|
1099
|
-
*/
|
|
1100
|
-
function keyStatus(name, o = {}) {
|
|
1101
|
-
const env = o.env || process.env;
|
|
1102
|
-
const file = o.file || envFileFor(o.dir);
|
|
1103
|
-
const varName = String(name || '');
|
|
1104
|
-
const out = { name: varName, present: false, inFile: false, source: 'none' };
|
|
1105
|
-
if (!isWritableName(varName)) return out;
|
|
1106
|
-
|
|
1107
|
-
const raw = env[varName];
|
|
1108
|
-
const shell = typeof raw === 'string' && raw.trim() !== '';
|
|
1109
|
-
let file_ = false;
|
|
1110
|
-
try {
|
|
1111
|
-
const parsed = parseEnvText(fs.readFileSync(file, 'utf8'));
|
|
1112
|
-
file_ = typeof parsed[varName] === 'string' && parsed[varName].trim() !== '';
|
|
1113
|
-
} catch { /* absent or unreadable is simply "not in the file" */ }
|
|
1114
|
-
|
|
1115
|
-
out.present = shell || file_;
|
|
1116
|
-
out.inFile = file_;
|
|
1117
|
-
out.source = shell && file_ ? 'both' : shell ? 'shell' : file_ ? 'file' : 'none';
|
|
1118
|
-
return out;
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
/**
|
|
1122
|
-
* The env var a model id's key belongs in — the question the model picker asks
|
|
1123
|
-
* to know what to collect, and the reason one key is not collected twice.
|
|
1124
|
-
*
|
|
1125
|
-
* A byok id is `<provider>:<model>` and its key is that provider's variable. A
|
|
1126
|
-
* pooled id (`deepseek`, `anthropic-haiku`, `nexus-brain`, …) is served by the
|
|
1127
|
-
* pool, which holds the provider keys itself, so the credential such a route
|
|
1128
|
-
* needs is the AEGIS ACCOUNT key — one variable, `AEGIS_API_KEY`, however many
|
|
1129
|
-
* providers the picker lists. The Claude Code Pro class is neither: it bills
|
|
1130
|
-
* nobody through AEGIS and reaches no vendor API, so the credential its route
|
|
1131
|
-
* needs is the subscription's own OAuth token — `foreign: true` marks that this
|
|
1132
|
-
* is a `secrets.env` name (`setForeignSecret`/`resolveForeignSecret`), not a
|
|
1133
|
-
* `.env` one (`setEnvValue`/`keyStatus`), so `modelKeyPlan`/`modelKeyQueue`/
|
|
1134
|
-
* `storeModelKey` in cli/src/models.js know which store to read and write.
|
|
1135
|
-
*
|
|
1136
|
-
* @param {string} modelId
|
|
1137
|
-
* @param {string} [cls] 'byok' | 'aegis' | 'pro' | anything else
|
|
1138
|
-
* @returns {{env:string, provider:string, vendor:string, pooled:boolean, foreign?:boolean}}
|
|
1139
|
-
*/
|
|
1140
|
-
function keyForModelId(modelId, cls) {
|
|
1141
|
-
const id = String(modelId == null ? '' : modelId).trim();
|
|
1142
|
-
if (String(cls || '').toLowerCase() === 'pro') {
|
|
1143
|
-
return {
|
|
1144
|
-
env: 'CLAUDE_CODE_OAUTH_TOKEN', provider: '', vendor: '', pooled: false, foreign: true,
|
|
1145
|
-
};
|
|
1146
|
-
}
|
|
1147
|
-
const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
|
|
1148
|
-
if (byok && id.includes(':')) {
|
|
1149
|
-
const provider = id.slice(0, id.indexOf(':')).trim();
|
|
1150
|
-
return { env: envVarFor(provider), provider, vendor: provider, pooled: false };
|
|
1151
|
-
}
|
|
1152
|
-
// A pooled id is served by the pool, so the credential the ROUTE needs is the
|
|
1153
|
-
// account key — but the id may still NAME the vendor underneath it
|
|
1154
|
-
// (`deepseek`, `anthropic-haiku`, `openai-gpt4o-mini`). That vendor is what
|
|
1155
|
-
// `vendor` reports, and it is not the same question as `env`: it is the
|
|
1156
|
-
// provider key a user may also want on this machine, which the picker asks
|
|
1157
|
-
// for after the account key. `provider` stays '' for pooled on purpose — the
|
|
1158
|
-
// byok call path reads it as "which provider's settings row to address", and
|
|
1159
|
-
// a pooled row has none.
|
|
1160
|
-
return { env: ACCOUNT_ENV_VAR, provider: '', vendor: providerForModelId(id, cls), pooled: true };
|
|
1161
|
-
}
|
|
1162
|
-
|
|
1163
|
-
/**
|
|
1164
|
-
* Vendors whose slug is a namespace a model id may be spelled under.
|
|
1165
|
-
*
|
|
1166
|
-
* Deliberately a *table* and not a pattern: the derivation below is a claim that
|
|
1167
|
-
* a key for this vendor exists, so an id whose first segment is not on this list
|
|
1168
|
-
* derives NO vendor (and the picker asks only for the account key) rather than
|
|
1169
|
-
* inventing a variable name like `NEXUS_API_KEY` for the pool's own namespace.
|
|
1170
|
-
* The list is the platform's providers as its own BYOK catalog spells them
|
|
1171
|
-
* (aegis1 services/nexus_provider/catalog.py MODEL_CATALOG) plus the ids this
|
|
1172
|
-
* module already re-spells in ALIASES above — keep it in step with that catalog,
|
|
1173
|
-
* not with whatever vendor a user might mention.
|
|
1174
|
-
*/
|
|
1175
|
-
const VENDOR_SLUGS = Object.freeze([
|
|
1176
|
-
'openai',
|
|
1177
|
-
'anthropic',
|
|
1178
|
-
'deepseek',
|
|
1179
|
-
'google',
|
|
1180
|
-
'gemini',
|
|
1181
|
-
'groq',
|
|
1182
|
-
'mistral',
|
|
1183
|
-
'openrouter',
|
|
1184
|
-
'together',
|
|
1185
|
-
'together-ai',
|
|
1186
|
-
'xai',
|
|
1187
|
-
'x-ai',
|
|
1188
|
-
'grok',
|
|
1189
|
-
'huggingface',
|
|
1190
|
-
'fireworks',
|
|
1191
|
-
'voyage-ai',
|
|
1192
|
-
'azure-openai',
|
|
1193
|
-
]);
|
|
1194
|
-
|
|
1195
|
-
/** The multi-segment slugs, longest first, so `azure-openai-x` matches the full slug. */
|
|
1196
|
-
const VENDOR_COMPOUNDS = Object.freeze(
|
|
1197
|
-
VENDOR_SLUGS.filter((s) => s.includes('-')).sort((a, b) => b.length - a.length)
|
|
1198
|
-
);
|
|
1199
|
-
|
|
1200
|
-
/**
|
|
1201
|
-
* The vendor a model id names, or '' — `deepseek-flash` → `deepseek`,
|
|
1202
|
-
* `nexus-brain` → '', `deepseek:deepseek-v4-flash` → `deepseek`.
|
|
1203
|
-
*
|
|
1204
|
-
* The one question the picker needs to answer "is there a SECOND key worth
|
|
1205
|
-
* asking for on this row?" A pooled row is billed to the AEGIS account, so its
|
|
1206
|
-
* route needs the account key and nothing else — but when the row is named
|
|
1207
|
-
* after a vendor whose key this machine could hold (`deepseek`), asking for that
|
|
1208
|
-
* key too is what lets the account actually call the model instead of the pool
|
|
1209
|
-
* failing a turn with "no provider key". That is the gap this closes:
|
|
1210
|
-
* aegis-key present, models listed, and every turn still failing because the
|
|
1211
|
-
* vendor key the models route through was never collected.
|
|
1212
|
-
*
|
|
1213
|
-
* @param {string} modelId
|
|
1214
|
-
* @param {string} [cls] unused by the derivation; accepted so a caller can pass
|
|
1215
|
-
* the same (id, cls) pair it passes `keyForModelId` without branching.
|
|
1216
|
-
* @returns {string} the vendor slug, or '' when the id names none this module
|
|
1217
|
-
* knows a variable for.
|
|
1218
|
-
*/
|
|
1219
|
-
function providerForModelId(modelId, cls) { // eslint-disable-line no-unused-vars
|
|
1220
|
-
const id = String(modelId == null ? '' : modelId).trim().toLowerCase();
|
|
1221
|
-
if (!id) return '';
|
|
1222
|
-
if (id.includes(':')) return id.slice(0, id.indexOf(':')).trim();
|
|
1223
|
-
for (const slug of VENDOR_COMPOUNDS) {
|
|
1224
|
-
if (id === slug || id.startsWith(slug + '-')) return slug;
|
|
1225
|
-
}
|
|
1226
|
-
const first = id.split('-')[0];
|
|
1227
|
-
return VENDOR_SLUGS.includes(first) ? first : '';
|
|
1228
|
-
}
|
|
1229
|
-
|
|
1230
|
-
module.exports = {
|
|
1231
|
-
ENV_FILE,
|
|
1232
|
-
ALIASES,
|
|
1233
|
-
ACCOUNT_ENV_VAR,
|
|
1234
|
-
SECRET_FILE_MODE,
|
|
1235
|
-
envFileFor,
|
|
1236
|
-
envVarFor,
|
|
1237
|
-
parseEnvText,
|
|
1238
|
-
loadEnvFile,
|
|
1239
|
-
// Provenance of what loadEnvFile put in the environment: a value taken from
|
|
1240
|
-
// the FILE is a fallback, not an explicit export, and the env-first readers
|
|
1241
|
-
// (client/credentials.js) must be able to tell the two apart.
|
|
1242
|
-
isFromEnvFile,
|
|
1243
|
-
providerKeyFromEnv,
|
|
1244
|
-
// The floor a value must clear to be a credential at all, and the predicate
|
|
1245
|
-
// built on it — exported so a host can say WHY a row is keyless instead of
|
|
1246
|
-
// only that it is (see providerKeyFromEnv's `rejected`).
|
|
1247
|
-
MIN_CREDENTIAL_LEN,
|
|
1248
|
-
credentialLooksUsable,
|
|
1249
|
-
// The vendor half of "what key does this model id need": the account key is
|
|
1250
|
-
// the route's credential, this is the provider key underneath it.
|
|
1251
|
-
providerForModelId,
|
|
1252
|
-
VENDOR_SLUGS,
|
|
1253
|
-
isWritableName,
|
|
1254
|
-
quoteEnvValue,
|
|
1255
|
-
upsertEnvText,
|
|
1256
|
-
removeEnvText,
|
|
1257
|
-
setEnvValue,
|
|
1258
|
-
clearEnvValue,
|
|
1259
|
-
keyStatus,
|
|
1260
|
-
keyForModelId,
|
|
1261
|
-
// The split: the second file, the list that decides what may not be loaded,
|
|
1262
|
-
// and the reader a process that genuinely needs a billing token calls.
|
|
1263
|
-
SECRETS_FILE,
|
|
1264
|
-
FOREIGN_SECRET_NAMES,
|
|
1265
|
-
FOREIGN_SECRET_PREFIXES,
|
|
1266
|
-
isForeignSecret,
|
|
1267
|
-
secretEnvFileFor,
|
|
1268
|
-
loadForeignSecrets,
|
|
1269
|
-
foreignSecretValue,
|
|
1270
|
-
// The two the Claude Code Pro class reads/writes through — a value from
|
|
1271
|
-
// every place a user might have the token, and the one writer for the name.
|
|
1272
|
-
resolveForeignSecret,
|
|
1273
|
-
setForeignSecret,
|
|
1274
|
-
splitForeignSecrets,
|
|
1275
|
-
};
|
|
3
|
+
const e=require("node:fs"),t=require("node:path"),r=require("./credentials.js"),n=require("./platform.js"),o=".env",i="secrets.env",s=Object.freeze(["STRIPE_"]),c=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function a(e){const t=String(null==e?"":e).trim();return!!t&&(!!c.includes(t)||s.some((e=>t.startsWith(e))))}const l=384,d=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),u="AEGIS_API_KEY";function f(e){return t.join(e||r.aegisHome(),o)}function g(e){return t.join(e||r.aegisHome(),i)}function p(e){const t=String(e||"").trim().toLowerCase();if(!t)return"";const r=t.startsWith("byok:")?t.slice(5).trim():t;if(!r)return"";if(d[r])return d[r];const n=r.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const m=/^[A-Za-z0-9_+/.-]+$/,h=32;function E(e,t,r){let n=r;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:t};for(;t+1<e.length;){const r=e[t+1],o=r.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!m.test(o))break;if(!/^[ \t]/.test(r)&&(n.length<h||!m.test(n)))break;n+=o,t+=1}return{value:n,i:t}}function S(e){const t={},r=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<r.length;e++){const n=r[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=E(r,e,n.slice(o+1).trim());let c=s.value;e=s.i;const a=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,l=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(a)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(l)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}t[i]=c}return t}const y=new WeakMap;function _(e){let t=y.get(e);return t||(t=new Map,y.set(e,t)),t}function v(t,r={}){if(!a(t))return"";const n=r.file||g(r.dir);try{const r=S(e.readFileSync(n,"utf8"))[String(t)];return"string"==typeof r?r:""}catch{return""}}function I(r,n){e.mkdirSync(t.dirname(r),{recursive:!0,mode:448});const o=`${r}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(o,n,{mode:l}),e.renameSync(o,r),e.chmodSync(r,l)}function $(e){return"string"==typeof e&&e.trim().length>=8}function k(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function A(e){const t=String(e);return""===t?"":/[\s"'#\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function F(e,t,r){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${t}\\s*=`),a=[];let l=!1;for(const e of s){const n=c.exec(e);n?l||(a.push(`${n[1]}${t}=${A(r)}`),l=!0):a.push(e)}l||a.push(`${t}=${A(r)}`);let d=a.join("\n");return""!==d&&(o||i)&&(d+="\n"),{text:d,replaced:l}}function O(e,t){const r=String(null==e?"":e),n=""===r||r.endsWith("\n"),o=""!==r&&""===r.split("\n").slice(-1)[0],i=""===r?[]:r.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${t}\\s*=`),c=[];let a=0;for(const e of i)s.test(e)?a+=1:c.push(e);let l=c.join("\n");return""!==l&&(n||o)&&(l+="\n"),{text:l,removed:a,changed:a>0}}const P=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),T=Object.freeze(P.filter((e=>e.includes("-"))).sort(((e,t)=>t.length-e.length)));function R(e,t){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return"";if(r.includes(":"))return r.slice(0,r.indexOf(":")).trim();for(const e of T)if(r===e||r.startsWith(e+"-"))return e;const n=r.split("-")[0];return P.includes(n)?n:""}module.exports={ENV_FILE:o,ALIASES:d,ACCOUNT_ENV_VAR:u,SECRET_FILE_MODE:l,envFileFor:f,envVarFor:p,parseEnvText:S,loadEnvFile:function(t={}){const r=t.env||process.env,o=t.file||f(t.dir),i=_(r),s={ok:!1,file:o,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let c;try{c=e.readFileSync(o,"utf8")}catch(e){return s.reason=e&&"ENOENT"===e.code?"absent":"unreadable",s}try{const t=e.statSync(o);s.mode=511&t.mode,s.loose=n.hasPosixModes()&&0!=(63&t.mode)}catch{}const l=S(c);for(const[e,t]of Object.entries(l))a(e)?s.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,i.set(e,t),s.loaded.push(e)):s.kept.push(e);return s.ok=!0,s},isFromEnvFile:function(e,t,r={}){const n=r.env||process.env,o=y.get(n);return!(!o||!o.has(e)||void 0!==t&&o.get(e)!==String(t))},providerKeyFromEnv:function(e,t){const r=p(e);if(!r)return{key:"",env:"",rejected:null};const n=(t||process.env)[r],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:r,rejected:null}:$(o)?{key:o,env:r,rejected:null}:{key:"",env:r,rejected:`${r} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}},MIN_CREDENTIAL_LEN:8,credentialLooksUsable:$,providerForModelId:R,VENDOR_SLUGS:P,isWritableName:k,quoteEnvValue:A,upsertEnvText:F,removeEnvText:O,setEnvValue:function(r,s,c={}){const d=c.env||process.env,u=c.file||f(c.dir),g={ok:!1,file:u,name:String(r||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!k(r))return g.error=`refusing to write "${r}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,g;if(a(r))return g.error=`refusing to write ${r} to ${o} — it is a production secret, not a host key; put it in ${i} (or use loadForeignSecrets)`,g;const p=String(null==s?"":s).trim();if(!p)return g.error=`refusing to write an empty ${r}`,g;if(/[\r\n]/.test(String(s)))return g.error=`refusing to write ${r} — the value contains a line break`,g;let m="",h=0;g.created=!0;try{m=e.readFileSync(u,"utf8"),g.created=!1;try{h=511&e.statSync(u).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return g.error=`could not read ${u}: ${e.code||e.message}`,g}const E=String(m).replace(/\r\n/g,"\n");if(!g.created&&S(E)[r]===p)return g.ok=!0,g.changed=!1,g.replaced=!0,g.mode=h||l,!1!==c.apply&&(d[r]=p,_(d).set(r,p)),g;const{text:y,replaced:v}=F(E,r,p),I=`${u}.tmp-${process.pid}`;try{e.mkdirSync(t.dirname(u),{recursive:!0,mode:448}),e.writeFileSync(I,y,{encoding:"utf8",mode:l}),e.chmodSync(I,l),e.renameSync(I,u)}catch(t){try{e.unlinkSync(I)}catch{}return g.error=`could not write ${u}: ${t.code||t.message}`,g}return g.ok=!0,g.changed=!0,g.replaced=v,g.mode=l,g.tightened=n.hasPosixModes()&&!g.created&&0!==h&&0!=(63&h),!1!==c.apply&&(d[r]=p,_(d).set(r,p)),g},clearEnvValue:function(r,n={}){const o=n.env||process.env,i=n.file||f(n.dir),s={ok:!1,file:i,name:String(r||""),changed:!1,removed:0,mode:0,error:""};if(!k(r))return s.error=`refusing to clear "${r}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,s;let c="",a=!1,d=0;try{c=e.readFileSync(i,"utf8");try{d=511&e.statSync(i).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return s.error=`could not read ${i}: ${e.code||e.message}`,s;a=!0}const{text:u,removed:g,changed:p}=a?{text:"",removed:0,changed:!1}:O(c,r);if(!p)return s.ok=!0,s.mode=d||l,!1!==n.apply&&delete o[String(r)],s;const m=`${i}.tmp-${process.pid}`;try{e.mkdirSync(t.dirname(i),{recursive:!0,mode:448}),e.writeFileSync(m,u,{encoding:"utf8",mode:l}),e.chmodSync(m,l),e.renameSync(m,i)}catch(t){try{e.unlinkSync(m)}catch{}return s.error=`could not write ${i}: ${t.code||t.message}`,s}return s.ok=!0,s.changed=!0,s.removed=g,s.mode=l,!1!==n.apply&&delete o[String(r)],s},keyStatus:function(t,r={}){const n=r.env||process.env,o=r.file||f(r.dir),i=String(t||""),s={name:i,present:!1,inFile:!1,source:"none"};if(!k(i))return s;const c=n[i],a="string"==typeof c&&""!==c.trim();let l=!1;try{const t=S(e.readFileSync(o,"utf8"));l="string"==typeof t[i]&&""!==t[i].trim()}catch{}return s.present=a||l,s.inFile=l,s.source=a&&l?"both":a?"shell":l?"file":"none",s},keyForModelId:function(e,t){const r=String(null==e?"":e).trim();if("pro"===String(t||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(t||"").toLowerCase()||r.includes(":"))&&r.includes(":")){const e=r.slice(0,r.indexOf(":")).trim();return{env:p(e),provider:e,vendor:e,pooled:!1}}return{env:u,provider:"",vendor:R(r),pooled:!0}},SECRETS_FILE:i,FOREIGN_SECRET_NAMES:c,FOREIGN_SECRET_PREFIXES:s,isForeignSecret:a,secretEnvFileFor:g,loadForeignSecrets:function(t={}){const r=t.env||process.env,o=t.file||g(t.dir),i={ok:!1,file:o,loaded:[],reason:"",mode:0,loose:!1},s=Array.isArray(t.only)&&t.only.length?t.only.filter(a):null;let c;try{c=e.readFileSync(o,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}try{const t=e.statSync(o);i.mode=511&t.mode,i.loose=n.hasPosixModes()&&0!=(63&t.mode)}catch{}const l=S(c);for(const[e,t]of Object.entries(l))s&&!s.includes(e)||(r[e]=t,i.loaded.push(e));return i.ok=!0,i},foreignSecretValue:v,resolveForeignSecret:function(t,r={}){if(!a(t))return"";const n=r.env||process.env,o=n&&n[t];if("string"==typeof o&&o.trim())return o.trim();const i=v(t,r);if(i&&i.trim())return i.trim();try{const n=S(e.readFileSync(f(r.dir),"utf8"))[String(t)];return"string"==typeof n?n.trim():""}catch{return""}},setForeignSecret:function(t,r,s={}){const c=s.file||g(s.dir),d={ok:!1,file:c,name:String(t||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!k(t))return d.error=`refusing to write "${t}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,d;if(!a(t))return d.error=`refusing to write ${t} to ${i} — it is a host credential, not a foreign secret; use setEnvValue (${o}) instead`,d;const u=String(null==r?"":r).trim();if(!u)return d.error=`refusing to write an empty ${t}`,d;if(/[\r\n]/.test(String(r)))return d.error=`refusing to write ${t} — the value contains a line break`,d;let f="",p=0;d.created=!0;try{f=e.readFileSync(c,"utf8"),d.created=!1;try{p=511&e.statSync(c).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return d.error=`could not read ${c}: ${e.code||e.message}`,d}const m=String(f).replace(/\r\n/g,"\n");if(!d.created&&S(m)[t]===u)return d.ok=!0,d.changed=!1,d.replaced=!0,d.mode=p||l,d;const{text:h,replaced:E}=F(m,t,u);try{I(c,h)}catch(e){return d.error=`could not write ${c}: ${e.code||e.message}`,d}return d.ok=!0,d.changed=!0,d.replaced=E,d.mode=l,d.tightened=n.hasPosixModes()&&!d.created&&0!==p&&0!=(63&p),d},splitForeignSecrets:function(t={}){const r=t.env||process.env,n=t.file||f(t.dir),o=t.secretsFile||g(t.dir),i=!0===t.apply,s={ok:!1,moved:[],kept:[],envFile:n,secretsFile:o,apply:i};let c;try{c=e.readFileSync(n,"utf8")}catch(e){return s.reason=e&&"ENOENT"===e.code?"absent":"unreadable",s}const l=S(c),d=Object.keys(l).filter(a).sort();if(!d.length)return s.ok=!0,s;let u="";try{u=e.readFileSync(o,"utf8")}catch{}const p=S(u);for(const e of d)Object.prototype.hasOwnProperty.call(p,e)?s.kept.push(e):(u=F(u,e,l[e]).text,s.moved.push(e));if(i){for(const e of d)c=O(c,e).text;s.moved.length&&I(o,u),I(n,c);for(const e of d)r[e]===l[e]&&delete r[e]}else s.moved.length&&(s.secretsFile=o);return s.ok=!0,s}};
|