aegiscode 7.0.6 → 7.0.8

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.
@@ -215,6 +215,59 @@ function envVarFor(providerId) {
215
215
  return name ? `${name}_API_KEY` : '';
216
216
  }
217
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
+
218
271
  /**
219
272
  * Parse dotenv text. Deliberately small and total: an unparseable line is
220
273
  * skipped rather than thrown, so one bad line cannot stop the rest of the file
@@ -224,18 +277,28 @@ function envVarFor(providerId) {
224
277
  * ` # comment` on an unquoted value. A double-quoted value is unescaped (`\"`,
225
278
  * `\\`) because that is what `quoteEnvValue` writes and what dotenv readers do;
226
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.
227
287
  */
228
288
  function parseEnvText(text) {
229
289
  const out = {};
230
- for (const raw of String(text == null ? '' : text).split(/\r?\n/)) {
231
- const line = raw.trim();
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();
232
293
  if (!line || line.startsWith('#')) continue;
233
294
  const eq = line.indexOf('=');
234
295
  if (eq <= 0) continue;
235
296
  let name = line.slice(0, eq).trim();
236
297
  if (name.startsWith('export ')) name = name.slice('export '.length).trim();
237
298
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
238
- let value = line.slice(eq + 1).trim();
299
+ const folded = foldWrappedEnvValue(lines, i, line.slice(eq + 1).trim());
300
+ let value = folded.value;
301
+ i = folded.i;
239
302
  const doubleQuoted = value.startsWith('"') && value.endsWith('"') && value.length >= 2;
240
303
  const singleQuoted = value.startsWith("'") && value.endsWith("'") && value.length >= 2;
241
304
  if (doubleQuoted) {
@@ -447,6 +510,45 @@ function foreignSecretValue(name, o = {}) {
447
510
  }
448
511
  }
449
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
+
450
552
  /** Write a secrets file with the right permissions and no half-written state. */
451
553
  function writeSecretFile(file, text) {
452
554
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
@@ -458,6 +560,97 @@ function writeSecretFile(file, text) {
458
560
  fs.chmodSync(file, SECRET_FILE_MODE);
459
561
  }
460
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
+
461
654
  /**
462
655
  * Move every foreign secret out of `~/.aegiscode/.env` into `secrets.env`.
463
656
  *
@@ -532,6 +725,31 @@ function splitForeignSecrets(o = {}) {
532
725
  return out;
533
726
  }
534
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
+
535
753
  /**
536
754
  * The BYOK key for a provider out of the environment, if the env file (or the
537
755
  * shell) supplies one. Returns '' when it does not — the encrypted store then
@@ -539,10 +757,27 @@ function splitForeignSecrets(o = {}) {
539
757
  */
540
758
  function providerKeyFromEnv(providerId, env) {
541
759
  const name = envVarFor(providerId);
542
- if (!name) return { key: '', env: '' };
760
+ if (!name) return { key: '', env: '', rejected: null };
543
761
  const raw = (env || process.env)[name];
544
762
  const key = typeof raw === 'string' ? raw.trim() : '';
545
- return { key, env: name };
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 };
546
781
  }
547
782
 
548
783
  /** A variable name this module is willing to write. */
@@ -891,14 +1126,24 @@ function keyStatus(name, o = {}) {
891
1126
  * pooled id (`deepseek`, `anthropic-haiku`, `nexus-brain`, …) is served by the
892
1127
  * pool, which holds the provider keys itself, so the credential such a route
893
1128
  * needs is the AEGIS ACCOUNT key — one variable, `AEGIS_API_KEY`, however many
894
- * providers the picker lists.
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.
895
1135
  *
896
1136
  * @param {string} modelId
897
- * @param {string} [cls] 'byok' | 'aegis' | anything else
898
- * @returns {{env:string, provider:string, vendor:string, pooled:boolean}}
1137
+ * @param {string} [cls] 'byok' | 'aegis' | 'pro' | anything else
1138
+ * @returns {{env:string, provider:string, vendor:string, pooled:boolean, foreign?:boolean}}
899
1139
  */
900
1140
  function keyForModelId(modelId, cls) {
901
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
+ }
902
1147
  const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
903
1148
  if (byok && id.includes(':')) {
904
1149
  const provider = id.slice(0, id.indexOf(':')).trim();
@@ -996,6 +1241,11 @@ module.exports = {
996
1241
  // (client/credentials.js) must be able to tell the two apart.
997
1242
  isFromEnvFile,
998
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,
999
1249
  // The vendor half of "what key does this model id need": the account key is
1000
1250
  // the route's credential, this is the provider key underneath it.
1001
1251
  providerForModelId,
@@ -1017,5 +1267,9 @@ module.exports = {
1017
1267
  secretEnvFileFor,
1018
1268
  loadForeignSecrets,
1019
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,
1020
1274
  splitForeignSecrets,
1021
1275
  };