@gadicc/loom 1.35.3 → 1.36.0

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.
Files changed (103) hide show
  1. package/README.md +56 -0
  2. package/THIRD_PARTY_NOTICES.md +12 -9
  3. package/esm/src/cli/externalSkills.d.ts.map +1 -1
  4. package/esm/src/cli/externalSkills.js +25 -20
  5. package/esm/src/cli/mod.d.ts +72 -1
  6. package/esm/src/cli/mod.d.ts.map +1 -1
  7. package/esm/src/cli/mod.js +771 -36
  8. package/esm/src/cli/projectSkills.d.ts +10 -3
  9. package/esm/src/cli/projectSkills.d.ts.map +1 -1
  10. package/esm/src/cli/projectSkills.js +173 -49
  11. package/esm/src/cli/vercelBuildEnv.d.ts +28 -0
  12. package/esm/src/cli/vercelBuildEnv.d.ts.map +1 -1
  13. package/esm/src/cli/vercelBuildEnv.js +120 -30
  14. package/esm/src/next/secrets/mod.d.ts +108 -0
  15. package/esm/src/next/secrets/mod.d.ts.map +1 -0
  16. package/esm/src/next/secrets/mod.js +176 -0
  17. package/esm/src/secrets/encoding.d.ts +32 -0
  18. package/esm/src/secrets/encoding.d.ts.map +1 -0
  19. package/esm/src/secrets/encoding.js +87 -0
  20. package/esm/src/secrets/errors.d.ts +45 -0
  21. package/esm/src/secrets/errors.d.ts.map +1 -0
  22. package/esm/src/secrets/errors.js +39 -0
  23. package/esm/src/secrets/fingerprint.d.ts +43 -0
  24. package/esm/src/secrets/fingerprint.d.ts.map +1 -0
  25. package/esm/src/secrets/fingerprint.js +87 -0
  26. package/esm/src/secrets/frame.d.ts +34 -0
  27. package/esm/src/secrets/frame.d.ts.map +1 -0
  28. package/esm/src/secrets/frame.js +86 -0
  29. package/esm/src/secrets/keyring.d.ts +62 -0
  30. package/esm/src/secrets/keyring.d.ts.map +1 -0
  31. package/esm/src/secrets/keyring.js +160 -0
  32. package/esm/src/secrets/legacy.d.ts +60 -0
  33. package/esm/src/secrets/legacy.d.ts.map +1 -0
  34. package/esm/src/secrets/legacy.js +147 -0
  35. package/esm/src/secrets/maintenance.d.ts +173 -0
  36. package/esm/src/secrets/maintenance.d.ts.map +1 -0
  37. package/esm/src/secrets/maintenance.js +315 -0
  38. package/esm/src/secrets/mod.d.ts +6 -0
  39. package/esm/src/secrets/mod.d.ts.map +1 -0
  40. package/esm/src/secrets/mod.js +5 -0
  41. package/esm/src/secrets/secrets.d.ts +192 -0
  42. package/esm/src/secrets/secrets.d.ts.map +1 -0
  43. package/esm/src/secrets/secrets.js +528 -0
  44. package/package.json +50 -2
  45. package/script/src/cli/externalSkills.d.ts.map +1 -1
  46. package/script/src/cli/externalSkills.js +25 -20
  47. package/script/src/cli/mod.d.ts +72 -1
  48. package/script/src/cli/mod.d.ts.map +1 -1
  49. package/script/src/cli/mod.js +772 -33
  50. package/script/src/cli/projectSkills.d.ts +10 -3
  51. package/script/src/cli/projectSkills.d.ts.map +1 -1
  52. package/script/src/cli/projectSkills.js +173 -49
  53. package/script/src/cli/vercelBuildEnv.d.ts +28 -0
  54. package/script/src/cli/vercelBuildEnv.d.ts.map +1 -1
  55. package/script/src/cli/vercelBuildEnv.js +121 -30
  56. package/script/src/next/secrets/mod.d.ts +108 -0
  57. package/script/src/next/secrets/mod.d.ts.map +1 -0
  58. package/script/src/next/secrets/mod.js +218 -0
  59. package/script/src/secrets/encoding.d.ts +32 -0
  60. package/script/src/secrets/encoding.d.ts.map +1 -0
  61. package/script/src/secrets/encoding.js +95 -0
  62. package/script/src/secrets/errors.d.ts +45 -0
  63. package/script/src/secrets/errors.d.ts.map +1 -0
  64. package/script/src/secrets/errors.js +45 -0
  65. package/script/src/secrets/fingerprint.d.ts +43 -0
  66. package/script/src/secrets/fingerprint.d.ts.map +1 -0
  67. package/script/src/secrets/fingerprint.js +92 -0
  68. package/script/src/secrets/frame.d.ts +34 -0
  69. package/script/src/secrets/frame.d.ts.map +1 -0
  70. package/script/src/secrets/frame.js +91 -0
  71. package/script/src/secrets/keyring.d.ts +62 -0
  72. package/script/src/secrets/keyring.d.ts.map +1 -0
  73. package/script/src/secrets/keyring.js +202 -0
  74. package/script/src/secrets/legacy.d.ts +60 -0
  75. package/script/src/secrets/legacy.d.ts.map +1 -0
  76. package/script/src/secrets/legacy.js +186 -0
  77. package/script/src/secrets/maintenance.d.ts +173 -0
  78. package/script/src/secrets/maintenance.d.ts.map +1 -0
  79. package/script/src/secrets/maintenance.js +323 -0
  80. package/script/src/secrets/mod.d.ts +6 -0
  81. package/script/src/secrets/mod.d.ts.map +1 -0
  82. package/script/src/secrets/mod.js +24 -0
  83. package/script/src/secrets/secrets.d.ts +192 -0
  84. package/script/src/secrets/secrets.d.ts.map +1 -0
  85. package/script/src/secrets/secrets.js +532 -0
  86. package/skills/loom/SKILL.md +74 -222
  87. package/skills/loom/references/dependency-upgrades.md +26 -0
  88. package/skills/loom/references/local-development.md +157 -0
  89. package/skills/loom/references/release-safety.md +118 -0
  90. package/skills/loom/references/release-trusted-sources.md +55 -0
  91. package/skills/loom/references/tools-and-skills.md +83 -0
  92. package/skills/loom-api-keys/SKILL.md +1 -1
  93. package/skills/loom-auth/SKILL.md +7 -60
  94. package/skills/loom-auth/references/secrets-and-rotation.md +61 -0
  95. package/skills/loom-db/SKILL.md +4 -79
  96. package/skills/loom-files/SKILL.md +4 -2
  97. package/skills/loom-files/references/provider-configuration.md +142 -0
  98. package/skills/loom-jobs/SKILL.md +9 -8
  99. package/skills/loom-lingui/SKILL.md +5 -3
  100. package/skills/loom-secrets/SKILL.md +252 -0
  101. package/skills/loom-torvalds-review/SKILL.md +9 -6
  102. package/skills/loom-torvalds-review/references/context-profiles.md +2 -1
  103. package/skills/upgrade-deps/SKILL.md +15 -7
@@ -63,6 +63,10 @@ exports.setupGithubMigrationCredential = setupGithubMigrationCredential;
63
63
  exports.setupGithubVercelRelease = setupGithubVercelRelease;
64
64
  exports.initProject = initProject;
65
65
  exports.addFeature = addFeature;
66
+ exports.generateSecretsKey = generateSecretsKey;
67
+ exports.fingerprintSecretsKey = fingerprintSecretsKey;
68
+ exports.activateSecretsKey = activateSecretsKey;
69
+ exports.retireSecretsKey = retireSecretsKey;
66
70
  exports.integrateApiKeysJobs = integrateApiKeysJobs;
67
71
  exports.configureApiKeyRetention = configureApiKeyRetention;
68
72
  exports.addSkills = addSkills;
@@ -90,6 +94,10 @@ const managedFiles_js_1 = require("./managedFiles.js");
90
94
  const legacyManagedOutputs_js_1 = require("./legacyManagedOutputs.js");
91
95
  const betterAuth_js_1 = require("../apiKeys/betterAuth.js");
92
96
  const retention_js_1 = require("../apiKeys/retention.js");
