envpkt 0.8.0 → 0.9.1

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/README.md CHANGED
@@ -141,6 +141,29 @@ value = "info"
141
141
  purpose = "Application log verbosity"
142
142
  ```
143
143
 
144
+ ### Aliases
145
+
146
+ When a consumer hardcodes a different env var name than the one you govern
147
+ canonically, use `from_key` to expose the same value under a second name —
148
+ without duplicating the secret:
149
+
150
+ ```toml
151
+ [secret.API_KEY]
152
+ service = "stripe"
153
+ expires = "2027-01-15"
154
+ rotation_url = "https://dashboard.stripe.com/apikeys"
155
+
156
+ # Same governed value, under a legacy name some consumer expects
157
+ [secret.STRIPE_SECRET_KEY]
158
+ from_key = "secret.API_KEY"
159
+ ```
160
+
161
+ Both names are injected at boot, both appear in audit output, and expiration
162
+ tracking lives on the target — an alias is healthy iff its target is. Same
163
+ pattern works for `[env.*]`. Cross-type aliasing (secret → env) is rejected
164
+ at load time. See [TOML Schema → Aliases](https://envpkt.dev/reference/toml-schema/#aliases)
165
+ for the full rules.
166
+
144
167
  See [`examples/`](./examples/) for more configurations.
145
168
 
146
169
  ## Sealed Packets
@@ -150,21 +173,22 @@ Sealed packets embed age-encrypted secret values directly in `envpkt.toml`. This
150
173
  ### Setup
151
174
 
152
175
  ```bash
153
- # Generate an age keypair
154
- age-keygen -o identity.txt
155
- # public key: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p
176
+ # Generate an age keypair — writes to ~/.envpkt/<project>-key.txt and updates envpkt.toml
177
+ envpkt keygen
156
178
  ```
157
179
 
158
- Add the public key to your config and the identity file to `.gitignore`:
180
+ This writes `[identity]` with `name`, `recipient`, and `key_file` to your `envpkt.toml`. Add the key file to `.gitignore`:
159
181
 
160
182
  ```toml
161
183
  [identity]
162
184
  name = "my-agent"
163
185
  recipient = "age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p"
