@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
@@ -17,11 +17,15 @@ import { classifyManagedFile, classifyManagedTask, describeManagedFileDifference
17
17
  import { legacyDbPgliteHarnessOutputs, legacyDbTaskValues, legacyJobsDirectRunnerOutputs, legacyJobsTaskValues, } from "./legacyManagedOutputs.js";
18
18
  import { BETTER_AUTH_API_KEY_HTTP_PATHS } from "../apiKeys/betterAuth.js";
19
19
  import { DEFAULT_API_KEY_AUDIT_RETENTION } from "../apiKeys/retention.js";
20
- import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
20
+ import { SECRETS_ENVIRONMENT_ENV } from "../next/secrets/mod.js";
21
+ import { toBase64Url } from "../secrets/encoding.js";
22
+ import { parseExpectedSecretKeys, secretKeyFingerprint, } from "../secrets/fingerprint.js";
23
+ import { decodeSecretKey, DEFAULT_SECRETS_ACTIVE_KEY_ENV, DEFAULT_SECRETS_KEY_ENV_PREFIX, isSecretKeyId, parseSecretKeyId, SECRETS_KEY_BYTES, } from "../secrets/keyring.js";
24
+ import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, readProjectSkillsLock, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
21
25
  import { resolveMigrationEnvironment, resolveMigrationEnvironmentFromEnvFile, verifyMigrationConnection, verifyMigrationConnectionFromEnvFile, } from "./migrationEnv.js";
22
- import { prepareVercelBuildEnvironment, verifyVercelBuildArtifact, } from "./vercelBuildEnv.js";
26
+ import { parseVercelBuildEnvironmentPolicy, prepareVercelBuildEnvironment, verifyVercelBuildArtifact, } from "./vercelBuildEnv.js";
23
27
  import { parseVercelReleaseTimeout, prepareVercelProjectRelease, promoteVercelProjectRelease, } from "./vercelProjectRelease.js";
24
- import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, jsonValuesEqual, mutateDenoLinks, mutatePackageJsonOverride, mutateProjectDependencies, parseJsonc, patchJsonText, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
28
+ import { denoConfigAsPackageJson, detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, jsonValuesEqual, mutateDenoLinks, mutatePackageJsonOverride, mutateProjectDependencies, parseJsonc, patchJsonText, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
25
29
  import { withLocalDevLock, } from "./localDevLock.js";
26
30
  import { computeLoomSourceFingerprint, computePackageContentDigest, computePackageTreeSignature, findNewPeerVariantDuplicates, findPackageTreeDifference, formatLoomBuildStamp, getLockfileOverride, getLockfileRootImporterDependency, hasLoomBuildProvenance, LOOM_BUILD_STAMP_FILE, LOOM_PACKAGE_RELEVANT_PATHS, readLoomBuildStamp, } from "./localDevPackage.js";
27
31
  export const DEFAULT_LOOM_RANGE = "^1.0.0";
@@ -136,6 +140,12 @@ const managedSkills = [
136
140
  relativePackagePath: "skills/loom-lingui",
137
141
  skillName: "loom-lingui",
138
142
  },
143
+ {
144
+ featureKey: "secrets",
145
+ label: "loom secrets skill",
146
+ relativePackagePath: "skills/loom-secrets",
147
+ skillName: "loom-secrets",
148
+ },
139
149
  ];
140
150
  const featureDefinitions = [
141
151
  {
@@ -170,6 +180,10 @@ const featureDefinitions = [
170
180
  key: "pwa",
171
181
  description: "Shared Serwist PWA worker, provider lifecycle, update prompts, and build wiring.",
172
182
  },
183
+ {
184
+ key: "secrets",
185
+ description: "Reversible secrets at rest with versioned, fingerprint-verified keys.",
186
+ },
173
187
  ];
174
188
  const DB_DEFAULT_DEPENDENCIES = {
175
189
  "@neondatabase/serverless": "^1.1.0",
@@ -2068,6 +2082,31 @@ function mergeApiKeyAuditSchemaConfig(dbConfig, schemaConfig) {
2068
2082
  hashManagedSchemaText(buildApiKeyAuditSchemaText(merged)),
2069
2083
  };
2070
2084
  }
2085
+ function getSecretsConfig(framework, featureConfig) {
2086
+ const moduleRoot = framework.srcDir ? "src/" : "";
2087
+ return {
2088
+ modules: {
2089
+ secretsModule: featureConfig?.modules?.secretsModule ??
2090
+ `${moduleRoot}secrets.ts`,
2091
+ locationsModule: featureConfig?.modules?.locationsModule ??
2092
+ `${moduleRoot}secretLocations.ts`,
2093
+ },
2094
+ env: {
2095
+ keyPrefix: featureConfig?.env?.keyPrefix ??
2096
+ DEFAULT_SECRETS_KEY_ENV_PREFIX,
2097
+ activeKeyName: featureConfig?.env?.activeKeyName ??
2098
+ DEFAULT_SECRETS_ACTIVE_KEY_ENV,
2099
+ },
2100
+ // Recorded by `loom secrets`; passed through unvalidated so `loom check`
2101
+ // can report a hand-edited list instead of this getter hiding it.
2102
+ keys: {
2103
+ production: featureConfig?.keys?.production ?? [],
2104
+ ...(featureConfig?.keys?.preview !== undefined
2105
+ ? { preview: featureConfig.keys.preview }
2106
+ : {}),
2107
+ },
2108
+ };
2109
+ }
2071
2110
  function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
2072
2111
  const appRoot = framework.srcDir ? "src/app" : "app";
2073
2112
  const apiKeysRoot = framework.srcDir
@@ -4512,7 +4551,16 @@ async function checkPnpm11Compatibility(cwd, packageJson, npmrcText) {
4512
4551
  warnings: major === null || major < 11 ? findings : [],
4513
4552
  };
4514
4553
  }
4515
- function getSkillsContext(packageJson, manifest) {
4554
+ async function getSkillsContext(cwd, packageJson, manifest) {
4555
+ const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
4556
+ const dependencyConfig = tooling.dependencies.config;
4557
+ if (dependencyConfig !== "package.json") {
4558
+ const text = await readTextIfExists(join(cwd, dependencyConfig));
4559
+ if (text === null) {
4560
+ throw new Error(`Missing dependency config: ${dependencyConfig}`);
4561
+ }
4562
+ packageJson = denoConfigAsPackageJson(parseJsonc(text, dependencyConfig));
4563
+ }
4516
4564
  return {
4517
4565
  activeFeatureKeys: new Set(manifest
4518
4566
  ? Object.entries(manifest.features)
@@ -8062,11 +8110,14 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
8062
8110
  ok: false,
8063
8111
  };
8064
8112
  }
8065
- async function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
8113
+ /**
8114
+ * Reads one line from the terminal, writing the question to stderr. A secret
8115
+ * is read in raw mode so it is never echoed. Refuses when stdin is not a
8116
+ * terminal, with the caller's explanation of what to do instead.
8117
+ */
8118
+ async function promptForTerminalValue(question, secret, messages) {
8066
8119
  if (!process.stdin.isTTY) {
8067
- throw new Error(context === "MinIO"
8068
- ? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
8069
- : "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.");
8120
+ throw new Error(messages.notInteractive);
8070
8121
  }
8071
8122
  if (!secret) {
8072
8123
  const input = createInterface({
@@ -8098,7 +8149,7 @@ async function promptForLocalFilesValue(question, secret = false, context = "Min
8098
8149
  }
8099
8150
  if (character === "\u0003") {
8100
8151
  stdin.off("data", onData);
8101
- rejectPromise(new Error(`${context} setup was cancelled.`));
8152
+ rejectPromise(new Error(messages.cancelled));
8102
8153
  return;
8103
8154
  }
8104
8155
  if (character === "\u007f" || character === "\b") {
@@ -8117,6 +8168,14 @@ async function promptForLocalFilesValue(question, secret = false, context = "Min
8117
8168
  stdin.pause();
8118
8169
  }
8119
8170
  }
8171
+ function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
8172
+ return promptForTerminalValue(question, secret, {
8173
+ cancelled: `${context} setup was cancelled.`,
8174
+ notInteractive: context === "MinIO"
8175
+ ? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
8176
+ : "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.",
8177
+ });
8178
+ }
8120
8179
  function minioHostEnv(env, endpoint, accessKey, secretKey) {
8121
8180
  const url = new URL(endpoint);
8122
8181
  url.username = accessKey;
@@ -10595,6 +10654,216 @@ async function applyAuthFeature(cwd, framework, manifest, activate) {
10595
10654
  }
10596
10655
  return { changedFiles, notes };
10597
10656
  }
10657
+ /**
10658
+ * Whether a failed Git command failed because there is no repository, in
10659
+ * which case no file is tracked. The message is matched because Git uses the
10660
+ * same exit status (128) for failures that are not an answer at all.
10661
+ */
10662
+ function isNotAGitRepository(result) {
10663
+ return result.code !== 0 && /not a git repository/i.test(result.stderr);
10664
+ }
10665
+ function secretsModuleTemplate(config) {
10666
+ return `import { createNextSecrets } from "@gadicc/loom/next/secrets";
10667
+
10668
+ import loomManifest from "${toRelativeImportPath(config.modules.secretsModule, "loom.json")}";
10669
+
10670
+ const config = loomManifest.features.secrets.config;
10671
+
10672
+ // loom.json records the fingerprint of every key a deployed environment is
10673
+ // expected to hold, so a key that differs from the saved copy is refused.
10674
+ export const secrets = createNextSecrets({
10675
+ expectedKeys: config.keys,
10676
+ variables: config.env,
10677
+ });
10678
+
10679
+ // Declare one purpose per kind of secret, beside the code that uses it:
10680
+ //
10681
+ // export const thingSecret = secrets.purpose("area.thing");
10682
+ //
10683
+ // A purpose name and its binding are permanent: a value sealed under them can
10684
+ // never be opened under different ones.
10685
+ `;
10686
+ }
10687
+ function secretLocationsModuleTemplate() {
10688
+ return `import { defineSecretLocations } from "@gadicc/loom/secrets/maintenance";
10689
+
10690
+ // Every column that holds a sealed string must be declared here. The
10691
+ // maintenance operations (report, verify, reseal) only reach declared
10692
+ // locations, so an undeclared column is never re-encrypted and keeps its old
10693
+ // key in use without anyone noticing.
10694
+ export const secretLocations = defineSecretLocations([]);
10695
+ `;
10696
+ }
10697
+ /**
10698
+ * The normalised config laid over what loom.json already holds, so that a
10699
+ * property Loom does not know (under `config` or one of its sections) is
10700
+ * kept instead of being dropped by a rewrite.
10701
+ */
10702
+ function mergeSecretsConfig(existing, config) {
10703
+ const current = isJsonObject(existing) ? existing : {};
10704
+ const section = (name) => ({
10705
+ ...(isJsonObject(current[name]) ? current[name] : {}),
10706
+ ...config[name],
10707
+ });
10708
+ return {
10709
+ ...current,
10710
+ modules: section("modules"),
10711
+ env: section("env"),
10712
+ keys: section("keys"),
10713
+ };
10714
+ }
10715
+ /**
10716
+ * Gives a new checkout a working development key: writes a random key and the
10717
+ * pointer to gitignored `.env.local` when it holds neither. An existing
10718
+ * variable is never changed, and the key is never returned or reported.
10719
+ */
10720
+ async function ensureLocalSecretsKey(cwd, config, commandRunner) {
10721
+ const changedFiles = [];
10722
+ const { activeKeyName, keyPrefix } = config.env;
10723
+ const envPath = join(cwd, ".env.local");
10724
+ const envText = await readTextIfExists(envPath);
10725
+ const existingName = [...readEnvAssignments(envText ?? "").keys()].find((name) => name === activeKeyName || name.startsWith(keyPrefix));
10726
+ if (existingName !== undefined) {
10727
+ return {
10728
+ changedFiles,
10729
+ notes: [
10730
+ `No development secrets key was generated: .env.local already sets ${existingName}, and Loom never changes an existing secrets variable.`,
10731
+ ],
10732
+ };
10733
+ }
10734
+ const tracked = await commandRunner("git", [
10735
+ "ls-files",
10736
+ "--error-unmatch",
10737
+ "--",
10738
+ ".env.local",
10739
+ ], { cwd, stdio: "pipe" });
10740
+ if (tracked.code === 0) {
10741
+ return {
10742
+ changedFiles,
10743
+ notes: [
10744
+ "No development secrets key was written: .env.local is tracked by Git. Remove it from the index, then rerun `loom add secrets`.",
10745
+ ],
10746
+ };
10747
+ }
10748
+ // Exit 1 is Git's answer that the file is untracked, and outside a
10749
+ // repository nothing can be tracked. Any other failure is not an answer.
10750
+ if (tracked.code !== 1 && !isNotAGitRepository(tracked)) {
10751
+ return {
10752
+ changedFiles,
10753
+ notes: [
10754
+ "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.",
10755
+ ],
10756
+ };
10757
+ }
10758
+ let envFileExists = true;
10759
+ try {
10760
+ if ((await lstat(envPath)).isSymbolicLink()) {
10761
+ return {
10762
+ changedFiles,
10763
+ notes: [
10764
+ "No development secrets key was written: .env.local is a symlink, and Loom will not write a key through it.",
10765
+ ],
10766
+ };
10767
+ }
10768
+ }
10769
+ catch (error) {
10770
+ if (!isNodeErrorCode(error, "ENOENT"))
10771
+ throw error;
10772
+ envFileExists = false;
10773
+ }
10774
+ const keyName = `${keyPrefix}1`;
10775
+ const merged = mergeEnvValues(envText, {
10776
+ [keyName]: toBase64Url(globalThis.crypto.getRandomValues(new Uint8Array(SECRETS_KEY_BYTES))),
10777
+ [activeKeyName]: "1",
10778
+ // Lets a production build run locally (`next start`): without it the
10779
+ // wrapper cannot tell this machine from an unidentified production host
10780
+ // once fingerprints are recorded, and refuses.
10781
+ [SECRETS_ENVIRONMENT_ENV]: "development",
10782
+ });
10783
+ // Ignored before the key exists on disk, so it is never an untracked file
10784
+ // that a broad `git add` would pick up. Git is asked first, because a rule
10785
+ // such as `.env*` already covers it; when Git cannot answer, the rule is
10786
+ // appended unless it is already the last one.
10787
+ const ignored = await commandRunner("git", [
10788
+ "check-ignore",
10789
+ "-q",
10790
+ "--",
10791
+ ".env.local",
10792
+ ], { cwd, stdio: "pipe" });
10793
+ if (ignored.code !== 0) {
10794
+ const gitignorePath = join(cwd, ".gitignore");
10795
+ const gitignore = await readTextIfExists(gitignorePath) ?? "";
10796
+ const lastIgnoreRule = normalizeText(gitignore).split("\n")
10797
+ .map((line) => line.trim()).filter(Boolean).at(-1);
10798
+ if (lastIgnoreRule !== ".env.local" && lastIgnoreRule !== "/.env.local") {
10799
+ if (await writeTextIfChanged(gitignorePath, `${gitignore && !gitignore.endsWith("\n")
10800
+ ? `${gitignore}\n`
10801
+ : gitignore}.env.local\n`))
10802
+ changedFiles.push(".gitignore");
10803
+ }
10804
+ }
10805
+ // An existing file keeps its mode when it is rewritten, so it is made
10806
+ // owner-only before the key is in it, not after.
10807
+ if (envFileExists)
10808
+ await chmod(envPath, 0o600);
10809
+ await writeFile(envPath, merged.text, { mode: 0o600 });
10810
+ await chmod(envPath, 0o600);
10811
+ changedFiles.push(".env.local");
10812
+ return {
10813
+ changedFiles,
10814
+ notes: [
10815
+ `Wrote a development secrets key to .env.local (${merged.changedNames.join(", ")}). It is for this machine only and was not printed.${merged.conflicts.length
10816
+ ? ` Left unchanged: ${merged.conflicts.join(", ")}.`
10817
+ : ""}`,
10818
+ ],
10819
+ };
10820
+ }
10821
+ async function applySecretsFeature(cwd, framework, manifest, activate, options = {}) {
10822
+ const changedFiles = [];
10823
+ const notes = [];
10824
+ const currentFeature = manifest.features.secrets;
10825
+ if (!activate && currentFeature?.status !== "active") {
10826
+ return { changedFiles, notes };
10827
+ }
10828
+ const config = getSecretsConfig(framework, currentFeature?.config);
10829
+ const feature = currentFeature
10830
+ ? structuredClone(currentFeature)
10831
+ : { status: "planned" };
10832
+ if (activate && feature.status !== "active") {
10833
+ feature.status = "active";
10834
+ feature.activatedOn ??= todayIso();
10835
+ }
10836
+ const scaffolds = [
10837
+ [config.modules.secretsModule, secretsModuleTemplate(config), "module"],
10838
+ [
10839
+ config.modules.locationsModule,
10840
+ secretLocationsModuleTemplate(),
10841
+ "locations module",
10842
+ ],
10843
+ ];
10844
+ for (const [relativePath, text, label] of scaffolds) {
10845
+ const scaffoldState = await scaffoldTextFile(join(cwd, relativePath), text);
10846
+ if (scaffoldState === "created") {
10847
+ changedFiles.push(relativePath);
10848
+ }
10849
+ else if (activate && scaffoldState === "preserved") {
10850
+ notes.push(`Preserved existing secrets ${label}: ${relativePath}`);
10851
+ }
10852
+ }
10853
+ // Only an explicit `loom add secrets` may create a key; `loom init` reruns
10854
+ // this hook for every active feature and must never write one.
10855
+ if (activate) {
10856
+ const localKey = await ensureLocalSecretsKey(cwd, config, options.commandRunner ?? defaultCommandRunner);
10857
+ changedFiles.push(...localKey.changedFiles);
10858
+ notes.push(...localKey.notes);
10859
+ if (!Array.isArray(config.keys.production) || !config.keys.production.length) {
10860
+ 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.");
10861
+ }
10862
+ }
10863
+ feature.config = mergeSecretsConfig(currentFeature?.config, config);
10864
+ manifest.features.secrets = feature;
10865
+ return { changedFiles, notes };
10866
+ }
10598
10867
  function linguiCliCommand(tooling) {
10599
10868
  switch (tooling.dependencies.manager) {
10600
10869
  case "deno":
@@ -13335,6 +13604,165 @@ async function checkPwaFeature(cwd, framework, manifest) {
13335
13604
  warnings,
13336
13605
  };
13337
13606
  }
13607
+ const VERCEL_PRODUCTION_ENV_POLICY_PATH = ".github/vercel-production-env.json";
13608
+ /**
13609
+ * Escapes text for use as a literal in a regular expression, in a form both
13610
+ * JavaScript and POSIX extended syntax (`git grep -E`) read the same way.
13611
+ */
13612
+ function escapeExtendedRegex(text) {
13613
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13614
+ }
13615
+ async function checkSecretsFeature(cwd, framework, manifest, options) {
13616
+ const issues = [];
13617
+ const warnings = [];
13618
+ const suggestions = new Set();
13619
+ const feature = manifest.features.secrets;
13620
+ if (!feature || feature.status !== "active") {
13621
+ return { issues, suggestions: [], warnings };
13622
+ }
13623
+ const releaseBlocking = (message) => {
13624
+ if (options.production)
13625
+ issues.push(message);
13626
+ else
13627
+ warnings.push(message);
13628
+ };
13629
+ const config = getSecretsConfig(framework, feature.config);
13630
+ const { activeKeyName, keyPrefix } = config.env;
13631
+ const moduleChecks = [
13632
+ [
13633
+ config.modules.secretsModule,
13634
+ "Secrets module",
13635
+ // A Next.js app must use the wrapper: the core entry point has no
13636
+ // build-phase refusal and no environment-selected key list.
13637
+ framework.kind === "nextjs"
13638
+ ? /["']@gadicc\/loom\/next\/secrets["']/
13639
+ : /["']@gadicc\/loom\/(?:next\/)?secrets["']/,
13640
+ "is not wired to @gadicc/loom/next/secrets",
13641
+ ],
13642
+ [
13643
+ config.modules.locationsModule,
13644
+ "Secret locations module",
13645
+ /\bdefineSecretLocations\b/,
13646
+ "does not declare its locations with defineSecretLocations",
13647
+ ],
13648
+ ];
13649
+ for (const [relativePath, label, pattern, problem] of moduleChecks) {
13650
+ const text = await readTextIfExists(join(cwd, relativePath));
13651
+ if (text === null) {
13652
+ issues.push(`${label} is missing: ${relativePath}`);
13653
+ suggestions.add("Run `loom add secrets`.");
13654
+ }
13655
+ else if (!pattern.test(text)) {
13656
+ issues.push(`${label} ${problem}: ${relativePath}`);
13657
+ 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.");
13658
+ }
13659
+ }
13660
+ for (const environment of ["production", "preview"]) {
13661
+ const recorded = config.keys[environment];
13662
+ if (recorded === undefined)
13663
+ continue;
13664
+ if (Array.isArray(recorded) && recorded.length === 0)
13665
+ continue;
13666
+ try {
13667
+ parseExpectedSecretKeys(recorded);
13668
+ }
13669
+ catch (error) {
13670
+ issues.push(`Secrets ${environment} key list in loom.json is invalid: ${error.message}`);
13671
+ suggestions.add("Correct features.secrets.config.keys in loom.json; `loom secrets keygen`, `activate` and `retire` keep it valid.");
13672
+ }
13673
+ }
13674
+ // Every tracked file is searched, not only root `.env*` files: a key is as
13675
+ // exposed in `deploy/.env.production` or a compose file. The pattern finds
13676
+ // candidates; only a value that decodes as a key is reported, so an
13677
+ // example file's placeholder is not. The pattern ends at the value's end,
13678
+ // so the first 43 characters of a longer value are not taken for a key.
13679
+ const keyAssignment = `${escapeExtendedRegex(keyPrefix)}[1-9][0-9]{0,8}["']?[[:space:]]*[=:][[:space:]]*["']?[A-Za-z0-9+/_-]{43}=?([^A-Za-z0-9+/_=-]|$)`;
13680
+ const gitResult = await (options.commandRunner ?? defaultCommandRunner)("git", ["grep", "-I", "--null", "-o", "-E", "-e", keyAssignment], { cwd, stdio: "pipe" });
13681
+ if (gitResult.code === 0) {
13682
+ const reported = new Set();
13683
+ for (const line of gitResult.stdout.split(/\r?\n/)) {
13684
+ const separator = line.indexOf("\0");
13685
+ if (separator < 0)
13686
+ continue;
13687
+ const relativePath = line.slice(0, separator);
13688
+ const match = line.slice(separator + 1).match(/^(.*?)["']?\s*[=:]\s*["']?([A-Za-z0-9+/_-]{43}=?)[^A-Za-z0-9+/_=-]?$/);
13689
+ if (!match)
13690
+ continue;
13691
+ const [, name, candidate] = match;
13692
+ try {
13693
+ decodeSecretKey(candidate, name);
13694
+ }
13695
+ catch {
13696
+ continue;
13697
+ }
13698
+ // Names the file and the variable only; the value must not reach a log.
13699
+ const issue = `A secrets key value is committed in a git-tracked file: ${relativePath} (${name})`;
13700
+ if (reported.has(issue))
13701
+ continue;
13702
+ reported.add(issue);
13703
+ issues.push(issue);
13704
+ 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.");
13705
+ }
13706
+ }
13707
+ else if (gitResult.code !== 1 && !isNotAGitRepository(gitResult)) {
13708
+ // Exit 1 means no match and, outside a repository, nothing is tracked.
13709
+ // Anything else means the search did not happen, which is not "clean".
13710
+ releaseBlocking("Git-tracked files could not be checked for a committed secrets key: `git grep` failed.");
13711
+ suggestions.add("Make sure Git is installed and `git grep` works in this project, then rerun `loom check`.");
13712
+ }
13713
+ if (Array.isArray(config.keys.production) && config.keys.production.length === 0) {
13714
+ releaseBlocking("No production secrets key is recorded in loom.json, so production would run with unverified keys.");
13715
+ suggestions.add("Have an operator run `loom secrets keygen` in their own terminal, then commit the recorded fingerprint.");
13716
+ }
13717
+ const policyText = await readTextIfExists(join(cwd, VERCEL_PRODUCTION_ENV_POLICY_PATH));
13718
+ if (policyText !== null) {
13719
+ let covered = false;
13720
+ // True until the policy has been read, so that an unreadable policy is
13721
+ // reported once and not also as a missing pointer.
13722
+ let pointerRequired = true;
13723
+ let problem = `has no requirement that covers the secrets keys (${keyPrefix}<n>) as Production-only Sensitive variables`;
13724
+ try {
13725
+ const requirements = parseVercelBuildEnvironmentPolicy(parseJson(policyText, VERCEL_PRODUCTION_ENV_POLICY_PATH));
13726
+ pointerRequired = requirements.some((requirement) => requirement.keys.includes(activeKeyName));
13727
+ covered = requirements.some((requirement) => requirement.keyPattern !== undefined &&
13728
+ // Several versions, so a pattern written for one key (`..._1$`) or
13729
+ // for a single digit does not pass for the keys that follow it.
13730
+ [1, 2, 10].every((version) => requirement.matches(`${keyPrefix}${version}`)) && requirement.sensitive && requirement.productionOnly);
13731
+ }
13732
+ catch (error) {
13733
+ problem = `could not be read: ${error.message}`;
13734
+ }
13735
+ if (!covered) {
13736
+ releaseBlocking(`Vercel release policy ${VERCEL_PRODUCTION_ENV_POLICY_PATH} ${problem}.`);
13737
+ }
13738
+ if (!pointerRequired) {
13739
+ 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.`);
13740
+ }
13741
+ if (!covered || !pointerRequired) {
13742
+ // Serialised as JSON so that a name with a character that needs
13743
+ // escaping, in the pattern or in the string, can be pasted as it is.
13744
+ // Both are shown whichever is missing: the policy needs the pair.
13745
+ const suggestedKeys = JSON.stringify({
13746
+ name: "secrets keys",
13747
+ keyPattern: `^${escapeExtendedRegex(keyPrefix)}[1-9][0-9]*$`,
13748
+ sensitive: true,
13749
+ productionOnly: true,
13750
+ placeholder: { kind: "secret" },
13751
+ });
13752
+ // The pointer is a readable variable, so it is not marked sensitive.
13753
+ const suggestedPointer = JSON.stringify({
13754
+ name: "secrets active key pointer",
13755
+ keys: [activeKeyName],
13756
+ });
13757
+ suggestions.add(`Add requirements such as ${suggestedKeys} and ${suggestedPointer} to ${VERCEL_PRODUCTION_ENV_POLICY_PATH}.`);
13758
+ }
13759
+ }
13760
+ return {
13761
+ issues,
13762
+ suggestions: [...suggestions],
13763
+ warnings,
13764
+ };
13765
+ }
13338
13766
  const featureHooks = {
13339
13767
  "api-keys": {
13340
13768
  apply: applyApiKeysFeature,
@@ -13370,6 +13798,10 @@ const featureHooks = {
13370
13798
  apply: applyPwaFeature,
13371
13799
  check: checkPwaFeature,
13372
13800
  },
13801
+ secrets: {
13802
+ apply: applySecretsFeature,
13803
+ check: checkSecretsFeature,
13804
+ },
13373
13805
  };
13374
13806
  async function ensureActiveFeatureScaffolds(cwd, framework, manifest) {
13375
13807
  const changedFiles = [];
@@ -13471,13 +13903,13 @@ export async function initProject(cwd, versionRange) {
13471
13903
  .packageJson,
13472
13904
  };
13473
13905
  }
13474
- export async function addFeature(cwd, featureKey, versionRange) {
13906
+ export async function addFeature(cwd, featureKey, versionRange, options = {}) {
13475
13907
  const hook = featureHooks[featureKey];
13476
13908
  if (!hook) {
13477
13909
  throw new Error(`Unknown feature: ${featureKey}`);
13478
13910
  }
13479
13911
  const base = await initProject(cwd, versionRange);
13480
- const result = await hook.apply(cwd, base.framework, base.manifest, true);
13912
+ const result = await hook.apply(cwd, base.framework, base.manifest, true, options);
13481
13913
  const skillSync = await ensureManagedSkillLinks(cwd, base.manifest);
13482
13914
  const changedFiles = [
13483
13915
  ...base.changedFiles,
@@ -13493,6 +13925,147 @@ export async function addFeature(cwd, featureKey, versionRange) {
13493
13925
  notes: [...new Set(notes)],
13494
13926
  };
13495
13927
  }
13928
+ async function readActiveSecretsFeature(cwd) {
13929
+ const manifest = await readManifestIfExists(cwd);
13930
+ if (!manifest) {
13931
+ throw new Error("Missing loom.json. Run `loom add secrets` first.");
13932
+ }
13933
+ const feature = manifest.features.secrets;
13934
+ if (feature?.status !== "active") {
13935
+ throw new Error("The secrets feature is not active. Run `loom add secrets` first.");
13936
+ }
13937
+ const framework = manifest.project?.framework ??
13938
+ await detectFramework(cwd, (await readProjectPackageJson(cwd)).packageJson);
13939
+ const config = getSecretsConfig(framework, feature.config);
13940
+ return { config, feature, manifest };
13941
+ }
13942
+ function recordedSecretKeys(config, environment) {
13943
+ const recorded = config.keys[environment] ?? [];
13944
+ if (!Array.isArray(recorded)) {
13945
+ throw new Error(`features.secrets.config.keys.${environment} in loom.json must be a list.`);
13946
+ }
13947
+ return recorded;
13948
+ }
13949
+ /** Validates a changed key list, then records it in loom.json. */
13950
+ async function writeSecretKeys(cwd, loaded, environment, keys) {
13951
+ if (keys.length) {
13952
+ try {
13953
+ parseExpectedSecretKeys(keys);
13954
+ }
13955
+ catch (error) {
13956
+ throw new Error(`The ${environment} key list in loom.json would be invalid: ${error.message}`);
13957
+ }
13958
+ }
13959
+ // Replaces this one list and nothing else: any other property a user keeps
13960
+ // under `config` or `config.keys` is theirs, and stays.
13961
+ const existing = isJsonObject(loaded.feature.config)
13962
+ ? loaded.feature.config
13963
+ : {};
13964
+ loaded.feature.config = {
13965
+ ...existing,
13966
+ keys: {
13967
+ ...(isJsonObject(existing.keys) ? existing.keys : {}),
13968
+ [environment]: keys,
13969
+ },
13970
+ };
13971
+ loaded.manifest.features.secrets = loaded.feature;
13972
+ return await writeManifestIfChanged(cwd, loaded.manifest)
13973
+ ? ["loom.json"]
13974
+ : [];
13975
+ }
13976
+ /**
13977
+ * Generates a key for a deployed environment and records its fingerprint in
13978
+ * loom.json: `active` when the environment has no active key, otherwise
13979
+ * `decrypt-only`. The version is one above the highest ever listed, so a
13980
+ * retired version is never reused. It always records: an unrecorded key
13981
+ * would let the next run give the same version to a different key.
13982
+ *
13983
+ * The returned `assignment` contains the key. A caller shows it once, to a
13984
+ * person at a terminal, and never logs or stores it.
13985
+ */
13986
+ export async function generateSecretsKey(cwd, options = {}) {
13987
+ const environment = options.environment ?? "production";
13988
+ const loaded = await readActiveSecretsFeature(cwd);
13989
+ const current = recordedSecretKeys(loaded.config, environment);
13990
+ const id = current.reduce((highest, key) => isSecretKeyId(key?.id) ? Math.max(highest, key.id) : highest, 0) + 1;
13991
+ const state = current.some((key) => key?.state === "active")
13992
+ ? "decrypt-only"
13993
+ : "active";
13994
+ const key = globalThis.crypto.getRandomValues(new Uint8Array(SECRETS_KEY_BYTES));
13995
+ const fingerprint = await secretKeyFingerprint(key);
13996
+ const changedFiles = await writeSecretKeys(cwd, loaded, environment, [
13997
+ ...current,
13998
+ { id, fingerprint, state },
13999
+ ]);
14000
+ const variableName = `${loaded.config.env.keyPrefix}${id}`;
14001
+ return {
14002
+ activeKeyName: loaded.config.env.activeKeyName,
14003
+ assignment: `${variableName}=${toBase64Url(key)}`,
14004
+ changedFiles,
14005
+ environment,
14006
+ fingerprint,
14007
+ id,
14008
+ state,
14009
+ variableName,
14010
+ };
14011
+ }
14012
+ /**
14013
+ * The public fingerprint of a key as an operator typed or pasted it, for
14014
+ * comparing a saved copy with what loom.json records. Errors never include
14015
+ * the key.
14016
+ */
14017
+ export async function fingerprintSecretsKey(value) {
14018
+ return await secretKeyFingerprint(decodeSecretKey(value, "The entered key"));
14019
+ }
14020
+ /**
14021
+ * Marks a recorded key `active` in loom.json and the previously active key
14022
+ * `decrypt-only`. Refuses a version that is not listed or is retired.
14023
+ */
14024
+ export async function activateSecretsKey(cwd, id, environment = "production") {
14025
+ const loaded = await readActiveSecretsFeature(cwd);
14026
+ const current = recordedSecretKeys(loaded.config, environment);
14027
+ const target = current.find((key) => key?.id === id);
14028
+ if (!target) {
14029
+ throw new Error(`Key version ${id} is not listed for ${environment} in loom.json.`);
14030
+ }
14031
+ if (target.state === "retired") {
14032
+ throw new Error(`Key version ${id} is retired and cannot be activated. Generate a new key with \`loom secrets keygen\`.`);
14033
+ }
14034
+ const changedFiles = await writeSecretKeys(cwd, loaded, environment, current.map((key) => key?.id === id
14035
+ ? { ...key, state: "active" }
14036
+ : key?.state === "active"
14037
+ ? { ...key, state: "decrypt-only" }
14038
+ : key));
14039
+ return {
14040
+ activeKeyName: loaded.config.env.activeKeyName,
14041
+ changedFiles,
14042
+ environment,
14043
+ id,
14044
+ };
14045
+ }
14046
+ /**
14047
+ * Marks a recorded key `retired` in loom.json. Refuses the active key and a
14048
+ * version that is not listed. Whether anything still needs the key is the
14049
+ * operator's decision; nothing here can check stored data or backups.
14050
+ */
14051
+ export async function retireSecretsKey(cwd, id, environment = "production") {
14052
+ const loaded = await readActiveSecretsFeature(cwd);
14053
+ const current = recordedSecretKeys(loaded.config, environment);
14054
+ const target = current.find((key) => key?.id === id);
14055
+ if (!target) {
14056
+ throw new Error(`Key version ${id} is not listed for ${environment} in loom.json.`);
14057
+ }
14058
+ if (target.state === "active") {
14059
+ throw new Error(`Key version ${id} is the active key and cannot be retired. Activate another key with \`loom secrets activate <id>\` first.`);
14060
+ }
14061
+ const changedFiles = await writeSecretKeys(cwd, loaded, environment, current.map((key) => key?.id === id ? { ...key, state: "retired" } : key));
14062
+ return {
14063
+ changedFiles,
14064
+ environment,
14065
+ id,
14066
+ variableName: `${loaded.config.env.keyPrefix}${id}`,
14067
+ };
14068
+ }
13496
14069
  function jobsRouteHasAuthorizationCallback(text) {
13497
14070
  if (!text)
13498
14071
  return false;
@@ -13595,7 +14168,7 @@ export async function configureApiKeyRetention(cwd, enabled, overrides = {}) {
13595
14168
  }
13596
14169
  export async function addSkills(cwd, versionRange, env = process.env, options = {}) {
13597
14170
  const base = await initProject(cwd, versionRange);
13598
- const skillSync = await syncExternalProjectSkills(cwd, getSkillsContext(base.packageJson, base.manifest), {
14171
+ const skillSync = await syncExternalProjectSkills(cwd, await getSkillsContext(cwd, base.packageJson, base.manifest), {
13599
14172
  acceptUnknownLicense: options.acceptUnknownLicense,
13600
14173
  adoptRecommended: !options.skillNames?.length,
13601
14174
  commandRunner: options.commandRunner ?? defaultCommandRunner,
@@ -13734,7 +14307,7 @@ export async function checkProject(cwd, env = process.env, options = {}) {
13734
14307
  suggestions.add(suggestion);
13735
14308
  }
13736
14309
  }
13737
- const projectSkillsCheck = await checkProjectSkills(cwd, getSkillsContext(packageJson, manifest), options.strictSkills);
14310
+ const projectSkillsCheck = await checkProjectSkills(cwd, await getSkillsContext(cwd, packageJson, manifest), options.strictSkills);
13738
14311
  warnings.push(...projectSkillsCheck.warnings);
13739
14312
  issues.push(...projectSkillsCheck.issues);
13740
14313
  for (const suggestion of projectSkillsCheck.suggestions) {
@@ -14271,7 +14844,7 @@ async function runStatus(cwd, io) {
14271
14844
  managedSkillLines.push(`${skill.skillName}: ${formatSkillLinkState(state)}`);
14272
14845
  }
14273
14846
  io.out(` managed: ${managedSkillLines.join("; ") || "none"}`);
14274
- const skillStatus = await getProjectSkillStatus(cwd, getSkillsContext(packageJson, manifest));
14847
+ const skillStatus = await getProjectSkillStatus(cwd, await getSkillsContext(cwd, packageJson, manifest));
14275
14848
  const packageSkillLines = skillStatus.packageSkills.map((skill) => `${skill.skillName} from ${skill.packageName} (${skill.disabled ? "disabled" : skill.active ? "active" : "available"})`);
14276
14849
  io.out(` npm packages: ${formatInlineList(packageSkillLines)}`);
14277
14850
  const externalSkillLines = skillStatus.external
@@ -14281,7 +14854,7 @@ async function runStatus(cwd, io) {
14281
14854
  : "recommended"}; license ${skill.licenseStatus})`);
14282
14855
  io.out(` external: ${formatInlineList(externalSkillLines)}`);
14283
14856
  io.out(` disabled: ${formatInlineList(skillStatus.disabled)}`);
14284
- io.out(" updates: run `loom skills sync` or `loom skills update`.");
14857
+ io.out(" updates: run `loom skills sync` to restore pins; review `loom skills update` to advance them.");
14285
14858
  return 0;
14286
14859
  }
14287
14860
  function printHelp({ out }) {
@@ -14296,11 +14869,15 @@ function printHelp({ out }) {
14296
14869
  out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local storage, and Files adapter wiring.");
14297
14870
  out(" api-keys integrate jobs Record an explicit API-key jobs integration after the route has session/admin authorization.");
14298
14871
  out(" api-keys retention enable|disable Record API-key audit cleanup policy; scheduling remains app-owned.");
14872
+ out(" secrets keygen Generate a production secrets key, print it once to a terminal, and record its fingerprint in loom.json.");
14873
+ out(" secrets fingerprint Read a secrets key from a hidden terminal prompt and print only its fingerprint.");
14874
+ out(" secrets activate <id> Record a listed secrets key as the active one; the previous active key becomes decrypt-only.");
14875
+ out(" secrets retire <id> Record a secrets key that nothing needs any more as retired.");
14299
14876
  out(" status Show the Loom package, manifest, active features, local-dev state, and project skill state.");
14300
14877
  out(" check Validate project bootstrap, managed guidance, features, skill locks, caches, and links.");
14301
14878
  out(" env -- <command> Load project .env* files with Next-compatible semantics, then run a command from the project root.");
14302
- out(" skills sync Activate npm package skills and hydrate locked external skills.");
14303
- out(" skills update Move adopted skills to Loom's reviewed upstream revisions.");
14879
+ out(" skills sync Restore recorded skill content and links without adopting updates.");
14880
+ out(" skills update Approve reviewed updates for adopted skills, or select names.");
14304
14881
  out(" db fixtures Run the Loom-managed DB fixture dump script for the active DB feature.");
14305
14882
  out(" db schema-gen Run the Loom-managed Valibot generator workflow for the active DB feature. Pass extra generator args after `--`.");
14306
14883
  out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
@@ -14322,7 +14899,7 @@ function printHelp({ out }) {
14322
14899
  out(" dev published Remove the managed local-dev override and return to the published dependency.");
14323
14900
  out("");
14324
14901
  out("Options:");
14325
- out(" --strict-skills Treat missing or stale recommended external skills as check failures.");
14902
+ out(" --strict-skills Treat invalid recorded skill content or links as check failures.");
14326
14903
  out(" --accept-unknown-license <skill> Explicitly adopt an upstream skill without a clear declared license.");
14327
14904
  out(" --network Run registered network checks after the local project checks.");
14328
14905
  out(" --production Treat local Loom dev overrides and local lockfile resolutions as release-blocking check failures.");
@@ -14354,6 +14931,7 @@ function printHelp({ out }) {
14354
14931
  out(" --token-expiry-days <days> Vercel release token lifetime (default 90).");
14355
14932
  out(" --timeout <duration> Bounded Vercel promotion wait (default 3m).");
14356
14933
  out(" --environment <name> GitHub Environment for migration credential setup (default production).");
14934
+ out(" --environment production|preview Key list a `loom secrets` command uses (default production).");
14357
14935
  out(" --env-file <path> Preserved env snapshot for `db migrations verify-env`; process values take precedence.");
14358
14936
  out(" --connect Authenticate and check migration database identity and schema privileges.");
14359
14937
  out(" --resource <name> Permission resource for API-key integration.");
@@ -14398,6 +14976,129 @@ async function runApiKeys(cwd, command, target, options, io) {
14398
14976
  io.out(`Note: ${note}`);
14399
14977
  return 0;
14400
14978
  }
14979
+ 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.";
14980
+ /**
14981
+ * Variables that an automated or agent session sets. A key must not be shown
14982
+ * to, or typed into, such a session even when it runs under a pseudo-terminal.
14983
+ */
14984
+ const AUTOMATED_SESSION_ENV_NAMES = [
14985
+ "CI",
14986
+ "GITHUB_ACTIONS",
14987
+ "CLAUDECODE",
14988
+ "CLAUDE_CODE_ENTRYPOINT",
14989
+ "AI_AGENT",
14990
+ "CODEX_SANDBOX",
14991
+ "CURSOR_AGENT",
14992
+ "GEMINI_CLI",
14993
+ ];
14994
+ async function runSecrets(cwd, command, target, options, io, terminal = {}) {
14995
+ 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]";
14996
+ const environmentOption = options.environment ?? "production";
14997
+ if (environmentOption !== "production" && environmentOption !== "preview") {
14998
+ io.err("--environment must be production or preview.");
14999
+ return 1;
15000
+ }
15001
+ const environment = environmentOption;
15002
+ const platformTarget = environment === "production"
15003
+ ? "Production"
15004
+ : "Preview";
15005
+ const stdinIsTty = terminal.stdinIsTty ?? Boolean(process.stdin.isTTY);
15006
+ const stdoutIsTty = terminal.stdoutIsTty ?? Boolean(process.stdout.isTTY);
15007
+ const sessionEnv = terminal.env ?? process.env;
15008
+ const automatedMarker = AUTOMATED_SESSION_ENV_NAMES.find((name) => Boolean(sessionEnv[name]));
15009
+ try {
15010
+ switch (command) {
15011
+ case "keygen": {
15012
+ // Deliberately no flag overrides these: the only safe destination for
15013
+ // a production key is the screen of the operator who will save it.
15014
+ // They are a guardrail, not proof that a person is watching; a
15015
+ // pseudo-terminal with a clean environment still passes.
15016
+ const refusal = automatedMarker
15017
+ ? `this is an automated or agent session`
15018
+ : !stdoutIsTty
15019
+ ? "its output is not a terminal"
15020
+ : !stdinIsTty
15021
+ ? "its input is not a terminal"
15022
+ : null;
15023
+ if (refusal) {
15024
+ 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.`);
15025
+ return 1;
15026
+ }
15027
+ const result = await generateSecretsKey(cwd, { environment });
15028
+ io.out(`Generated secrets key version ${result.id} for ${environment}. It is shown once and Loom keeps no copy.`);
15029
+ io.out("");
15030
+ io.out(result.assignment);
15031
+ io.out(`Fingerprint: ${result.fingerprint}`);
15032
+ io.out("");
15033
+ io.out(`Recorded the fingerprint in loom.json as ${result.state}. Commit loom.json; it holds no key.`);
15034
+ io.out("Next steps:");
15035
+ io.out(" 1. Save the key and its fingerprint in your password manager now, before anything else.");
15036
+ 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"
15037
+ ? `, and set ${result.activeKeyName}=${result.id} there`
15038
+ : ""}.`);
15039
+ io.out(" 3. Deploy.");
15040
+ io.out(` 4. Confirm \`secrets.assertReady()\` passes in the deployment: that proves the deployed key is the one you saved.${result.state === "active"
15041
+ ? ""
15042
+ : ` Then switch to it with \`loom secrets activate ${result.id}\`.`}`);
15043
+ return 0;
15044
+ }
15045
+ case "fingerprint": {
15046
+ // Checked before anything else, and never echoed: whatever followed
15047
+ // the command may be a key.
15048
+ if (target !== undefined) {
15049
+ io.err(SECRETS_FINGERPRINT_ARGUMENT_REFUSAL);
15050
+ return 1;
15051
+ }
15052
+ if (automatedMarker) {
15053
+ 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.`);
15054
+ return 1;
15055
+ }
15056
+ 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.";
15057
+ if (!stdinIsTty) {
15058
+ io.err(notInteractive);
15059
+ return 1;
15060
+ }
15061
+ const prompt = terminal.prompt ??
15062
+ ((question) => promptForTerminalValue(question, true, {
15063
+ cancelled: "Fingerprinting was cancelled.",
15064
+ notInteractive,
15065
+ }));
15066
+ io.out(await fingerprintSecretsKey(await prompt("Secrets key (input is hidden): ")));
15067
+ return 0;
15068
+ }
15069
+ case "activate":
15070
+ case "retire": {
15071
+ const id = target === undefined ? null : parseSecretKeyId(target);
15072
+ if (id === null) {
15073
+ io.err(usage);
15074
+ return 1;
15075
+ }
15076
+ if (command === "activate") {
15077
+ const result = await activateSecretsKey(cwd, id, environment);
15078
+ io.out(result.changedFiles.length
15079
+ ? `Updated ${result.changedFiles.join(", ")}: key version ${id} is now the active ${environment} key.`
15080
+ : `Key version ${id} is already the active ${environment} key in loom.json.`);
15081
+ 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).`);
15082
+ return 0;
15083
+ }
15084
+ const result = await retireSecretsKey(cwd, id, environment);
15085
+ io.out(result.changedFiles.length
15086
+ ? `Updated ${result.changedFiles.join(", ")}: key version ${id} is now retired for ${environment}.`
15087
+ : `Key version ${id} is already retired for ${environment} in loom.json.`);
15088
+ 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.`);
15089
+ return 0;
15090
+ }
15091
+ default:
15092
+ io.err(usage);
15093
+ return 1;
15094
+ }
15095
+ }
15096
+ catch (error) {
15097
+ // These are operator-facing refusals; a stack trace adds nothing.
15098
+ io.err(error.message);
15099
+ return 1;
15100
+ }
15101
+ }
14401
15102
  async function runFiles(cwd, command, target, options, io) {
14402
15103
  if (command === "id-generation") {
14403
15104
  if (target !== "uuid-v4" && target !== "uuid-v7") {
@@ -14593,12 +15294,12 @@ function printSkillsHelp({ out }) {
14593
15294
  out("");
14594
15295
  out("Commands:");
14595
15296
  out(" list Show discovered, adopted, disabled, and recommended skills.");
14596
- out(" add Adopt and install matching external skills.");
14597
- out(" sync Hydrate locked skills and activate npm package skills.");
15297
+ out(" add Adopt selected external or installed npm skills.");
15298
+ out(" sync Restore recorded skill content and links.");
14598
15299
  out(" check Validate project skill locks, caches, and links.");
14599
- out(" update Move adopted skills to Loom's reviewed catalog revisions.");
15300
+ out(" update Update adopted skills to reviewed catalog or installed npm content.");
14600
15301
  out(" migrate Replace legacy packaged-skill links with project installs.");
14601
- out(" disable Opt out of automatic activation for a skill.");
15302
+ out(" disable Disable a managed skill or opt out of a recommendation.");
14602
15303
  out(" enable Clear a skill opt-out; run sync afterward.");
14603
15304
  out("");
14604
15305
  out("Unlicensed external skills require `--accept-unknown-license <name>`.");
@@ -14624,7 +15325,7 @@ async function runSkills(cwd, command, args, io, options) {
14624
15325
  const manifest = manifestText
14625
15326
  ? parseJson(manifestText, "loom.json")
14626
15327
  : null;
14627
- const context = getSkillsContext(packageJson, manifest);
15328
+ const context = await getSkillsContext(cwd, packageJson, manifest);
14628
15329
  const accepted = options.acceptUnknownLicense
14629
15330
  ? [options.acceptUnknownLicense]
14630
15331
  : [];
@@ -14661,6 +15362,30 @@ async function runSkills(cwd, command, args, io, options) {
14661
15362
  case "migrate":
14662
15363
  case "sync":
14663
15364
  case "update": {
15365
+ if ((command === "sync" || command === "migrate") && args.length) {
15366
+ io.err(`loom skills ${command} restores locked state and does not select new skills.`);
15367
+ return 1;
15368
+ }
15369
+ const status = await getProjectSkillStatus(cwd, context);
15370
+ const locked = await readProjectSkillsLock(cwd);
15371
+ const packageNames = new Set(status.packageSkills.map((skill) => skill.skillName));
15372
+ const externalNames = new Set([
15373
+ ...status.external.map((skill) => skill.skillName),
15374
+ ...Object.keys(locked.skills).filter((name) => locked.skills[name].kind === "external"),
15375
+ ]);
15376
+ const unknown = args.filter((name) => !packageNames.has(name) && !externalNames.has(name));
15377
+ if (unknown.length) {
15378
+ io.err(`Unknown skill: ${unknown.join(", ")}`);
15379
+ return 1;
15380
+ }
15381
+ const ambiguous = args.filter((name) => !locked.skills[name] && packageNames.has(name) &&
15382
+ externalNames.has(name));
15383
+ if (ambiguous.length) {
15384
+ io.err(`Ambiguous skill source: ${ambiguous.join(", ")}. Choose and adopt the source explicitly before using its name.`);
15385
+ return 1;
15386
+ }
15387
+ const selectedPackages = args.filter((name) => locked.skills[name]?.kind === "package" ||
15388
+ (!locked.skills[name] && packageNames.has(name)));
14664
15389
  const nextGuidance = await ensureNextAgentsFile(cwd, packageJson);
14665
15390
  const migrationFiles = [];
14666
15391
  const migrationNotes = [];
@@ -14672,12 +15397,18 @@ async function runSkills(cwd, command, args, io, options) {
14672
15397
  migrationFiles.push(".agents/skills/next-best-practices");
14673
15398
  migrationNotes.push("Removed the retired next-best-practices link; use Next.js version-matched agent documentation.");
14674
15399
  }
14675
- const packageResult = await syncInstalledPackageSkills(cwd);
15400
+ const packageResult = await syncInstalledPackageSkills(cwd, {
15401
+ skillNames: selectedPackages,
15402
+ update: command === "update" && !args.length,
15403
+ });
14676
15404
  const externalResult = await syncExternalProjectSkills(cwd, context, {
14677
15405
  acceptUnknownLicense: accepted,
14678
- adoptRecommended: command === "add" || command === "migrate",
15406
+ adoptRecommended: command === "add" && !args.length,
15407
+ update: command === "update",
14679
15408
  commandRunner: defaultCommandRunner,
14680
- skillNames: args.length ? args : undefined,
15409
+ skillNames: args.length
15410
+ ? args.filter((name) => !selectedPackages.includes(name))
15411
+ : undefined,
14681
15412
  });
14682
15413
  if (await ensureExternalSkillsGitignore(cwd)) {
14683
15414
  externalResult.changedFiles.push(".gitignore");
@@ -15216,20 +15947,10 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
15216
15947
  }
15217
15948
  }
15218
15949
  async function runCheck(cwd, strictSkills, production, network, noProgress, noColor, io) {
15219
- const packageSkills = await syncInstalledPackageSkills(cwd);
15220
- if (packageSkills.changedFiles.length) {
15221
- io.out(`Updated ${packageSkills.changedFiles.join(", ")} while activating npm package skills.`);
15222
- }
15223
- for (const note of packageSkills.notes)
15224
- io.out(`Note: ${note}`);
15225
15950
  const localResult = await checkProject(cwd, process.env, {
15226
15951
  production,
15227
15952
  strictSkills,
15228
15953
  });
15229
- if (production && packageSkills.changedFiles.length) {
15230
- localResult.issues.push(`Production check activated or updated project skills: ${packageSkills.changedFiles.join(", ")}.`);
15231
- localResult.suggestions.push("Review and commit the project skill lock and activation links before release.");
15232
- }
15233
15954
  let result = localResult;
15234
15955
  if (network) {
15235
15956
  const reporter = createNetworkProgressReporter(io, {
@@ -15273,6 +15994,15 @@ export async function runCli(args = process.argv.slice(2), io = {
15273
15994
  err: (line) => console.error(line),
15274
15995
  out: (line) => console.log(line),
15275
15996
  }, options = {}) {
15997
+ // Checked before any argument is parsed: a parse error quotes the argument,
15998
+ // and a key pasted after `fingerprint` (base64url keys can begin with `-`)
15999
+ // must not be printed back.
16000
+ const secretsIndex = args.indexOf("secrets");
16001
+ if (secretsIndex >= 0 && args[secretsIndex + 1] === "fingerprint" &&
16002
+ args.length > secretsIndex + 2) {
16003
+ io.err(SECRETS_FINGERPRINT_ARGUMENT_REFUSAL);
16004
+ return 1;
16005
+ }
15276
16006
  const parsed = parseArgs({
15277
16007
  allowPositionals: true,
15278
16008
  args,
@@ -15337,6 +16067,9 @@ export async function runCli(args = process.argv.slice(2), io = {
15337
16067
  const addListOnly = command === "add" && arg1 === undefined;
15338
16068
  if (command !== undefined &&
15339
16069
  command !== "dev" &&
16070
+ // `loom secrets` reads and writes only loom.json and the terminal. A
16071
+ // sync would put build output and notes around a key shown once.
16072
+ command !== "secrets" &&
15340
16073
  command !== "skills" &&
15341
16074
  command !== "status" &&
15342
16075
  !addListOnly &&
@@ -15404,6 +16137,8 @@ export async function runCli(args = process.argv.slice(2), io = {
15404
16137
  maxRequestsPerKey: parsed.values["max-requests-per-key"],
15405
16138
  resource: parsed.values.resource,
15406
16139
  }, io);
16140
+ case "secrets":
16141
+ return await runSecrets(cwd, arg1, arg2, { environment: parsed.values.environment }, io, options.secretsTerminal);
15407
16142
  case "skills":
15408
16143
  return await runSkills(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
15409
16144
  acceptUnknownLicense: parsed.values["accept-unknown-license"],