97
+ const mod_js_1 = require("../next/secrets/mod.js");
98
+ const encoding_js_1 = require("../secrets/encoding.js");
99
+ const fingerprint_js_1 = require("../secrets/fingerprint.js");
100
+ const keyring_js_1 = require("../secrets/keyring.js");
93
101
  const projectSkills_js_1 = require("./projectSkills.js");
94
102
  const migrationEnv_js_1 = require("./migrationEnv.js");
95
103
  const vercelBuildEnv_js_1 = require("./vercelBuildEnv.js");
@@ -209,6 +217,12 @@ const managedSkills = [
209
217
  relativePackagePath: "skills/loom-lingui",
210
218
  skillName: "loom-lingui",
211
219
  },
220
+ {
221
+ featureKey: "secrets",
222
+ label: "loom secrets skill",
223
+ relativePackagePath: "skills/loom-secrets",
224
+ skillName: "loom-secrets",
225
+ },
212
226
  ];
213
227
  const featureDefinitions = [
214
228
  {
@@ -243,6 +257,10 @@ const featureDefinitions = [
243
257
  key: "pwa",
244
258
  description: "Shared Serwist PWA worker, provider lifecycle, update prompts, and build wiring.",
245
259
  },
260
+ {
261
+ key: "secrets",
262
+ description: "Reversible secrets at rest with versioned, fingerprint-verified keys.",
263
+ },
246
264
  ];
247
265
  const DB_DEFAULT_DEPENDENCIES = {
248
266
  "@neondatabase/serverless": "^1.1.0",
@@ -2141,6 +2159,31 @@ function mergeApiKeyAuditSchemaConfig(dbConfig, schemaConfig) {
2141
2159
  hashManagedSchemaText(buildApiKeyAuditSchemaText(merged)),
2142
2160
  };
2143
2161
  }
2162
+ function getSecretsConfig(framework, featureConfig) {
2163
+ const moduleRoot = framework.srcDir ? "src/" : "";
2164
+ return {
2165
+ modules: {
2166
+ secretsModule: featureConfig?.modules?.secretsModule ??
2167
+ `${moduleRoot}secrets.ts`,
2168
+ locationsModule: featureConfig?.modules?.locationsModule ??
2169
+ `${moduleRoot}secretLocations.ts`,
2170
+ },
2171
+ env: {
2172
+ keyPrefix: featureConfig?.env?.keyPrefix ??
2173
+ keyring_js_1.DEFAULT_SECRETS_KEY_ENV_PREFIX,
2174
+ activeKeyName: featureConfig?.env?.activeKeyName ??
2175
+ keyring_js_1.DEFAULT_SECRETS_ACTIVE_KEY_ENV,
2176
+ },
2177
+ // Recorded by `loom secrets`; passed through unvalidated so `loom check`
2178
+ // can report a hand-edited list instead of this getter hiding it.
2179
+ keys: {
2180
+ production: featureConfig?.keys?.production ?? [],
2181
+ ...(featureConfig?.keys?.preview !== undefined
2182
+ ? { preview: featureConfig.keys.preview }
2183
+ : {}),
2184
+ },
2185
+ };
2186
+ }
2144
2187
  function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
2145
2188
  const appRoot = framework.srcDir ? "src/app" : "app";
2146
2189
  const apiKeysRoot = framework.srcDir
@@ -4585,7 +4628,16 @@ async function checkPnpm11Compatibility(cwd, packageJson, npmrcText) {
4585
4628
  warnings: major === null || major < 11 ? findings : [],
4586
4629
  };
4587
4630
  }
4588
- function getSkillsContext(packageJson, manifest) {
4631
+ async function getSkillsContext(cwd, packageJson, manifest) {
4632
+ const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
4633
+ const dependencyConfig = tooling.dependencies.config;
4634
+ if (dependencyConfig !== "package.json") {
4635
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, dependencyConfig));
4636
+ if (text === null) {
4637
+ throw new Error(`Missing dependency config: ${dependencyConfig}`);
4638
+ }
4639
+ packageJson = (0, projectTooling_js_1.denoConfigAsPackageJson)((0, projectTooling_js_1.parseJsonc)(text, dependencyConfig));
4640
+ }
4589
4641
  return {
4590
4642
  activeFeatureKeys: new Set(manifest
4591
4643
  ? Object.entries(manifest.features)
@@ -8135,11 +8187,14 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
8135
8187
  ok: false,
8136
8188
  };
8137
8189
  }