164
- key_file = "identity.txt"
186
+ key_file = "~/.envpkt/my-agent-key.txt"
165
187
  ```
166
188
 
167
- The `key_file` path supports `~` expansion and environment variables (`$VAR`, `${VAR}`), so you can use paths like `~/keys/identity.txt` or `$KEYS_DIR/identity.txt`. Relative paths are resolved from the config file's directory. When omitted, envpkt falls back to `ENVPKT_AGE_KEY_FILE` env var, then `~/.envpkt/age-key.txt`.
189
+ `envpkt keygen` defaults to a **project-specific path** (`~/.envpkt/<project>-key.txt`), so separate projects never collide. For multi-environment projects (e.g. `prod.envpkt.toml` + `dev.envpkt.toml`), each config gets its own key automatically. Pass `--global` to use the shared `~/.envpkt/age-key.txt` path instead.
190
+
191
+ The `key_file` path supports `~` expansion and environment variables (`$VAR`, `${VAR}`). Relative paths are resolved from the config file's directory. When omitted, envpkt falls back to `ENVPKT_AGE_KEY_FILE` env var, then `~/.envpkt/age-key.txt` — but it's best to set `key_file` explicitly so the config tells you which key it needs.
168
192
 
169
193
  ### Seal
170
194
 
package/dist/cli.js CHANGED
@@ -54,10 +54,28 @@ const classifySecret = (key, meta, fnoxKeys, staleWarningDays, requireExpiration
54
54
  purpose,
55
55
  created: Option(meta.created),
56
56
  expires: Option(meta.expires),
57
- issues: List(issues)
57
+ issues: List(issues),
58
+ alias_of: Option(void 0)
58
59
  };
59
60
  };
60
- const computeAudit = (config, fnoxKeys, today) => {
61
+ /**
62
+ * Build a SecretHealth row for an alias entry. Status is inherited from the
63
+ * target; metadata (purpose, tags) comes from the alias entry itself where
64
+ * set, otherwise falls through to the target so operators see context.
65
+ */
66
+ const classifyAlias = (key, meta, targetHealth, targetRef) => ({
67
+ key,
68
+ service: targetHealth.service,
69
+ status: targetHealth.status,
70
+ days_remaining: targetHealth.days_remaining,
71
+ rotation_url: targetHealth.rotation_url,
72
+ purpose: meta.purpose !== void 0 ? Option(meta.purpose) : targetHealth.purpose,
73
+ created: targetHealth.created,
74
+ expires: targetHealth.expires,
75
+ issues: List([]),
76
+ alias_of: Option(targetRef)
77
+ });
78
+ const computeAudit = (config, fnoxKeys, today, aliasTable) => {
61
79
  const now = today ?? /* @__PURE__ */ new Date();
62
80
  const lifecycle = config.lifecycle ?? {};
63
81
  const staleWarningDays = lifecycle.stale_warning_days ?? 90;
@@ -65,9 +83,31 @@ const computeAudit = (config, fnoxKeys, today) => {
65
83
  const requireService = lifecycle.require_service ?? false;
66
84
  const keys = fnoxKeys ?? /* @__PURE__ */ new Set();
67
85
  const secretEntries = config.secret ?? {};
68
- const metaKeys = new Set(Object.keys(secretEntries));
69
- const secrets = List(Object.entries(secretEntries).map(([key, meta]) => classifySecret(key, meta, keys, staleWarningDays, requireExpiration, requireService, now)));
70
- const orphaned = keys.size > 0 ? [...metaKeys].filter((k) => !keys.has(k)).length : 0;
86
+ const nonAliasEntries = Object.entries(secretEntries).filter(([, meta]) => meta.from_key === void 0);
87
+ const aliasEntries = Object.entries(secretEntries).filter(([, meta]) => meta.from_key !== void 0);
88
+ const nonAliasMetaKeys = new Set(nonAliasEntries.map(([k]) => k));
89
+ const nonAliasHealth = nonAliasEntries.map(([key, meta]) => classifySecret(key, meta, keys, staleWarningDays, requireExpiration, requireService, now));
90
+ const healthByKey = new Map(nonAliasHealth.map((h) => [h.key, h]));
91
+ const aliasHealth = aliasEntries.map(([key, meta]) => {
92
+ const targetKey = (aliasTable?.entries.get(`secret.${key}`))?.targetKey;
93
+ const targetHealth = targetKey !== void 0 ? healthByKey.get(targetKey) : void 0;
94
+ const targetRef = meta.from_key ?? (targetKey !== void 0 ? `secret.${targetKey}` : "");
95
+ if (!targetHealth) return {
96
+ key,
97
+ service: Option(meta.service),
98
+ status: "missing",
99
+ days_remaining: Option(void 0),
100
+ rotation_url: Option(meta.rotation_url),
101
+ purpose: Option(meta.purpose),
102
+ created: Option(meta.created),
103
+ expires: Option(meta.expires),
104
+ issues: List(["Alias target not resolvable"]),
105
+ alias_of: Option(targetRef)
106
+ };
107
+ return classifyAlias(key, meta, targetHealth, targetRef);
108
+ });
109
+ const secrets = List([...nonAliasHealth, ...aliasHealth]);
110
+ const orphaned = keys.size > 0 ? [...nonAliasMetaKeys].filter((k) => !keys.has(k)).length : 0;
71
111
  const total = secrets.size;
72
112
  const expired = secrets.count((s) => s.status === "expired");
73
113
  const missing = secrets.count((s) => s.status === "missing");
@@ -75,6 +115,7 @@ const computeAudit = (config, fnoxKeys, today) => {
75
115
  const expiring_soon = secrets.count((s) => s.status === "expiring_soon");
76
116
  const stale = secrets.count((s) => s.status === "stale");
77
117
  const healthy = secrets.count((s) => s.status === "healthy");
118
+ const aliases = aliasHealth.length;
78
119
  return {
79
120
  status: Cond.of().when(expired > 0 || missing > 0, "critical").elseWhen(expiring_soon > 0 || stale > 0 || missing_metadata > 0, "degraded").else("healthy"),
80
121
  secrets,
@@ -86,6 +127,7 @@ const computeAudit = (config, fnoxKeys, today) => {
86
127
  missing,
87
128
  missing_metadata,
88
129
  orphaned,
130
+ aliases,
89
131
  identity: config.identity
90
132
  };
91
133
  };
@@ -93,13 +135,17 @@ const computeEnvAudit = (config, env = process.env) => {
93
135
  const envEntries = config.env ?? {};
94
136
  const entries = Object.entries(envEntries).map(([key, entry]) => {
95
137
  const currentValue = env[key];
96
- const status = Cond.of().when(currentValue === void 0, "missing").elseWhen(currentValue !== entry.value, "overridden").else("default");
138
+ const effectiveDefault = entry.from_key !== void 0 ? (() => {
139
+ const targetKey = /^env\.(.+)$/.exec(entry.from_key)?.[1];
140
+ return (targetKey !== void 0 ? envEntries[targetKey] : void 0)?.value ?? "";
141
+ })() : entry.value ?? "";
97
142
  return {
98
143
  key,
99
- defaultValue: entry.value,
144
+ defaultValue: effectiveDefault,
100
145
  currentValue,
101
- status,
102
- purpose: entry.purpose
146
+ status: Cond.of().when(currentValue === void 0, "missing").elseWhen(currentValue !== effectiveDefault, "overridden").else("default"),
147
+ purpose: entry.purpose,
148
+ alias_of: Option(entry.from_key)
103
149
  };
104
150
  });
105
151
  return {
@@ -158,6 +204,7 @@ const SecretMetaSchema = Type.Object({
158
204
  model_hint: Type.Optional(Type.String({ description: "Suggested model or tier for this credential" })),
159
205
  source: Type.Optional(Type.String({ description: "Where the secret value originates (e.g. 'vault', 'ci')" })),
160
206
  encrypted_value: Type.Optional(Type.String({ description: "Age-encrypted secret value (armored ciphertext, safe to commit)" })),
207
+ from_key: Type.Optional(Type.String({ description: "Reference another entry (format: 'secret.<KEY>') whose resolved value this alias reuses. Mutually exclusive with encrypted_value." })),
161
208
  required: Type.Optional(Type.Boolean({ description: "Whether this secret is required for operation" })),
162
209
  tags: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Key-value tags for grouping and filtering" }))
163
210
  }, { description: "Metadata about a single secret" });
@@ -182,7 +229,8 @@ const CallbackConfigSchema = Type.Object({
182
229
  }, { description: "Automation callbacks for lifecycle events" });
183
230
  const ToolsConfigSchema = Type.Record(Type.String(), Type.Unknown(), { description: "Tool integration configuration — open namespace for third-party extensions" });
184
231
  const EnvMetaSchema = Type.Object({
185
- value: Type.String({ description: "Default value for this environment variable" }),
232
+ value: Type.Optional(Type.String({ description: "Default value for this environment variable. Optional when from_key is set; required otherwise." })),
233
+ from_key: Type.Optional(Type.String({ description: "Reference another entry (format: 'env.<KEY>') whose resolved value this alias reuses. Mutually exclusive with value." })),
186
234
  purpose: Type.Optional(Type.String({ description: "Why this env var exists" })),
187
235
  comment: Type.Optional(Type.String({ description: "Free-form annotation or note" })),
188
236
  tags: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Key-value tags for grouping and filtering" }))
@@ -822,17 +870,151 @@ const readFnoxConfig = (path) => Try(() => readFileSync(path, "utf-8")).fold((er
822
870
  /** Extract the set of secret key names from a parsed fnox config */
823
871
  const extractFnoxKeys = (config) => new Set(Object.keys(config.secrets));
824
872
  //#endregion
873
+ //#region src/core/alias.ts
874
+ const ALIAS_REF_RE = /^(secret|env)\.(.+)$/;
875
+ const parseRef = (raw) => {
876
+ const match = ALIAS_REF_RE.exec(raw);
877
+ if (!match) return Option(void 0);
878
+ const kind = match[1];
879
+ const key = match[2];
880
+ if (!key) return Option(void 0);
881
+ return Option({
882
+ kind,
883
+ key
884
+ });
885
+ };
886
+ const validateOneSecret = (key, meta, secretEntries) => {
887
+ if (meta.from_key === void 0) return Right(Option(void 0));
888
+ const ref = meta.from_key;
889
+ if (meta.encrypted_value !== void 0) return Left({
890
+ _tag: "AliasValueConflict",
891
+ key,
892
+ kind: "secret",
893
+ field: "encrypted_value"
894
+ });
895
+ return parseRef(ref).fold(() => Left({
896
+ _tag: "AliasInvalidSyntax",
897
+ key,
898
+ kind: "secret",
899
+ value: ref
900
+ }), (parsed) => {
901
+ if (parsed.kind !== "secret") return Left({
902
+ _tag: "AliasCrossType",
903
+ key,
904
+ kind: "secret",
905
+ targetKind: parsed.kind
906
+ });
907
+ if (parsed.key === key) return Left({
908
+ _tag: "AliasSelfReference",
909
+ key: `secret.${key}`
910
+ });
911
+ return Option(secretEntries[parsed.key]).fold(() => Left({
912
+ _tag: "AliasTargetMissing",
913
+ key: `secret.${key}`,
914
+ target: ref
915
+ }), (target) => {
916
+ if (target.from_key !== void 0) return Left({
917
+ _tag: "AliasChained",
918
+ key: `secret.${key}`,
919
+ target: ref
920
+ });
921
+ return Right(Option({
922
+ kind: "secret",
923
+ targetKind: "secret",
924
+ targetKey: parsed.key
925
+ }));
926
+ });
927
+ });
928
+ };
929
+ const validateOneEnv = (key, meta, envEntries) => {
930
+ if (meta.from_key === void 0) return Right(Option(void 0));
931
+ const ref = meta.from_key;
932
+ if (meta.value !== void 0) return Left({
933
+ _tag: "AliasValueConflict",
934
+ key,
935
+ kind: "env",
936
+ field: "value"
937
+ });
938
+ return parseRef(ref).fold(() => Left({
939
+ _tag: "AliasInvalidSyntax",
940
+ key,
941
+ kind: "env",
942
+ value: ref
943
+ }), (parsed) => {
944
+ if (parsed.kind !== "env") return Left({
945
+ _tag: "AliasCrossType",
946
+ key,
947
+ kind: "env",
948
+ targetKind: parsed.kind
949
+ });
950
+ if (parsed.key === key) return Left({
951
+ _tag: "AliasSelfReference",
952
+ key: `env.${key}`
953
+ });
954
+ return Option(envEntries[parsed.key]).fold(() => Left({
955
+ _tag: "AliasTargetMissing",
956
+ key: `env.${key}`,
957
+ target: ref
958
+ }), (target) => {
959
+ if (target.from_key !== void 0) return Left({
960
+ _tag: "AliasChained",
961
+ key: `env.${key}`,
962
+ target: ref
963
+ });
964
+ return Right(Option({
965
+ kind: "env",
966
+ targetKind: "env",
967
+ targetKey: parsed.key
968
+ }));
969
+ });
970
+ });
971
+ };
972
+ /**
973
+ * Validate all `from_key` references in a resolved config. Produces an
974
+ * AliasTable mapping each alias to its target, or an AliasError describing
975
+ * the first failure.
976
+ *
977
+ * Rules:
978
+ * - Ref must be "secret.<KEY>" or "env.<KEY>"
979
+ * - Target must exist in the same resolved config
980
+ * - Target must be the same type (secret→secret, env→env only)
981
+ * - Target must not itself be a from_key entry (single hop only)
982
+ * - Self-reference is rejected
983
+ * - An alias entry cannot also carry a value field (encrypted_value for
984
+ * secrets, value for env)
985
+ */
986
+ const validateAliases = (config) => {
987
+ const secretEntries = config.secret ?? {};
988
+ const envEntries = config.env ?? {};
989
+ const entries = /* @__PURE__ */ new Map();
990
+ const secretResults = Object.entries(secretEntries).map(([key, meta]) => [key, validateOneSecret(key, meta, secretEntries)]);
991
+ for (const [key, result] of secretResults) {
992
+ const outcome = result.fold((err) => err, (opt) => opt.orUndefined());
993
+ if (outcome === void 0) continue;
994
+ if ("_tag" in outcome) return Left(outcome);
995
+ entries.set(`secret.${key}`, outcome);
996
+ }
997
+ const envResults = Object.entries(envEntries).map(([key, meta]) => [key, validateOneEnv(key, meta, envEntries)]);
998
+ for (const [key, result] of envResults) {
999
+ const outcome = result.fold((err) => err, (opt) => opt.orUndefined());
1000
+ if (outcome === void 0) continue;
1001
+ if ("_tag" in outcome) return Left(outcome);
1002
+ entries.set(`env.${key}`, outcome);
1003
+ }
1004
+ return Right({ entries });
1005
+ };
1006
+ //#endregion
825
1007
  //#region src/core/keygen.ts
826
1008
  /** Resolve the age identity file path: ENVPKT_AGE_KEY_FILE env var > ~/.envpkt/age-key.txt */
827
1009
  const resolveKeyPath = () => process.env["ENVPKT_AGE_KEY_FILE"] ?? join(homedir(), ".envpkt", "age-key.txt");
828
- /** Generate an age keypair and write to disk */
1010
+ /** Generate an age keypair and write to disk. Refuses to overwrite if the file already exists. */
829
1011
  const generateKeypair = (options) => {
830
1012
  if (!ageAvailable()) return Left({
831
1013
  _tag: "AgeNotFound",
832
1014
  message: "age-keygen CLI not found on PATH. Install age: https://github.com/FiloSottile/age"
833
1015
  });
834
1016
  const outputPath = options?.outputPath ?? resolveKeyPath();
835
- if (existsSync(outputPath) && !options?.force) return Left({
1017
+ if (existsSync(outputPath)) return Left({
836
1018
  _tag: "KeyExists",
837
1019
  path: outputPath
838
1020
  });
@@ -1089,7 +1271,7 @@ const looksLikeSecret = (value) => {
1089
1271
  };
1090
1272
  const checkEnvMisclassification = (config) => {
1091
1273
  const envEntries = config.env ?? {};
1092
- return Object.entries(envEntries).filter(([, entry]) => looksLikeSecret(entry.value)).map(([key]) => `[env.${key}] value looks like a secret — consider moving to [secret.${key}]`);
1274
+ return Object.entries(envEntries).filter(([, entry]) => entry.value !== void 0 && looksLikeSecret(entry.value)).map(([key]) => `[env.${key}] value looks like a secret — consider moving to [secret.${key}]`);
1093
1275
  };
1094
1276
  /** Programmatic boot — returns Either<BootError, BootResult> */
1095
1277
  const bootSafe = (options) => {
@@ -1097,26 +1279,29 @@ const bootSafe = (options) => {
1097
1279
  const inject = opts.inject !== false;
1098
1280
  const failOnExpired = opts.failOnExpired !== false;
1099
1281
  const warnOnly = opts.warnOnly ?? false;
1100
- return resolveAndLoad(opts).flatMap(({ config, configPath, configDir, configSource }) => {
1282
+ return resolveAndLoad(opts).flatMap(({ config, configPath, configDir, configSource }) => validateAliases(config).fold((err) => Left(err), (aliasTable) => {
1101
1283
  const secretEntries = config.secret ?? {};
1102
- const metaKeys = Object.keys(secretEntries);
1103
- const hasSealedValues = metaKeys.some((k) => !!secretEntries[k].encrypted_value);
1284
+ const envEntries = config.env ?? {};
1285
+ const nonAliasSecretEntries = Object.fromEntries(Object.entries(secretEntries).filter(([, meta]) => meta.from_key === void 0));
1286
+ const aliasSecretKeys = Object.keys(secretEntries).filter((k) => secretEntries[k].from_key !== void 0);
1287
+ const nonAliasEnvEntries = Object.entries(envEntries).filter(([, meta]) => meta.from_key === void 0);
1288
+ const aliasEnvKeys = Object.keys(envEntries).filter((k) => envEntries[k].from_key !== void 0);
1289
+ const nonAliasMetaKeys = Object.keys(nonAliasSecretEntries);
1290
+ const hasSealedValues = nonAliasMetaKeys.some((k) => !!nonAliasSecretEntries[k].encrypted_value);
1104
1291
  const identityKeyResult = resolveIdentityKey(config, configDir);
1105
1292
  const identityKey = identityKeyResult.fold(() => Option(void 0), (k) => k);
1106
1293
  if (identityKeyResult.isLeft() && !hasSealedValues) return identityKeyResult.fold((err) => Left(err), () => Left({
1107
1294
  _tag: "ReadError",
1108
1295
  message: "unexpected"
1109
1296
  }));
1110
- const audit = computeAudit(config, detectFnoxKeys(configDir));
1297
+ const audit = computeAudit(config, detectFnoxKeys(configDir), void 0, aliasTable);
1111
1298
  return checkExpiration(audit, failOnExpired, warnOnly).map((warnings) => {
1112
1299
  const secrets = {};
1113
1300
  const injected = [];
1114
1301
  const skipped = [];
1115
1302
  warnings.push(...checkEnvMisclassification(config));
1116
- const envEntries = config.env ?? {};
1117
- const envEntriesArr = Object.entries(envEntries);
1118
- const envDefaults = Object.fromEntries(envEntriesArr.flatMap(([key, entry]) => Option(process.env[key]).fold(() => [[key, entry.value]], () => [])));
1119
- const overridden = envEntriesArr.flatMap(([key]) => Option(process.env[key]).fold(() => [], () => [key]));
1303
+ const envDefaults = Object.fromEntries(nonAliasEnvEntries.flatMap(([key, entry]) => Option(process.env[key]).fold(() => entry.value !== void 0 ? [[key, entry.value]] : [], () => [])));
1304
+ const overridden = nonAliasEnvEntries.flatMap(([key]) => Option(process.env[key]).fold(() => [], () => [key]));
1120
1305
  if (inject) Object.entries(envDefaults).forEach(([key, value]) => {
1121
1306
  process.env[key] = value;
1122
1307
  });
@@ -1125,7 +1310,7 @@ const bootSafe = (options) => {
1125
1310
  if (hasSealedValues) identityFilePath.fold(() => {
1126
1311
  warnings.push("Sealed values found but no identity file available for decryption");
1127
1312
  }, (idPath) => {
1128
- unsealSecrets(secretEntries, idPath).fold((err) => {
1313
+ unsealSecrets(nonAliasSecretEntries, idPath).fold((err) => {
1129
1314
  warnings.push(`Sealed value decryption failed: ${err.message}`);
1130
1315
  }, (unsealed) => {
1131
1316
  const unsealedEntries = Object.entries(unsealed);
@@ -1134,7 +1319,7 @@ const bootSafe = (options) => {
1134
1319
  unsealedEntries.map(([key]) => key).forEach((key) => sealedKeys.add(key));
1135
1320
  });
1136
1321
  });
1137
- const remainingKeys = metaKeys.filter((k) => !sealedKeys.has(k));
1322
+ const remainingKeys = nonAliasMetaKeys.filter((k) => !sealedKeys.has(k));
1138
1323
  if (remainingKeys.length > 0) if (fnoxAvailable()) fnoxExport(opts.profile, identityKey.orUndefined()).fold((err) => {
1139
1324
  warnings.push(`fnox export failed: ${err.message}`);
1140
1325
  skipped.push(...remainingKeys);
@@ -1152,9 +1337,34 @@ const bootSafe = (options) => {
1152
1337
  else warnings.push("fnox not available — unsealed secrets could not be resolved");
1153
1338
  skipped.push(...remainingKeys);
1154
1339
  }
1155
- if (inject) Object.entries(secrets).forEach(([key, value]) => {
1156
- process.env[key] = value;
1340
+ aliasSecretKeys.forEach((aliasKey) => {
1341
+ const entry = aliasTable.entries.get(`secret.${aliasKey}`);
1342
+ if (!entry) return;
1343
+ const targetValue = secrets[entry.targetKey];
1344
+ if (targetValue !== void 0) {
1345
+ secrets[aliasKey] = targetValue;
1346
+ injected.push(aliasKey);
1347
+ } else skipped.push(aliasKey);
1348
+ });
1349
+ aliasEnvKeys.forEach((aliasKey) => {
1350
+ const entry = aliasTable.entries.get(`env.${aliasKey}`);
1351
+ if (!entry) return;
1352
+ if (process.env[aliasKey] !== void 0) {
1353
+ overridden.push(aliasKey);
1354
+ return;
1355
+ }
1356
+ const targetEntry = envEntries[entry.targetKey];
1357
+ if (targetEntry?.value === void 0) return;
1358
+ envDefaults[aliasKey] = process.env[entry.targetKey] ?? targetEntry.value;
1157
1359
  });
1360
+ if (inject) {
1361
+ Object.entries(envDefaults).forEach(([key, value]) => {
1362
+ process.env[key] ??= value;
1363
+ });
1364
+ Object.entries(secrets).forEach(([key, value]) => {
1365
+ process.env[key] = value;
1366
+ });
1367
+ }
1158
1368
  return {
1159
1369
  audit,
1160
1370
  injected,
@@ -1167,7 +1377,7 @@ const bootSafe = (options) => {
1167
1377
  configSource
1168
1378
  };
1169
1379
  });
1170
- });
1380
+ }));
1171
1381
  };
1172
1382
  //#endregion
1173
1383
  //#region src/core/patterns.ts
@@ -1883,14 +2093,27 @@ const envScan = (env, options) => {
1883
2093
  low_confidence
1884
2094
  };
1885
2095
  };
2096
+ const parseAliasRef = (raw, expectedKind) => {
2097
+ const match = /^(secret|env)\.(.+)$/.exec(raw);
2098
+ if (!match) return void 0;
2099
+ if (match[1] !== expectedKind) return void 0;
2100
+ return match[2];
2101
+ };
1886
2102
  /** Bidirectional drift detection between config and live environment */
1887
2103
  const envCheck = (config, env) => {
1888
2104
  const secretEntries = config.secret ?? {};
1889
2105
  const metaKeys = Object.keys(secretEntries);
1890
2106
  const trackedSet = new Set(metaKeys);
2107
+ const isSecretPresent = (key) => {
2108
+ if (env[key] !== void 0 && env[key] !== "") return true;
2109
+ const meta = secretEntries[key];
2110
+ if (meta?.from_key === void 0) return false;
2111
+ const targetKey = parseAliasRef(meta.from_key, "secret");
2112
+ return targetKey !== void 0 && env[targetKey] !== void 0 && env[targetKey] !== "";
2113
+ };
1891
2114
  const secretDriftEntries = metaKeys.map((key) => {
1892
2115
  const meta = secretEntries[key];
1893
- const present = env[key] !== void 0 && env[key] !== "";
2116
+ const present = isSecretPresent(key);
1894
2117
  return {
1895
2118
  envVar: key,
1896
2119
  service: Option(meta.service),
@@ -1899,12 +2122,19 @@ const envCheck = (config, env) => {
1899
2122
  };
1900
2123
  });
1901
2124
  const envDefaults = config.env ?? {};
2125
+ const isEnvPresent = (key) => {
2126
+ if (env[key] !== void 0 && env[key] !== "") return true;
2127
+ const meta = envDefaults[key];
2128
+ if (meta?.from_key === void 0) return false;
2129
+ const targetKey = parseAliasRef(meta.from_key, "env");
2130
+ return targetKey !== void 0 && env[targetKey] !== void 0 && env[targetKey] !== "";
2131
+ };
1902
2132
  const envDefaultEntries = Object.keys(envDefaults).filter((key) => {
1903
2133
  if (trackedSet.has(key)) return false;
1904
2134
  trackedSet.add(key);
1905
2135
  return true;
1906
2136
  }).map((key) => {
1907
- const present = env[key] !== void 0 && env[key] !== "";
2137
+ const present = isEnvPresent(key);
1908
2138
  return {
1909
2139
  envVar: key,
1910
2140
  service: Option(void 0),
@@ -2193,7 +2423,9 @@ const runEnvExport = (options) => {
2193
2423
  if (boot.overridden.length > 0) loadConfig(boot.configPath).fold(() => {}, (config) => {
2194
2424
  const envEntries = config.env ?? {};
2195
2425
  boot.overridden.forEach((key) => {
2196
- if (key in envEntries) console.log(`export ${key}='${shellEscape(envEntries[key].value)}'`);
2426
+ if (!(key in envEntries)) return;
2427
+ const value = envEntries[key].value ?? process.env[key] ?? "";
2428
+ console.log(`export ${key}='${shellEscape(value)}'`);
2197
2429
  });
2198
2430
  });
2199
2431
  Object.entries(boot.secrets).forEach(([key, value]) => {
@@ -2738,15 +2970,26 @@ const tildeShorten = (p) => {
2738
2970
  };
2739
2971
  /** Derive a default identity name from the config path's parent directory */
2740
2972
  const deriveIdentityName = (configPath) => basename(dirname(resolve(configPath)));
2973
+ /**
2974
+ * Derive a project-specific key path from the config path.
2975
+ * - `envpkt.toml` → `~/.envpkt/<dir>-key.txt`
2976
+ * - `prod.envpkt.toml` → `~/.envpkt/<dir>-prod-key.txt`
2977
+ * - `foo.envpkt.toml` → `~/.envpkt/<dir>-foo-key.txt`
2978
+ */
2979
+ const deriveKeyPath = (configPath) => {
2980
+ const abs = resolve(configPath);
2981
+ const dir = basename(dirname(abs));
2982
+ const stem = basename(abs).replace(/\.envpkt\.toml$/, "").replace(/\.toml$/, "");
2983
+ const name = stem === "envpkt" || stem === "" ? dir : `${dir}-${stem}`;
2984
+ return join(homedir(), ".envpkt", `${name}-key.txt`);
2985
+ };
2741
2986
  const runKeygen = (options) => {
2742
- const outputPath = options.output ?? resolveKeyPath();
2743
- generateKeypair({
2744
- force: options.force,
2745
- outputPath
2746
- }).fold((err) => {
2987
+ const configPath = resolve(options.config ?? join(process.cwd(), "envpkt.toml"));
2988
+ generateKeypair({ outputPath: options.output ?? (options.global ? resolveKeyPath() : deriveKeyPath(configPath)) }).fold((err) => {
2747
2989
  if (err._tag === "KeyExists") {
2748
2990
  console.error(`${YELLOW}Warning:${RESET} Identity file already exists: ${CYAN}${err.path}${RESET}`);
2749
- console.error(`${DIM}Use --force to overwrite.${RESET}`);
2991
+ console.error(`${DIM}To replace it: remove the file first, then re-run keygen.${RESET}`);
2992
+ console.error(`${DIM}To use a different path: pass -o <path>.${RESET}`);
2750
2993
  process.exit(1);
2751
2994
  }
2752
2995
  console.error(formatError(err));
@@ -2755,7 +2998,6 @@ const runKeygen = (options) => {
2755
2998
  console.log(`${GREEN}Generated${RESET} age identity: ${CYAN}${identityPath}${RESET}`);
2756
2999
  console.log(`${BOLD}Recipient:${RESET} ${recipient}`);
2757
3000
  console.log("");
2758
- const configPath = resolve(options.config ?? join(process.cwd(), "envpkt.toml"));
2759
3001
  if (existsSync(configPath)) {
2760
3002
  const name = deriveIdentityName(configPath);
2761
3003
  const keyFile = tildeShorten(identityPath);
@@ -2959,6 +3201,7 @@ const handleGetPacketHealth = (args) => {
2959
3201
  status: s.status,
2960
3202
  days_remaining: s.days_remaining.fold(() => null, (d) => d),
2961
3203
  rotation_url: s.rotation_url.fold(() => null, (u) => u),
3204
+ alias_of: s.alias_of.fold(() => null, (a) => a),
2962
3205
  issues: s.issues.toArray()
2963
3206
  }));
2964
3207
  return textResult(JSON.stringify({
@@ -2970,6 +3213,7 @@ const handleGetPacketHealth = (args) => {
2970
3213
  expired: audit.expired,
2971
3214
  stale: audit.stale,
2972
3215
  missing: audit.missing,
3216
+ aliases: audit.aliases,
2973
3217
  secrets: secretDetails
2974
3218
  }, null, 2));
2975
3219
  };
@@ -2999,11 +3243,30 @@ const handleGetSecretMeta = (args) => {
2999
3243
  const loaded = loadConfigForTool(configPathArg(args));
3000
3244
  if (!loaded.ok) return loaded.result;
3001
3245
  const { config } = loaded;
3002
- return Option((config.secret ?? {})[key]).fold(() => errorResult(`Secret not found: ${key}`), (meta) => {
3003
- const { encrypted_value: _, ...safeMeta } = meta;
3246
+ const secretEntries = config.secret ?? {};
3247
+ return Option(secretEntries[key]).fold(() => errorResult(`Secret not found: ${key}`), (meta) => {
3248
+ const { encrypted_value: _, from_key: fromKey, ...rest } = meta;
3249
+ if (fromKey !== void 0) {
3250
+ const targetKey = /^secret\.(.+)$/.exec(fromKey)?.[1];
3251
+ const target = targetKey !== void 0 ? secretEntries[targetKey] : void 0;
3252
+ if (target) {
3253
+ const { encrypted_value: __, from_key: ___, ...targetRest } = target;
3254
+ return textResult(JSON.stringify({
3255
+ key,
3256
+ ...targetRest,
3257
+ ...rest,
3258
+ alias_of: fromKey
3259
+ }, null, 2));
3260
+ }
3261
+ return textResult(JSON.stringify({
3262
+ key,
3263
+ ...rest,
3264
+ alias_of: fromKey
3265
+ }, null, 2));
3266
+ }
3004
3267
  return textResult(JSON.stringify({
3005
3268
  key,
3006
- ...safeMeta
3269
+ ...rest
3007
3270
  }, null, 2));
3008
3271
  });
3009
3272
  };
@@ -3661,7 +3924,7 @@ program.name("envpkt").description("Credential lifecycle and fleet management fo
3661
3924
  program.command("init").description("Initialize a new envpkt.toml in the current directory").option("--from-fnox [path]", "Scaffold from fnox.toml (optionally specify path)").option("--catalog <path>", "Path to shared secret catalog").option("--identity", "Include [identity] section").option("--name <name>", "Identity name (requires --identity)").option("--capabilities <caps>", "Comma-separated capabilities (requires --identity)").option("--expires <date>", "Credential expiration YYYY-MM-DD (requires --identity)").option("--force", "Overwrite existing envpkt.toml").action((options) => {
3662
3925
  runInit(process.cwd(), options);
3663
3926
  });
3664
- program.command("keygen").description("Generate an age keypair for sealing secrets — run this before `seal` if you don't have a key yet").option("-c, --config <path>", "Path to envpkt.toml (updates identity.recipient if found)").option("--force", "Overwrite existing identity file").option("-o, --output <path>", "Output path for identity file (default: ~/.envpkt/age-key.txt)").action((options) => {
3927
+ program.command("keygen").description("Generate an age keypair for sealing secrets — run this before `seal` if you don't have a key yet").option("-c, --config <path>", "Path to envpkt.toml (updates identity.recipient if found)").option("-o, --output <path>", "Output path for identity file (default: ~/.envpkt/<project>-key.txt)").option("--global", "Write key to the shared default path (~/.envpkt/age-key.txt) instead of a project-specific one").action((options) => {
3665
3928
  runKeygen(options);
3666
3929
  });
3667
3930
  program.command("audit").description("Audit credential health from envpkt.toml (use --strict in CI pipelines to gate deploys)").option("-c, --config <path>", "Path to envpkt.toml").option("--format <format>", "Output format: table | json | minimal", "table").option("--expiring <days>", "Show secrets expiring within N days", parseInt).option("--status <status>", "Filter by status: healthy | expiring_soon | expired | stale | missing").option("--strict", "Exit non-zero on any non-healthy secret").option("--all", "Show both secrets and env defaults").option("--env-only", "Show only env defaults (drift detection)").option("--sealed", "Show only secrets with encrypted_value").option("--external", "Show only secrets without encrypted_value").action((options) => {