8138
- async function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
8190
+ /**
8191
+ * Reads one line from the terminal, writing the question to stderr. A secret
8192
+ * is read in raw mode so it is never echoed. Refuses when stdin is not a
8193
+ * terminal, with the caller's explanation of what to do instead.
8194
+ */
8195
+ async function promptForTerminalValue(question, secret, messages) {
8139
8196
  if (!node_process_1.default.stdin.isTTY) {
8140
- throw new Error(context === "MinIO"
8141
- ? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
8142
- : "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.");
8197
+ throw new Error(messages.notInteractive);
8143
8198
  }
8144
8199
  if (!secret) {
8145
8200
  const input = (0, promises_2.createInterface)({
@@ -8171,7 +8226,7 @@ async function promptForLocalFilesValue(question, secret = false, context = "Min
8171
8226
  }
8172
8227
  if (character === "\u0003") {
8173
8228
  stdin.off("data", onData);
8174
- rejectPromise(new Error(`${context} setup was cancelled.`));
8229
+ rejectPromise(new Error(messages.cancelled));
8175
8230
  return;
8176
8231
  }
8177
8232
  if (character === "\u007f" || character === "\b") {
@@ -8190,6 +8245,14 @@ async function promptForLocalFilesValue(question, secret = false, context = "Min
8190
8245
  stdin.pause();
8191
8246
  }
8192
8247
  }
8248
+ function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
8249
+ return promptForTerminalValue(question, secret, {
8250
+ cancelled: `${context} setup was cancelled.`,
8251
+ notInteractive: context === "MinIO"
8252
+ ? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
8253
+ : "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.",
8254
+ });
8255
+ }
8193
8256
  function minioHostEnv(env, endpoint, accessKey, secretKey) {
8194
8257
  const url = new URL(endpoint);
8195
8258
  url.username = accessKey;
@@ -10668,6 +10731,216 @@ async function applyAuthFeature(cwd, framework, manifest, activate) {
10668
10731
  }
10669
10732
  return { changedFiles, notes };
10670
10733
  }
10734
+ /**
10735
+ * Whether a failed Git command failed because there is no repository, in
10736
+ * which case no file is tracked. The message is matched because Git uses the
10737
+ * same exit status (128) for failures that are not an answer at all.
10738
+ */
10739
+ function isNotAGitRepository(result) {
10740
+ return result.code !== 0 && /not a git repository/i.test(result.stderr);
10741
+ }
10742
+ function secretsModuleTemplate(config) {
10743
+ return `import { createNextSecrets } from "@gadicc/loom/next/secrets";
10744
+
10745
+ import loomManifest from "${toRelativeImportPath(config.modules.secretsModule, "loom.json")}";
10746
+
10747
+ const config = loomManifest.features.secrets.config;
10748
+
10749
+ // loom.json records the fingerprint of every key a deployed environment is
10750
+ // expected to hold, so a key that differs from the saved copy is refused.
10751
+ export const secrets = createNextSecrets({
10752
+ expectedKeys: config.keys,
10753
+ variables: config.env,
10754
+ });
10755
+
10756
+ // Declare one purpose per kind of secret, beside the code that uses it:
10757
+ //
10758
+ // export const thingSecret = secrets.purpose("area.thing");
10759
+ //
10760
+ // A purpose name and its binding are permanent: a value sealed under them can
10761
+ // never be opened under different ones.
10762
+ `;
10763
+ }
10764
+ function secretLocationsModuleTemplate() {
10765
+ return `import { defineSecretLocations } from "@gadicc/loom/secrets/maintenance";
10766
+
10767
+ // Every column that holds a sealed string must be declared here. The
10768
+ // maintenance operations (report, verify, reseal) only reach declared
10769
+ // locations, so an undeclared column is never re-encrypted and keeps its old
10770
+ // key in use without anyone noticing.
10771
+ export const secretLocations = defineSecretLocations([]);
10772
+ `;
10773
+ }
10774
+ /**
10775
+ * The normalised config laid over what loom.json already holds, so that a
10776
+ * property Loom does not know (under `config` or one of its sections) is
10777
+ * kept instead of being dropped by a rewrite.
10778
+ */
10779
+ function mergeSecretsConfig(existing, config) {
10780
+ const current = isJsonObject(existing) ? existing : {};
10781
+ const section = (name) => ({
10782
+ ...(isJsonObject(current[name]) ? current[name] : {}),
10783
+ ...config[name],
10784
+ });
10785
+ return {
10786
+ ...current,
10787
+ modules: section("modules"),
10788
+ env: section("env"),
10789
+ keys: section("keys"),
10790
+ };
10791
+ }
10792
+ /**
10793
+ * Gives a new checkout a working development key: writes a random key and the
10794
+ * pointer to gitignored `.env.local` when it holds neither. An existing
10795
+ * variable is never changed, and the key is never returned or reported.
10796
+ */
10797
+ async function ensureLocalSecretsKey(cwd, config, commandRunner) {
10798
+ const changedFiles = [];
10799
+ const { activeKeyName, keyPrefix } = config.env;
10800
+ const envPath = (0, node_path_1.join)(cwd, ".env.local");
10801
+ const envText = await readTextIfExists(envPath);
10802
+ const existingName = [...readEnvAssignments(envText ?? "").keys()].find((name) => name === activeKeyName || name.startsWith(keyPrefix));
10803
+ if (existingName !== undefined) {
10804
+ return {
10805
+ changedFiles,
10806
+ notes: [
10807
+ `No development secrets key was generated: .env.local already sets ${existingName}, and Loom never changes an existing secrets variable.`,
10808
+ ],
10809
+ };
10810
+ }
10811
+ const tracked = await commandRunner("git", [
10812
+ "ls-files",
10813
+ "--error-unmatch",
10814
+ "--",
10815
+ ".env.local",
10816
+ ], { cwd, stdio: "pipe" });
10817
+ if (tracked.code === 0) {
10818
+ return {
10819
+ changedFiles,
10820
+ notes: [
10821
+ "No development secrets key was written: .env.local is tracked by Git. Remove it from the index, then rerun `loom add secrets`.",
10822
+ ],
10823
+ };
10824
+ }
10825
+ // Exit 1 is Git's answer that the file is untracked, and outside a
10826
+ // repository nothing can be tracked. Any other failure is not an answer.
10827
+ if (tracked.code !== 1 && !isNotAGitRepository(tracked)) {
10828
+ return {
10829
+ changedFiles,
10830
+ notes: [
10831
+ "No development secrets key was written: Git could not be asked whether .env.local is tracked. Rerun `loom add secrets` once `git ls-files` works in this project.",
10832
+ ],
10833
+ };
10834
+ }
10835
+ let envFileExists = true;
10836
+ try {
10837
+ if ((await (0, promises_1.lstat)(envPath)).isSymbolicLink()) {
10838
+ return {
10839
+ changedFiles,
10840
+ notes: [
10841
+ "No development secrets key was written: .env.local is a symlink, and Loom will not write a key through it.",
10842
+ ],
10843
+ };
10844
+ }
10845
+ }
10846
+ catch (error) {
10847
+ if (!isNodeErrorCode(error, "ENOENT"))
10848
+ throw error;
10849
+ envFileExists = false;
10850
+ }
10851
+ const keyName = `${keyPrefix}1`;
10852
+ const merged = mergeEnvValues(envText, {
10853
+ [keyName]: (0, encoding_js_1.toBase64Url)(globalThis.crypto.getRandomValues(new Uint8Array(keyring_js_1.SECRETS_KEY_BYTES))),
10854
+ [activeKeyName]: "1",
10855
+ // Lets a production build run locally (`next start`): without it the
10856
+ // wrapper cannot tell this machine from an unidentified production host
10857
+ // once fingerprints are recorded, and refuses.
10858
+ [mod_js_1.SECRETS_ENVIRONMENT_ENV]: "development",
10859
+ });
10860
+ // Ignored before the key exists on disk, so it is never an untracked file
10861
+ // that a broad `git add` would pick up. Git is asked first, because a rule
10862
+ // such as `.env*` already covers it; when Git cannot answer, the rule is
10863
+ // appended unless it is already the last one.
10864
+ const ignored = await commandRunner("git", [
10865
+ "check-ignore",
10866
+ "-q",
10867
+ "--",
10868
+ ".env.local",
10869
+ ], { cwd, stdio: "pipe" });
10870
+ if (ignored.code !== 0) {
10871
+ const gitignorePath = (0, node_path_1.join)(cwd, ".gitignore");
10872
+ const gitignore = await readTextIfExists(gitignorePath) ?? "";
10873
+ const lastIgnoreRule = normalizeText(gitignore).split("\n")
10874
+ .map((line) => line.trim()).filter(Boolean).at(-1);
10875
+ if (lastIgnoreRule !== ".env.local" && lastIgnoreRule !== "/.env.local") {
10876
+ if (await writeTextIfChanged(gitignorePath, `${gitignore && !gitignore.endsWith("\n")
10877
+ ? `${gitignore}\n`
10878
+ : gitignore}.env.local\n`))
10879
+ changedFiles.push(".gitignore");
10880
+ }
10881
+ }
10882
+ // An existing file keeps its mode when it is rewritten, so it is made
10883
+ // owner-only before the key is in it, not after.
10884
+ if (envFileExists)
10885
+ await (0, promises_1.chmod)(envPath, 0o600);
10886
+ await (0, promises_1.writeFile)(envPath, merged.text, { mode: 0o600 });
10887
+ await (0, promises_1.chmod)(envPath, 0o600);
10888
+ changedFiles.push(".env.local");
10889
+ return {
10890
+ changedFiles,
10891
+ notes: [
10892
+ `Wrote a development secrets key to .env.local (${merged.changedNames.join(", ")}). It is for this machine only and was not printed.${merged.conflicts.length
10893
+ ? ` Left unchanged: ${merged.conflicts.join(", ")}.`
10894
+ : ""}`,
10895
+ ],
10896
+ };
10897
+ }
10898
+ async function applySecretsFeature(cwd, framework, manifest, activate, options = {}) {
10899
+ const changedFiles = [];
10900
+ const notes = [];
10901
+ const currentFeature = manifest.features.secrets;
10902
+ if (!activate && currentFeature?.status !== "active") {
10903
+ return { changedFiles, notes };
10904
+ }
10905
+ const config = getSecretsConfig(framework, currentFeature?.config);
10906
+ const feature = currentFeature
10907
+ ? structuredClone(currentFeature)
10908
+ : { status: "planned" };
10909
+ if (activate && feature.status !== "active") {
10910
+ feature.status = "active";
10911
+ feature.activatedOn ??= todayIso();
10912
+ }
10913
+ const scaffolds = [
10914
+ [config.modules.secretsModule, secretsModuleTemplate(config), "module"],
10915
+ [
10916
+ config.modules.locationsModule,
10917
+ secretLocationsModuleTemplate(),
10918
+ "locations module",
10919
+ ],
10920
+ ];
10921
+ for (const [relativePath, text, label] of scaffolds) {
10922
+ const scaffoldState = await scaffoldTextFile((0, node_path_1.join)(cwd, relativePath), text);
10923
+ if (scaffoldState === "created") {
10924
+ changedFiles.push(relativePath);
10925
+ }
10926
+ else if (activate && scaffoldState === "preserved") {
10927
+ notes.push(`Preserved existing secrets ${label}: ${relativePath}`);
10928
+ }
10929
+ }
10930
+ // Only an explicit `loom add secrets` may create a key; `loom init` reruns
10931
+ // this hook for every active feature and must never write one.
10932
+ if (activate) {
10933
+ const localKey = await ensureLocalSecretsKey(cwd, config, options.commandRunner ?? defaultCommandRunner);
10934
+ changedFiles.push(...localKey.changedFiles);
10935
+ notes.push(...localKey.notes);
10936
+ if (!Array.isArray(config.keys.production) || !config.keys.production.length) {
10937
+ notes.push("No production key is recorded yet. Before the first production deploy, an operator runs `loom secrets keygen` in their own terminal; an agent must not run it.");
10938
+ }
10939
+ }
10940
+ feature.config = mergeSecretsConfig(currentFeature?.config, config);
10941
+ manifest.features.secrets = feature;
10942
+ return { changedFiles, notes };
10943
+ }
10671
10944
  function linguiCliCommand(tooling) {
10672
10945
  switch (tooling.dependencies.manager) {
10673
10946
  case "deno":
@@ -13408,6 +13681,165 @@ async function checkPwaFeature(cwd, framework, manifest) {
13408
13681
  warnings,
13409
13682
  };
13410
13683
  }
13684
+ const VERCEL_PRODUCTION_ENV_POLICY_PATH = ".github/vercel-production-env.json";
13685
+ /**
13686
+ * Escapes text for use as a literal in a regular expression, in a form both
13687
+ * JavaScript and POSIX extended syntax (`git grep -E`) read the same way.
13688
+ */
13689
+ function escapeExtendedRegex(text) {
13690
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13691
+ }
13692
+ async function checkSecretsFeature(cwd, framework, manifest, options) {
13693
+ const issues = [];
13694
+ const warnings = [];
13695
+ const suggestions = new Set();
13696
+ const feature = manifest.features.secrets;
13697
+ if (!feature || feature.status !== "active") {
13698
+ return { issues, suggestions: [], warnings };
13699
+ }
13700
+ const releaseBlocking = (message) => {
13701
+ if (options.production)
13702
+ issues.push(message);
13703
+ else
13704
+ warnings.push(message);
13705
+ };
13706
+ const config = getSecretsConfig(framework, feature.config);
13707
+ const { activeKeyName, keyPrefix } = config.env;
13708
+ const moduleChecks = [
13709
+ [
13710
+ config.modules.secretsModule,
13711
+ "Secrets module",
13712
+ // A Next.js app must use the wrapper: the core entry point has no
13713
+ // build-phase refusal and no environment-selected key list.
13714
+ framework.kind === "nextjs"
13715
+ ? /["']@gadicc\/loom\/next\/secrets["']/
13716
+ : /["']@gadicc\/loom\/(?:next\/)?secrets["']/,
13717
+ "is not wired to @gadicc/loom/next/secrets",
13718
+ ],
13719
+ [
13720
+ config.modules.locationsModule,
13721
+ "Secret locations module",
13722
+ /\bdefineSecretLocations\b/,
13723
+ "does not declare its locations with defineSecretLocations",
13724
+ ],
13725
+ ];
13726
+ for (const [relativePath, label, pattern, problem] of moduleChecks) {
13727
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
13728
+ if (text === null) {
13729
+ issues.push(`${label} is missing: ${relativePath}`);
13730
+ suggestions.add("Run `loom add secrets`.");
13731
+ }
13732
+ else if (!pattern.test(text)) {
13733
+ issues.push(`${label} ${problem}: ${relativePath}`);
13734
+ suggestions.add("Restore the Loom secrets wiring in the app-local module, or point features.secrets.config.modules in loom.json at the module that has it.");
13735
+ }
13736
+ }
13737
+ for (const environment of ["production", "preview"]) {
13738
+ const recorded = config.keys[environment];
13739
+ if (recorded === undefined)
13740
+ continue;
13741
+ if (Array.isArray(recorded) && recorded.length === 0)
13742
+ continue;
13743
+ try {
13744
+ (0, fingerprint_js_1.parseExpectedSecretKeys)(recorded);
13745
+ }
13746
+ catch (error) {
13747
+ issues.push(`Secrets ${environment} key list in loom.json is invalid: ${error.message}`);
13748
+ suggestions.add("Correct features.secrets.config.keys in loom.json; `loom secrets keygen`, `activate` and `retire` keep it valid.");
13749
+ }
13750
+ }
13751
+ // Every tracked file is searched, not only root `.env*` files: a key is as
13752
+ // exposed in `deploy/.env.production` or a compose file. The pattern finds
13753
+ // candidates; only a value that decodes as a key is reported, so an
13754
+ // example file's placeholder is not. The pattern ends at the value's end,
13755
+ // so the first 43 characters of a longer value are not taken for a key.
13756
+ const keyAssignment = `${escapeExtendedRegex(keyPrefix)}[1-9][0-9]{0,8}["']?[[:space:]]*[=:][[:space:]]*["']?[A-Za-z0-9+/_-]{43}=?([^A-Za-z0-9+/_=-]|$)`;
13757
+ const gitResult = await (options.commandRunner ?? defaultCommandRunner)("git", ["grep", "-I", "--null", "-o", "-E", "-e", keyAssignment], { cwd, stdio: "pipe" });
13758
+ if (gitResult.code === 0) {
13759
+ const reported = new Set();
13760
+ for (const line of gitResult.stdout.split(/\r?\n/)) {
13761
+ const separator = line.indexOf("\0");
13762
+ if (separator < 0)
13763
+ continue;
13764
+ const relativePath = line.slice(0, separator);
13765
+ const match = line.slice(separator + 1).match(/^(.*?)["']?\s*[=:]\s*["']?([A-Za-z0-9+/_-]{43}=?)[^A-Za-z0-9+/_=-]?$/);
13766
+ if (!match)
13767
+ continue;
13768
+ const [, name, candidate] = match;
13769
+ try {
13770
+ (0, keyring_js_1.decodeSecretKey)(candidate, name);
13771
+ }
13772
+ catch {
13773
+ continue;
13774
+ }
13775
+ // Names the file and the variable only; the value must not reach a log.
13776
+ const issue = `A secrets key value is committed in a git-tracked file: ${relativePath} (${name})`;
13777
+ if (reported.has(issue))
13778
+ continue;
13779
+ reported.add(issue);
13780
+ issues.push(issue);
13781
+ suggestions.add("Remove the value from the tracked file and treat that key as exposed: generate a replacement with `loom secrets keygen` and rotate to it.");
13782
+ }
13783
+ }
13784
+ else if (gitResult.code !== 1 && !isNotAGitRepository(gitResult)) {
13785
+ // Exit 1 means no match and, outside a repository, nothing is tracked.
13786
+ // Anything else means the search did not happen, which is not "clean".
13787
+ releaseBlocking("Git-tracked files could not be checked for a committed secrets key: `git grep` failed.");
13788
+ suggestions.add("Make sure Git is installed and `git grep` works in this project, then rerun `loom check`.");
13789
+ }
13790
+ if (Array.isArray(config.keys.production) && config.keys.production.length === 0) {
13791
+ releaseBlocking("No production secrets key is recorded in loom.json, so production would run with unverified keys.");
13792
+ suggestions.add("Have an operator run `loom secrets keygen` in their own terminal, then commit the recorded fingerprint.");
13793
+ }
13794
+ const policyText = await readTextIfExists((0, node_path_1.join)(cwd, VERCEL_PRODUCTION_ENV_POLICY_PATH));
13795
+ if (policyText !== null) {
13796
+ let covered = false;
13797
+ // True until the policy has been read, so that an unreadable policy is
13798
+ // reported once and not also as a missing pointer.
13799
+ let pointerRequired = true;
13800
+ let problem = `has no requirement that covers the secrets keys (${keyPrefix}<n>) as Production-only Sensitive variables`;
13801
+ try {
13802
+ const requirements = (0, vercelBuildEnv_js_1.parseVercelBuildEnvironmentPolicy)(parseJson(policyText, VERCEL_PRODUCTION_ENV_POLICY_PATH));
13803
+ pointerRequired = requirements.some((requirement) => requirement.keys.includes(activeKeyName));
13804
+ covered = requirements.some((requirement) => requirement.keyPattern !== undefined &&
13805
+ // Several versions, so a pattern written for one key (`..._1$`) or
13806
+ // for a single digit does not pass for the keys that follow it.
13807
+ [1, 2, 10].every((version) => requirement.matches(`${keyPrefix}${version}`)) && requirement.sensitive && requirement.productionOnly);
13808
+ }
13809
+ catch (error) {
13810
+ problem = `could not be read: ${error.message}`;
13811
+ }
13812
+ if (!covered) {
13813
+ releaseBlocking(`Vercel release policy ${VERCEL_PRODUCTION_ENV_POLICY_PATH} ${problem}.`);
13814
+ }
13815
+ if (!pointerRequired) {
13816
+ releaseBlocking(`Vercel release policy ${VERCEL_PRODUCTION_ENV_POLICY_PATH} has no requirement whose keys include the secrets active key pointer (${activeKeyName}): a deployment without the pointer cannot seal.`);
13817
+ }
13818
+ if (!covered || !pointerRequired) {
13819
+ // Serialised as JSON so that a name with a character that needs
13820
+ // escaping, in the pattern or in the string, can be pasted as it is.
13821
+ // Both are shown whichever is missing: the policy needs the pair.
13822
+ const suggestedKeys = JSON.stringify({
13823
+ name: "secrets keys",
13824
+ keyPattern: `^${escapeExtendedRegex(keyPrefix)}[1-9][0-9]*$`,
13825
+ sensitive: true,
13826
+ productionOnly: true,
13827
+ placeholder: { kind: "secret" },
13828
+ });
13829
+ // The pointer is a readable variable, so it is not marked sensitive.
13830
+ const suggestedPointer = JSON.stringify({
13831
+ name: "secrets active key pointer",
13832
+ keys: [activeKeyName],
13833
+ });
13834
+ suggestions.add(`Add requirements such as ${suggestedKeys} and ${suggestedPointer} to ${VERCEL_PRODUCTION_ENV_POLICY_PATH}.`);
13835
+ }
13836
+ }
13837
+ return {
13838
+ issues,
13839
+ suggestions: [...suggestions],
13840
+ warnings,
13841
+ };
13842
+ }
13411
13843
  const featureHooks = {
13412
13844
  "api-keys": {
13413
13845
  apply: applyApiKeysFeature,
@@ -13443,6 +13875,10 @@ const featureHooks = {
13443
13875
  apply: applyPwaFeature,
13444
13876
  check: checkPwaFeature,
13445
13877
  },
13878
+ secrets: {
13879
+ apply: applySecretsFeature,
13880
+ check: checkSecretsFeature,
13881
+ },
13446
13882
  };
13447
13883
  async function ensureActiveFeatureScaffolds(cwd, framework, manifest) {
13448
13884
  const changedFiles = [];
@@ -13544,13 +13980,13 @@ async function initProject(cwd, versionRange) {
13544
13980
  .packageJson,
13545
13981
  };
13546
13982
  }
13547
- async function addFeature(cwd, featureKey, versionRange) {
13983
+ async function addFeature(cwd, featureKey, versionRange, options = {}) {
13548
13984
  const hook = featureHooks[featureKey];
13549
13985
  if (!hook) {
13550
13986
  throw new Error(`Unknown feature: ${featureKey}`);
13551
13987
  }
13552
13988
  const base = await initProject(cwd, versionRange);
13553
- const result = await hook.apply(cwd, base.framework, base.manifest, true);
13989
+ const result = await hook.apply(cwd, base.framework, base.manifest, true, options);
13554
13990
  const skillSync = await ensureManagedSkillLinks(cwd, base.manifest);
13555
13991
  const changedFiles = [
13556
13992
  ...base.changedFiles,
@@ -13566,6 +14002,147 @@ async function addFeature(cwd, featureKey, versionRange) {
13566
14002
  notes: [...new Set(notes)],
13567
14003
  };
13568
14004
  }
14005
+ async function readActiveSecretsFeature(cwd) {
14006
+ const manifest = await readManifestIfExists(cwd);
14007
+ if (!manifest) {
14008
+ throw new Error("Missing loom.json. Run `loom add secrets` first.");
14009
+ }
14010
+ const feature = manifest.features.secrets;
14011
+ if (feature?.status !== "active") {
14012
+ throw new Error("The secrets feature is not active. Run `loom add secrets` first.");
14013
+ }
14014
+ const framework = manifest.project?.framework ??
14015
+ await detectFramework(cwd, (await readProjectPackageJson(cwd)).packageJson);
14016
+ const config = getSecretsConfig(framework, feature.config);
14017
+ return { config, feature, manifest };
14018
+ }
14019
+ function recordedSecretKeys(config, environment) {
14020
+ const recorded = config.keys[environment] ?? [];
14021
+ if (!Array.isArray(recorded)) {
14022
+ throw new Error(`features.secrets.config.keys.${environment} in loom.json must be a list.`);
14023
+ }
14024
+ return recorded;
14025
+ }
14026
+ /** Validates a changed key list, then records it in loom.json. */
14027
+ async function writeSecretKeys(cwd, loaded, environment, keys) {
14028
+ if (keys.length) {
14029
+ try {
14030
+ (0, fingerprint_js_1.parseExpectedSecretKeys)(keys);
14031
+ }
14032
+ catch (error) {
14033
+ throw new Error(`The ${environment} key list in loom.json would be invalid: ${error.message}`);
14034
+ }
14035
+ }
14036
+ // Replaces this one list and nothing else: any other property a user keeps
14037
+ // under `config` or `config.keys` is theirs, and stays.
14038
+ const existing = isJsonObject(loaded.feature.config)
14039
+ ? loaded.feature.config
14040
+ : {};
14041
+ loaded.feature.config = {
14042
+ ...existing,
14043
+ keys: {
14044
+ ...(isJsonObject(existing.keys) ? existing.keys : {}),
14045
+ [environment]: keys,
14046
+ },
14047
+ };
14048
+ loaded.manifest.features.secrets = loaded.feature;
14049
+ return await writeManifestIfChanged(cwd, loaded.manifest)
14050
+ ? ["loom.json"]
14051
+ : [];
14052
+ }
14053
+ /**
14054
+ * Generates a key for a deployed environment and records its fingerprint in
14055
+ * loom.json: `active` when the environment has no active key, otherwise
14056
+ * `decrypt-only`. The version is one above the highest ever listed, so a
14057
+ * retired version is never reused. It always records: an unrecorded key
14058
+ * would let the next run give the same version to a different key.
14059
+ *
14060
+ * The returned `assignment` contains the key. A caller shows it once, to a
14061
+ * person at a terminal, and never logs or stores it.
14062
+ */
14063
+ async function generateSecretsKey(cwd, options = {}) {
14064
+ const environment = options.environment ?? "production";
14065
+ const loaded = await readActiveSecretsFeature(cwd);
14066
+ const current = recordedSecretKeys(loaded.config, environment);
14067
+ const id = current.reduce((highest, key) => (0, keyring_js_1.isSecretKeyId)(key?.id) ? Math.max(highest, key.id) : highest, 0) + 1;
14068
+ const state = current.some((key) => key?.state === "active")
14069
+ ? "decrypt-only"
14070
+ : "active";
14071
+ const key = globalThis.crypto.getRandomValues(new Uint8Array(keyring_js_1.SECRETS_KEY_BYTES));
14072
+ const fingerprint = await (0, fingerprint_js_1.secretKeyFingerprint)(key);
14073
+ const changedFiles = await writeSecretKeys(cwd, loaded, environment, [
14074
+ ...current,
14075
+ { id, fingerprint, state },
14076
+ ]);
14077
+ const variableName = `${loaded.config.env.keyPrefix}${id}`;
14078
+ return {
14079
+ activeKeyName: loaded.config.env.activeKeyName,
14080
+ assignment: `${variableName}=${(0, encoding_js_1.toBase64Url)(key)}`,
14081
+ changedFiles,
14082
+ environment,
14083
+ fingerprint,
14084
+ id,
14085
+ state,
14086
+ variableName,
14087
+ };
14088
+ }
14089
+ /**
14090
+ * The public fingerprint of a key as an operator typed or pasted it, for
14091
+ * comparing a saved copy with what loom.json records. Errors never include
14092
+ * the key.
14093
+ */
14094
+ async function fingerprintSecretsKey(value) {
14095
+ return await (0, fingerprint_js_1.secretKeyFingerprint)((0, keyring_js_1.decodeSecretKey)(value, "The entered key"));
14096
+ }
14097
+ /**
14098
+ * Marks a recorded key `active` in loom.json and the previously active key
14099
+ * `decrypt-only`. Refuses a version that is not listed or is retired.
14100
+ */
14101
+ async function activateSecretsKey(cwd, id, environment = "production") {
14102
+ const loaded = await readActiveSecretsFeature(cwd);
14103
+ const current = recordedSecretKeys(loaded.config, environment);
14104
+ const target = current.find((key) => key?.id === id);
14105
+ if (!target) {
14106
+ throw new Error(`Key version ${id} is not listed for ${environment} in loom.json.`);
14107
+ }
14108
+ if (target.state === "retired") {
14109
+ throw new Error(`Key version ${id} is retired and cannot be activated. Generate a new key with \`loom secrets keygen\`.`);
14110
+ }
14111
+ const changedFiles = await writeSecretKeys(cwd, loaded, environment, current.map((key) => key?.id === id
14112
+ ? { ...key, state: "active" }
14113
+ : key?.state === "active"
14114
+ ? { ...key, state: "decrypt-only" }
14115
+ : key));
14116
+ return {
14117
+ activeKeyName: loaded.config.env.activeKeyName,
14118
+ changedFiles,
14119
+ environment,
14120
+ id,
14121
+ };
14122
+ }
14123
+ /**
14124
+ * Marks a recorded key `retired` in loom.json. Refuses the active key and a
14125
+ * version that is not listed. Whether anything still needs the key is the
14126
+ * operator's decision; nothing here can check stored data or backups.
14127
+ */
14128
+ async function retireSecretsKey(cwd, id, environment = "production") {
14129
+ const loaded = await readActiveSecretsFeature(cwd);
14130
+ const current = recordedSecretKeys(loaded.config, environment);
14131
+ const target = current.find((key) => key?.id === id);
14132
+ if (!target) {
14133
+ throw new Error(`Key version ${id} is not listed for ${environment} in loom.json.`);
14134
+ }
14135
+ if (target.state === "active") {
14136
+ throw new Error(`Key version ${id} is the active key and cannot be retired. Activate another key with \`loom secrets activate <id>\` first.`);
14137
+ }
14138
+ const changedFiles = await writeSecretKeys(cwd, loaded, environment, current.map((key) => key?.id === id ? { ...key, state: "retired" } : key));
14139
+ return {
14140
+ changedFiles,
14141
+ environment,
14142
+ id,
14143
+ variableName: `${loaded.config.env.keyPrefix}${id}`,
14144
+ };
14145
+ }
13569
14146
  function jobsRouteHasAuthorizationCallback(text) {
13570
14147
  if (!text)
13571
14148
  return false;
@@ -13668,7 +14245,7 @@ async function configureApiKeyRetention(cwd, enabled, overrides = {}) {
13668
14245
  }
13669
14246
  async function addSkills(cwd, versionRange, env = node_process_1.default.env, options = {}) {
13670
14247
  const base = await initProject(cwd, versionRange);
13671
- const skillSync = await (0, projectSkills_js_1.syncExternalProjectSkills)(cwd, getSkillsContext(base.packageJson, base.manifest), {
14248
+ const skillSync = await (0, projectSkills_js_1.syncExternalProjectSkills)(cwd, await getSkillsContext(cwd, base.packageJson, base.manifest), {
13672
14249
  acceptUnknownLicense: options.acceptUnknownLicense,
13673
14250
  adoptRecommended: !options.skillNames?.length,
13674
14251
  commandRunner: options.commandRunner ?? defaultCommandRunner,
@@ -13807,7 +14384,7 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
13807
14384
  suggestions.add(suggestion);
13808
14385
  }
13809
14386
  }
13810
- const projectSkillsCheck = await (0, projectSkills_js_1.checkProjectSkills)(cwd, getSkillsContext(packageJson, manifest), options.strictSkills);
14387
+ const projectSkillsCheck = await (0, projectSkills_js_1.checkProjectSkills)(cwd, await getSkillsContext(cwd, packageJson, manifest), options.strictSkills);
13811
14388
  warnings.push(...projectSkillsCheck.warnings);
13812
14389
  issues.push(...projectSkillsCheck.issues);
13813
14390
  for (const suggestion of projectSkillsCheck.suggestions) {
@@ -14344,7 +14921,7 @@ async function runStatus(cwd, io) {
14344
14921
  managedSkillLines.push(`${skill.skillName}: ${formatSkillLinkState(state)}`);
14345
14922
  }
14346
14923
  io.out(` managed: ${managedSkillLines.join("; ") || "none"}`);
14347
- const skillStatus = await (0, projectSkills_js_1.getProjectSkillStatus)(cwd, getSkillsContext(packageJson, manifest));
14924
+ const skillStatus = await (0, projectSkills_js_1.getProjectSkillStatus)(cwd, await getSkillsContext(cwd, packageJson, manifest));
14348
14925
  const packageSkillLines = skillStatus.packageSkills.map((skill) => `${skill.skillName} from ${skill.packageName} (${skill.disabled ? "disabled" : skill.active ? "active" : "available"})`);
14349
14926
  io.out(` npm packages: ${formatInlineList(packageSkillLines)}`);
14350
14927
  const externalSkillLines = skillStatus.external
@@ -14354,7 +14931,7 @@ async function runStatus(cwd, io) {
14354
14931
  : "recommended"}; license ${skill.licenseStatus})`);
14355
14932
  io.out(` external: ${formatInlineList(externalSkillLines)}`);
14356
14933
  io.out(` disabled: ${formatInlineList(skillStatus.disabled)}`);
14357
- io.out(" updates: run `loom skills sync` or `loom skills update`.");
14934
+ io.out(" updates: run `loom skills sync` to restore pins; review `loom skills update` to advance them.");
14358
14935
  return 0;
14359
14936
  }
14360
14937
  function printHelp({ out }) {
@@ -14369,11 +14946,15 @@ function printHelp({ out }) {
14369
14946
  out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local storage, and Files adapter wiring.");
14370
14947
  out(" api-keys integrate jobs Record an explicit API-key jobs integration after the route has session/admin authorization.");
14371
14948
  out(" api-keys retention enable|disable Record API-key audit cleanup policy; scheduling remains app-owned.");
14949
+ out(" secrets keygen Generate a production secrets key, print it once to a terminal, and record its fingerprint in loom.json.");
14950
+ out(" secrets fingerprint Read a secrets key from a hidden terminal prompt and print only its fingerprint.");
14951
+ out(" secrets activate <id> Record a listed secrets key as the active one; the previous active key becomes decrypt-only.");
14952
+ out(" secrets retire <id> Record a secrets key that nothing needs any more as retired.");
14372
14953
  out(" status Show the Loom package, manifest, active features, local-dev state, and project skill state.");
14373
14954
  out(" check Validate project bootstrap, managed guidance, features, skill locks, caches, and links.");
14374
14955
  out(" env -- <command> Load project .env* files with Next-compatible semantics, then run a command from the project root.");
14375
- out(" skills sync Activate npm package skills and hydrate locked external skills.");
14376
- out(" skills update Move adopted skills to Loom's reviewed upstream revisions.");
14956
+ out(" skills sync Restore recorded skill content and links without adopting updates.");
14957
+ out(" skills update Approve reviewed updates for adopted skills, or select names.");
14377
14958
  out(" db fixtures Run the Loom-managed DB fixture dump script for the active DB feature.");
14378
14959
  out(" db schema-gen Run the Loom-managed Valibot generator workflow for the active DB feature. Pass extra generator args after `--`.");
14379
14960
  out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
@@ -14395,7 +14976,7 @@ function printHelp({ out }) {
14395
14976
  out(" dev published Remove the managed local-dev override and return to the published dependency.");
14396
14977
  out("");
14397
14978
  out("Options:");
14398
- out(" --strict-skills Treat missing or stale recommended external skills as check failures.");
14979
+ out(" --strict-skills Treat invalid recorded skill content or links as check failures.");
14399
14980
  out(" --accept-unknown-license <skill> Explicitly adopt an upstream skill without a clear declared license.");
14400
14981
  out(" --network Run registered network checks after the local project checks.");
14401
14982
  out(" --production Treat local Loom dev overrides and local lockfile resolutions as release-blocking check failures.");
@@ -14427,6 +15008,7 @@ function printHelp({ out }) {
14427
15008
  out(" --token-expiry-days <days> Vercel release token lifetime (default 90).");
14428
15009
  out(" --timeout <duration> Bounded Vercel promotion wait (default 3m).");
14429
15010
  out(" --environment <name> GitHub Environment for migration credential setup (default production).");
15011
+ out(" --environment production|preview Key list a `loom secrets` command uses (default production).");
14430
15012
  out(" --env-file <path> Preserved env snapshot for `db migrations verify-env`; process values take precedence.");
14431
15013
  out(" --connect Authenticate and check migration database identity and schema privileges.");
14432
15014
  out(" --resource <name> Permission resource for API-key integration.");
@@ -14471,6 +15053,129 @@ async function runApiKeys(cwd, command, target, options, io) {
14471
15053
  io.out(`Note: ${note}`);
14472
15054
  return 0;
14473
15055
  }
15056
+ const SECRETS_FINGERPRINT_ARGUMENT_REFUSAL = "loom secrets fingerprint takes no arguments. A key must never be passed as an argument: if a key was typed there, treat it as exposed, because it is now in the shell history and was visible in the process list. The key is read from a hidden terminal prompt instead.";
15057
+ /**
15058
+ * Variables that an automated or agent session sets. A key must not be shown
15059
+ * to, or typed into, such a session even when it runs under a pseudo-terminal.
15060
+ */
15061
+ const AUTOMATED_SESSION_ENV_NAMES = [
15062
+ "CI",
15063
+ "GITHUB_ACTIONS",
15064
+ "CLAUDECODE",
15065
+ "CLAUDE_CODE_ENTRYPOINT",
15066
+ "AI_AGENT",
15067
+ "CODEX_SANDBOX",
15068
+ "CURSOR_AGENT",
15069
+ "GEMINI_CLI",
15070
+ ];
15071
+ async function runSecrets(cwd, command, target, options, io, terminal = {}) {
15072
+ const usage = "Usage: loom secrets keygen [--environment production|preview]\n or: loom secrets fingerprint\n or: loom secrets activate <id> [--environment production|preview]\n or: loom secrets retire <id> [--environment production|preview]";
15073
+ const environmentOption = options.environment ?? "production";
15074
+ if (environmentOption !== "production" && environmentOption !== "preview") {
15075
+ io.err("--environment must be production or preview.");
15076
+ return 1;
15077
+ }
15078
+ const environment = environmentOption;
15079
+ const platformTarget = environment === "production"
15080
+ ? "Production"
15081
+ : "Preview";
15082
+ const stdinIsTty = terminal.stdinIsTty ?? Boolean(node_process_1.default.stdin.isTTY);
15083
+ const stdoutIsTty = terminal.stdoutIsTty ?? Boolean(node_process_1.default.stdout.isTTY);
15084
+ const sessionEnv = terminal.env ?? node_process_1.default.env;
15085
+ const automatedMarker = AUTOMATED_SESSION_ENV_NAMES.find((name) => Boolean(sessionEnv[name]));
15086
+ try {
15087
+ switch (command) {
15088
+ case "keygen": {
15089
+ // Deliberately no flag overrides these: the only safe destination for
15090
+ // a production key is the screen of the operator who will save it.
15091
+ // They are a guardrail, not proof that a person is watching; a
15092
+ // pseudo-terminal with a clean environment still passes.
15093
+ const refusal = automatedMarker
15094
+ ? `this is an automated or agent session`
15095
+ : !stdoutIsTty
15096
+ ? "its output is not a terminal"
15097
+ : !stdinIsTty
15098
+ ? "its input is not a terminal"
15099
+ : null;
15100
+ if (refusal) {
15101
+ io.err(`loom secrets keygen prints a production key, so it only runs for a person at a terminal, and ${refusal}. A production key must not be written to a pipe, a file, a log or an AI agent transcript. An operator runs it personally, in their own terminal.`);
15102
+ return 1;
15103
+ }
15104
+ const result = await generateSecretsKey(cwd, { environment });
15105
+ io.out(`Generated secrets key version ${result.id} for ${environment}. It is shown once and Loom keeps no copy.`);
15106
+ io.out("");
15107
+ io.out(result.assignment);
15108
+ io.out(`Fingerprint: ${result.fingerprint}`);
15109
+ io.out("");
15110
+ io.out(`Recorded the fingerprint in loom.json as ${result.state}. Commit loom.json; it holds no key.`);
15111
+ io.out("Next steps:");
15112
+ io.out(" 1. Save the key and its fingerprint in your password manager now, before anything else.");
15113
+ io.out(` 2. Add ${result.variableName} to the deployment platform from the password-manager copy, ${platformTarget} only, as a write-only secret${result.state === "active"
15114
+ ? `, and set ${result.activeKeyName}=${result.id} there`
15115
+ : ""}.`);
15116
+ io.out(" 3. Deploy.");
15117
+ io.out(` 4. Confirm \`secrets.assertReady()\` passes in the deployment: that proves the deployed key is the one you saved.${result.state === "active"
15118
+ ? ""
15119
+ : ` Then switch to it with \`loom secrets activate ${result.id}\`.`}`);
15120
+ return 0;
15121
+ }
15122
+ case "fingerprint": {
15123
+ // Checked before anything else, and never echoed: whatever followed
15124
+ // the command may be a key.
15125
+ if (target !== undefined) {
15126
+ io.err(SECRETS_FINGERPRINT_ARGUMENT_REFUSAL);
15127
+ return 1;
15128
+ }
15129
+ if (automatedMarker) {
15130
+ io.err(`loom secrets fingerprint reads a key, so it only runs for a person at a terminal, and this is an automated or agent session. A key must not be typed into, or read by, such a session. An operator runs it personally, in their own terminal.`);
15131
+ return 1;
15132
+ }
15133
+ const notInteractive = "loom secrets fingerprint reads the key from a hidden terminal prompt, so its input must be a terminal. Never pass a key as an argument, through a pipe, or from a file. Run it yourself, in your own terminal.";
15134
+ if (!stdinIsTty) {
15135
+ io.err(notInteractive);
15136
+ return 1;
15137
+ }
15138
+ const prompt = terminal.prompt ??
15139
+ ((question) => promptForTerminalValue(question, true, {
15140
+ cancelled: "Fingerprinting was cancelled.",
15141
+ notInteractive,
15142
+ }));
15143
+ io.out(await fingerprintSecretsKey(await prompt("Secrets key (input is hidden): ")));
15144
+ return 0;
15145
+ }
15146
+ case "activate":
15147
+ case "retire": {
15148
+ const id = target === undefined ? null : (0, keyring_js_1.parseSecretKeyId)(target);
15149
+ if (id === null) {
15150
+ io.err(usage);
15151
+ return 1;
15152
+ }
15153
+ if (command === "activate") {
15154
+ const result = await activateSecretsKey(cwd, id, environment);
15155
+ io.out(result.changedFiles.length
15156
+ ? `Updated ${result.changedFiles.join(", ")}: key version ${id} is now the active ${environment} key.`
15157
+ : `Key version ${id} is already the active ${environment} key in loom.json.`);
15158
+ io.out(`Note: Set ${result.activeKeyName}=${id} for ${platformTarget} on the deployment platform, before deploying this loom.json. Until both match, every seal fails (opens still work).`);
15159
+ return 0;
15160
+ }
15161
+ const result = await retireSecretsKey(cwd, id, environment);
15162
+ io.out(result.changedFiles.length
15163
+ ? `Updated ${result.changedFiles.join(", ")}: key version ${id} is now retired for ${environment}.`
15164
+ : `Key version ${id} is already retired for ${environment} in loom.json.`);
15165
+ io.out(`Note: Retiring a key is only safe when no stored value, keyed fingerprint or restorable backup needs it. Remove ${result.variableName} from ${platformTarget} and delete every deployment built while it was active.`);
15166
+ return 0;
15167
+ }
15168
+ default:
15169
+ io.err(usage);
15170
+ return 1;
15171
+ }
15172
+ }
15173
+ catch (error) {
15174
+ // These are operator-facing refusals; a stack trace adds nothing.
15175
+ io.err(error.message);
15176
+ return 1;
15177
+ }
15178
+ }
14474
15179
  async function runFiles(cwd, command, target, options, io) {
14475
15180
  if (command === "id-generation") {
14476
15181
  if (target !== "uuid-v4" && target !== "uuid-v7") {
@@ -14666,12 +15371,12 @@ function printSkillsHelp({ out }) {
14666
15371
  out("");
14667
15372
  out("Commands:");
14668
15373
  out(" list Show discovered, adopted, disabled, and recommended skills.");
14669
- out(" add Adopt and install matching external skills.");
14670
- out(" sync Hydrate locked skills and activate npm package skills.");
15374
+ out(" add Adopt selected external or installed npm skills.");
15375
+ out(" sync Restore recorded skill content and links.");
14671
15376
  out(" check Validate project skill locks, caches, and links.");
14672
- out(" update Move adopted skills to Loom's reviewed catalog revisions.");
15377
+ out(" update Update adopted skills to reviewed catalog or installed npm content.");
14673
15378
  out(" migrate Replace legacy packaged-skill links with project installs.");
14674
- out(" disable Opt out of automatic activation for a skill.");
15379
+ out(" disable Disable a managed skill or opt out of a recommendation.");
14675
15380
  out(" enable Clear a skill opt-out; run sync afterward.");
14676
15381
  out("");
14677
15382
  out("Unlicensed external skills require `--accept-unknown-license <name>`.");
@@ -14697,7 +15402,7 @@ async function runSkills(cwd, command, args, io, options) {
14697
15402
  const manifest = manifestText
14698
15403
  ? parseJson(manifestText, "loom.json")
14699
15404
  : null;
14700
- const context = getSkillsContext(packageJson, manifest);
15405
+ const context = await getSkillsContext(cwd, packageJson, manifest);
14701
15406
  const accepted = options.acceptUnknownLicense
14702
15407
  ? [options.acceptUnknownLicense]
14703
15408
  : [];
@@ -14734,6 +15439,30 @@ async function runSkills(cwd, command, args, io, options) {
14734
15439
  case "migrate":
14735
15440
  case "sync":
14736
15441
  case "update": {
15442
+ if ((command === "sync" || command === "migrate") && args.length) {
15443
+ io.err(`loom skills ${command} restores locked state and does not select new skills.`);
15444
+ return 1;
15445
+ }
15446
+ const status = await (0, projectSkills_js_1.getProjectSkillStatus)(cwd, context);
15447
+ const locked = await (0, projectSkills_js_1.readProjectSkillsLock)(cwd);
15448
+ const packageNames = new Set(status.packageSkills.map((skill) => skill.skillName));
15449
+ const externalNames = new Set([
15450
+ ...status.external.map((skill) => skill.skillName),
15451
+ ...Object.keys(locked.skills).filter((name) => locked.skills[name].kind === "external"),
15452
+ ]);
15453
+ const unknown = args.filter((name) => !packageNames.has(name) && !externalNames.has(name));
15454
+ if (unknown.length) {
15455
+ io.err(`Unknown skill: ${unknown.join(", ")}`);
15456
+ return 1;
15457
+ }
15458
+ const ambiguous = args.filter((name) => !locked.skills[name] && packageNames.has(name) &&
15459
+ externalNames.has(name));
15460
+ if (ambiguous.length) {
15461
+ io.err(`Ambiguous skill source: ${ambiguous.join(", ")}. Choose and adopt the source explicitly before using its name.`);
15462
+ return 1;
15463
+ }
15464
+ const selectedPackages = args.filter((name) => locked.skills[name]?.kind === "package" ||
15465
+ (!locked.skills[name] && packageNames.has(name)));
14737
15466
  const nextGuidance = await ensureNextAgentsFile(cwd, packageJson);
14738
15467
  const migrationFiles = [];
14739
15468
  const migrationNotes = [];
@@ -14745,12 +15474,18 @@ async function runSkills(cwd, command, args, io, options) {
14745
15474
  migrationFiles.push(".agents/skills/next-best-practices");
14746
15475
  migrationNotes.push("Removed the retired next-best-practices link; use Next.js version-matched agent documentation.");
14747
15476
  }
14748
- const packageResult = await (0, projectSkills_js_1.syncInstalledPackageSkills)(cwd);
15477
+ const packageResult = await (0, projectSkills_js_1.syncInstalledPackageSkills)(cwd, {
15478
+ skillNames: selectedPackages,
15479
+ update: command === "update" && !args.length,
15480
+ });
14749
15481
  const externalResult = await (0, projectSkills_js_1.syncExternalProjectSkills)(cwd, context, {
14750
15482
  acceptUnknownLicense: accepted,
14751
- adoptRecommended: command === "add" || command === "migrate",
15483
+ adoptRecommended: command === "add" && !args.length,
15484
+ update: command === "update",
14752
15485
  commandRunner: defaultCommandRunner,
14753
- skillNames: args.length ? args : undefined,
15486
+ skillNames: args.length
15487
+ ? args.filter((name) => !selectedPackages.includes(name))
15488
+ : undefined,
14754
15489
  });
14755
15490
  if (await ensureExternalSkillsGitignore(cwd)) {
14756
15491
  externalResult.changedFiles.push(".gitignore");
@@ -15289,20 +16024,10 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
15289
16024
  }
15290
16025
  }
15291
16026
  async function runCheck(cwd, strictSkills, production, network, noProgress, noColor, io) {
15292
- const packageSkills = await (0, projectSkills_js_1.syncInstalledPackageSkills)(cwd);
15293
- if (packageSkills.changedFiles.length) {
15294
- io.out(`Updated ${packageSkills.changedFiles.join(", ")} while activating npm package skills.`);
15295
- }
15296
- for (const note of packageSkills.notes)
15297
- io.out(`Note: ${note}`);
15298
16027
  const localResult = await checkProject(cwd, node_process_1.default.env, {
15299
16028
  production,
15300
16029
  strictSkills,
15301
16030
  });
15302
- if (production && packageSkills.changedFiles.length) {
15303
- localResult.issues.push(`Production check activated or updated project skills: ${packageSkills.changedFiles.join(", ")}.`);
15304
- localResult.suggestions.push("Review and commit the project skill lock and activation links before release.");
15305
- }
15306
16031
  let result = localResult;
15307
16032
  if (network) {
15308
16033
  const reporter = createNetworkProgressReporter(io, {
@@ -15346,6 +16071,15 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
15346
16071
  err: (line) => console.error(line),
15347
16072
  out: (line) => console.log(line),
15348
16073
  }, options = {}) {
16074
+ // Checked before any argument is parsed: a parse error quotes the argument,
16075
+ // and a key pasted after `fingerprint` (base64url keys can begin with `-`)
16076
+ // must not be printed back.
16077
+ const secretsIndex = args.indexOf("secrets");
16078
+ if (secretsIndex >= 0 && args[secretsIndex + 1] === "fingerprint" &&
16079
+ args.length > secretsIndex + 2) {
16080
+ io.err(SECRETS_FINGERPRINT_ARGUMENT_REFUSAL);
16081
+ return 1;
16082
+ }
15349
16083
  const parsed = (0, node_util_1.parseArgs)({
15350
16084
  allowPositionals: true,
15351
16085
  args,
@@ -15410,6 +16144,9 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
15410
16144
  const addListOnly = command === "add" && arg1 === undefined;
15411
16145
  if (command !== undefined &&
15412
16146
  command !== "dev" &&
16147
+ // `loom secrets` reads and writes only loom.json and the terminal. A
16148
+ // sync would put build output and notes around a key shown once.
16149
+ command !== "secrets" &&
15413
16150
  command !== "skills" &&
15414
16151
  command !== "status" &&
15415
16152
  !addListOnly &&
@@ -15477,6 +16214,8 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
15477
16214
  maxRequestsPerKey: parsed.values["max-requests-per-key"],
15478
16215
  resource: parsed.values.resource,
15479
16216
  }, io);
16217
+ case "secrets":
16218
+ return await runSecrets(cwd, arg1, arg2, { environment: parsed.values.environment }, io, options.secretsTerminal);
15480
16219
  case "skills":
15481
16220
  return await runSkills(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
15482
16221
  acceptUnknownLicense: parsed.values["accept-unknown-license"],