@gadicc/loom 1.15.5 → 1.16.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.
@@ -56,6 +56,7 @@ exports.buildVercelFilesEnvProbeArgs = buildVercelFilesEnvProbeArgs;
56
56
  exports.setupCloudflareR2 = setupCloudflareR2;
57
57
  exports.buildVercelNeonSetupCommand = buildVercelNeonSetupCommand;
58
58
  exports.setupVercelNeon = setupVercelNeon;
59
+ exports.setupGithubMigrationCredential = setupGithubMigrationCredential;
59
60
  exports.setupGithubVercelRelease = setupGithubVercelRelease;
60
61
  exports.initProject = initProject;
61
62
  exports.addFeature = addFeature;
@@ -77,6 +78,8 @@ const node_process_1 = __importDefault(require("node:process"));
77
78
  const node_util_1 = require("node:util");
78
79
  const retention_js_1 = require("../apiKeys/retention.js");
79
80
  const projectSkills_js_1 = require("./projectSkills.js");
81
+ const migrationEnv_js_1 = require("./migrationEnv.js");
82
+ const vercelBuildEnv_js_1 = require("./vercelBuildEnv.js");
80
83
  exports.DEFAULT_LOOM_RANGE = "^1.0.0";
81
84
  exports.LOOM_DEPENDENCY = "@gadicc/loom";
82
85
  exports.LOOM_MANIFEST_SCHEMA = "https://loom.gadicc.local/project-manifest.schema.json";
@@ -112,6 +115,15 @@ const REQUIRED_GITHUB_VERCEL_ID_NAMES = [
112
115
  "VERCEL_ORG_ID",
113
116
  "VERCEL_PROJECT_ID",
114
117
  ];
118
+ const GITHUB_MIGRATION_DATABASE_SECRET_NAME = "MIGRATION_DATABASE_URL_UNPOOLED";
119
+ const GITHUB_MIGRATION_DATABASE_ROLE_VARIABLE_NAME = "LOOM_MIGRATION_DATABASE_ROLE";
120
+ const LEGACY_GITHUB_MIGRATION_DATABASE_SECRET_NAME = "DATABASE_URL_UNPOOLED";
121
+ const GITHUB_DATABASE_URL_VARIABLE_NAMES = [
122
+ "DATABASE_URL",
123
+ "DATABASE_URL_UNPOOLED",
124
+ "MIGRATION_DATABASE_URL",
125
+ "MIGRATION_DATABASE_URL_UNPOOLED",
126
+ ];
115
127
  const STALE_GITHUB_RELEASE_SECRET_NAMES = [
116
128
  "DATABASE_URL",
117
129
  "VERCEL_DEPLOY_HOOK",
@@ -2842,11 +2854,12 @@ function workflowStepQueriesVercelProductionEnvMetadata(block) {
2842
2854
  /\s--format(?:=|\s+)json\b/.test(block);
2843
2855
  }
2844
2856
  function workflowStepPreparesVercelBuildEnv(block) {
2845
- return /\bvercel-build-env(?:\.mjs)?\b[\s\S]*\bprepare\b/.test(block);
2857
+ return (/\bvercel-build-env(?:\.mjs)?\b[\s\S]*\bprepare\b/.test(block) ||
2858
+ /\bloom\b[\s\S]*\bdb\s+release\s+prepare-build-env\b/.test(block));
2846
2859
  }
2847
2860
  function workflowStepVerifiesVercelBuildEnv(block) {
2848
- return /\bvercel-build-env(?:\.mjs)?\b[\s\S]*\bverify\b/.test(block) &&
2849
- /\.vercel\/output\b/.test(block);
2861
+ return (/\bvercel-build-env(?:\.mjs)?\b[\s\S]*\bverify\b/.test(block) ||
2862
+ /\bloom\b[\s\S]*\bdb\s+release\s+verify-build-env\b/.test(block)) && /\.vercel\/output\b/.test(block);
2850
2863
  }
2851
2864
  function workflowStepStagesVercelProductionDeployment(block) {
2852
2865
  return workflowStepUsesVercelCommand(block, "deploy") &&
@@ -2882,6 +2895,12 @@ function workflowUsesGithubDatabaseUrlSecret(text) {
2882
2895
  function workflowUsesGithubUnpooledDatabaseUrlSecret(text) {
2883
2896
  return /\$\{\{\s*secrets\.DATABASE_URL_UNPOOLED\s*\}\}/.test(text);
2884
2897
  }
2898
+ function workflowUsesGithubMigrationDatabaseUrlSecret(text) {
2899
+ return /\$\{\{\s*secrets\.MIGRATION_DATABASE_URL(?:_UNPOOLED)?\s*\}\}/.test(text);
2900
+ }
2901
+ function workflowUsesGithubDatabaseUrlVariable(text) {
2902
+ return /\$\{\{\s*vars\.(?:MIGRATION_)?DATABASE_URL(?:_UNPOOLED)?\s*\}\}/.test(text);
2903
+ }
2885
2904
  function getGithubWorkflowJobBlocks(text) {
2886
2905
  const lines = normalizeText(text).split("\n");
2887
2906
  const jobsIndex = lines.findIndex((line) => /^\s*jobs:\s*(?:#.*)?$/.test(line));
@@ -2973,8 +2992,10 @@ function inspectDbMigrationWorkflow(relativePath, workflowText) {
2973
2992
  return {
2974
2993
  jobs,
2975
2994
  mainPush: githubWorkflowRunsOnMainPush(normalized),
2995
+ usesGithubDatabaseUrlVariable: workflowUsesGithubDatabaseUrlVariable(normalized),
2976
2996
  relativePath,
2977
2997
  usesGithubDatabaseUrlSecret: workflowUsesGithubDatabaseUrlSecret(normalized),
2998
+ usesGithubMigrationDatabaseUrlSecret: workflowUsesGithubMigrationDatabaseUrlSecret(normalized),
2978
2999
  usesGithubUnpooledDatabaseUrlSecret: workflowUsesGithubUnpooledDatabaseUrlSecret(normalized),
2979
3000
  usesOldVercelDeployHook: workflowUsesOldVercelDeployHook(normalized),
2980
3001
  };
@@ -2994,7 +3015,8 @@ function dbMigrationJobHasOrderedStagedRelease(job) {
2994
3015
  function dbMigrationWorkflowIsValid(workflow) {
2995
3016
  return workflow.jobs.some((job) => dbMigrationJobHasOrderedStagedRelease(job) &&
2996
3017
  job.promoteStepUsesExplicitScope &&
2997
- workflow.usesGithubUnpooledDatabaseUrlSecret);
3018
+ (workflow.usesGithubMigrationDatabaseUrlSecret ||
3019
+ workflow.usesGithubUnpooledDatabaseUrlSecret));
2998
3020
  }
2999
3021
  function isJsonObject(value) {
3000
3022
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -3052,6 +3074,9 @@ async function checkDbProductionMigrationFlow(cwd, production) {
3052
3074
  const validMigrationWorkflow = mainPushWorkflows.find(dbMigrationWorkflowIsValid);
3053
3075
  const oldDeployHookWorkflows = mainPushWorkflows.filter((inspection) => inspection.usesOldVercelDeployHook);
3054
3076
  const duplicatedDatabaseUrlWorkflows = mainPushWorkflows.filter((inspection) => inspection.usesGithubDatabaseUrlSecret);
3077
+ const databaseUrlVariableWorkflows = mainPushWorkflows.filter((inspection) => inspection.usesGithubDatabaseUrlVariable);
3078
+ const legacyUnpooledSecretWorkflows = mainPushWorkflows.filter((inspection) => inspection.usesGithubUnpooledDatabaseUrlSecret &&
3079
+ !inspection.usesGithubMigrationDatabaseUrlSecret);
3055
3080
  const vercelCurlWorkflowPaths = mainPushWorkflows.flatMap((inspection) => inspection.jobs.some((job) => job.vercelCurlStepIndex >= 0)
3056
3081
  ? [inspection.relativePath]
3057
3082
  : []);
@@ -3087,8 +3112,9 @@ async function checkDbProductionMigrationFlow(cwd, production) {
3087
3112
  findings.push("DB production migration flow does not restore the untouched pulled env before migrations: " +
3088
3113
  migrationWorkflowPaths.join(", "));
3089
3114
  }
3090
- else if (!mainPushWorkflows.some((inspection) => inspection.usesGithubUnpooledDatabaseUrlSecret)) {
3091
- findings.push("DB production migration flow is not ready for Sensitive database variables because it lacks a GitHub `DATABASE_URL_UNPOOLED` migration-secret binding: " +
3115
+ else if (!mainPushWorkflows.some((inspection) => inspection.usesGithubMigrationDatabaseUrlSecret ||
3116
+ inspection.usesGithubUnpooledDatabaseUrlSecret)) {
3117
+ findings.push("DB production migration flow is not ready for Sensitive database variables because it lacks a GitHub migration-secret binding: " +
3092
3118
  migrationWorkflowPaths.join(", "));
3093
3119
  }
3094
3120
  else if (mainPushWorkflows.some((inspection) => inspection.jobs.some((job) => dbMigrationJobHasOrderedStagedRelease(job) &&
@@ -3100,7 +3126,19 @@ async function checkDbProductionMigrationFlow(cwd, production) {
3100
3126
  findings.push("DB production migration flow does not order build, staged deploy, migration, and promotion correctly: " +
3101
3127
  migrationWorkflowPaths.join(", "));
3102
3128
  }
3103
- suggestions.add('Add a production GitHub Actions workflow that runs `vercel pull --environment=production --scope "$VERCEL_ORG_ID"`, preserves an untouched migration snapshot, masks usable pulled values, queries `vercel env ls production --format=json`, adds unique placeholders only for unreadable Sensitive build values, runs `vercel build --prod --scope "$VERCEL_ORG_ID"`, rejects placeholder leakage from `.vercel/output`, stages with `vercel deploy --prebuilt --prod --skip-domain --scope "$VERCEL_ORG_ID"`, restores the migration snapshot with an optional GitHub `DATABASE_URL_UNPOOLED` override, runs migrations, then runs `vercel promote --scope "$VERCEL_ORG_ID"`.');
3129
+ suggestions.add('Add a production GitHub Actions workflow that runs `vercel pull --environment=production --scope "$VERCEL_ORG_ID"`, preserves an untouched migration snapshot, masks usable pulled values, queries `vercel env ls production --format=json`, adds unique build-only placeholders for unreadable Sensitive values, runs `vercel build --prod --scope "$VERCEL_ORG_ID"`, rejects placeholder leakage from `.vercel/output`, stages with `vercel deploy --prebuilt --prod --skip-domain --scope "$VERCEL_ORG_ID"`, restores the migration snapshot with an optional GitHub `MIGRATION_DATABASE_URL_UNPOOLED` override, runs migrations, then runs `vercel promote --scope "$VERCEL_ORG_ID"`.');
3130
+ }
3131
+ if (legacyUnpooledSecretWorkflows.length) {
3132
+ warnings.push("DB production migration flow still uses the gradual-adoption GitHub secret `DATABASE_URL_UNPOOLED` instead of the migration-scoped `MIGRATION_DATABASE_URL_UNPOOLED`: " +
3133
+ legacyUnpooledSecretWorkflows.map((workflow) => workflow.relativePath)
3134
+ .join(", "));
3135
+ suggestions.add("When rotating the migration credential, store the new direct URL as the protected GitHub Environment secret `MIGRATION_DATABASE_URL_UNPOOLED` and update the workflow binding. The existing `DATABASE_URL_UNPOOLED` flow remains supported during gradual adoption.");
3136
+ }
3137
+ if (databaseUrlVariableWorkflows.length) {
3138
+ warnings.push("DB production migration flow reads a database URL from a readable GitHub Actions variable: " +
3139
+ databaseUrlVariableWorkflows.map((workflow) => workflow.relativePath)
3140
+ .join(", "));
3141
+ suggestions.add("Rotate that credential into the protected GitHub Environment secret `MIGRATION_DATABASE_URL_UNPOOLED`; keep GitHub variables for non-secret IDs and the expected migration role only.");
3104
3142
  }
3105
3143
  if (oldDeployHookWorkflows.length) {
3106
3144
  findings.push("DB production migration flow still references a Vercel Deploy Hook: " +
@@ -3111,7 +3149,7 @@ async function checkDbProductionMigrationFlow(cwd, production) {
3111
3149
  findings.push("DB production migration flow still reads `secrets.DATABASE_URL` from GitHub: " +
3112
3150
  duplicatedDatabaseUrlWorkflows.map((workflow) => workflow.relativePath)
3113
3151
  .join(", "));
3114
- suggestions.add("Remove the duplicate GitHub `DATABASE_URL`. While Vercel database variables remain readable, migrate with an untouched `vercel pull` snapshot; before making them Sensitive, store only `DATABASE_URL_UNPOOLED` in the protected GitHub Environment and overlay it for the migration step.");
3152
+ suggestions.add("Remove the duplicate GitHub `DATABASE_URL`. While Vercel database variables remain readable, migrate with an untouched `vercel pull` snapshot; before making them Sensitive, store only `MIGRATION_DATABASE_URL_UNPOOLED` in the protected GitHub Environment and expose it to the migration step.");
3115
3153
  }
3116
3154
  if (vercelCurlWorkflowPaths.length) {
3117
3155
  findings.push("DB production migration flow still uses beta `vercel curl` for smoke checks: " +
@@ -5493,6 +5531,32 @@ function createGithubReleaseConfigCheckStep(state, context) {
5493
5531
  suggestions.add(`After confirming no other workflow uses it, run \`gh secret delete ${staleSecret}\`.`);
5494
5532
  }
5495
5533
  }
5534
+ const hasCanonicalMigrationSecret = environmentSecrets.names.has(GITHUB_MIGRATION_DATABASE_SECRET_NAME);
5535
+ const hasRepositoryCanonicalMigrationSecret = repoSecrets.names.has(GITHUB_MIGRATION_DATABASE_SECRET_NAME);
5536
+ const hasLegacyMigrationSecret = collectionHasName(LEGACY_GITHUB_MIGRATION_DATABASE_SECRET_NAME, environmentSecrets, repoSecrets);
5537
+ if (!hasCanonicalMigrationSecret) {
5538
+ if (hasRepositoryCanonicalMigrationSecret) {
5539
+ warnings.push(`GitHub Actions stores ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} at repository scope instead of the protected ${PRODUCTION_GITHUB_ENVIRONMENT} environment.`);
5540
+ }
5541
+ else if (hasLegacyMigrationSecret) {
5542
+ warnings.push(`GitHub Actions still uses the gradual-adoption migration secret ${LEGACY_GITHUB_MIGRATION_DATABASE_SECRET_NAME}; rotate into ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} when convenient.`);
5543
+ }
5544
+ else {
5545
+ warnings.push(`GitHub Actions has no dedicated ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} production secret. The existing pulled Vercel URL remains supported while it is readable.`);
5546
+ }
5547
+ suggestions.add("Provision a dedicated direct migration credential, then run `loom db migrations setup-github` to store it without making the Vercel integration variables Sensitive yet.");
5548
+ }
5549
+ if (hasCanonicalMigrationSecret &&
5550
+ findGithubVariableValue(GITHUB_MIGRATION_DATABASE_ROLE_VARIABLE_NAME, environmentVariables, repoVariables) === null) {
5551
+ warnings.push(`GitHub Actions has ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} but no ${GITHUB_MIGRATION_DATABASE_ROLE_VARIABLE_NAME} metadata variable.`);
5552
+ suggestions.add("Run `loom db migrations setup-github` with the migration URL loaded in the environment so Loom can record the expected non-secret role.");
5553
+ }
5554
+ for (const name of GITHUB_DATABASE_URL_VARIABLE_NAMES) {
5555
+ if (collectionHasName(name, environmentVariables, repoVariables)) {
5556
+ warnings.push(`GitHub Actions stores database credential ${name} as a readable variable.`);
5557
+ suggestions.add(`Rotate ${name} into the protected ${PRODUCTION_GITHUB_ENVIRONMENT} Environment secret ${GITHUB_MIGRATION_DATABASE_SECRET_NAME}, then delete the readable variable.`);
5558
+ }
5559
+ }
5496
5560
  if (collectionHasName("VERCEL_DEPLOY_HOOK", environmentSecrets, repoSecrets) ||
5497
5561
  [...STALE_GITHUB_RELEASE_SECRET_NAMES].some((name) => name.startsWith("VERCEL_DEPLOY") &&
5498
5562
  collectionHasName(name, environmentSecrets, repoSecrets))) {
@@ -6083,6 +6147,54 @@ async function setupVercelNeon(cwd, options = {}) {
6083
6147
  notes,
6084
6148
  };
6085
6149
  }
6150
+ /**
6151
+ * Stores an already-provisioned direct migration URL in a protected GitHub
6152
+ * Environment without persisting or printing the credential.
6153
+ */
6154
+ async function setupGithubMigrationCredential(cwd, options = {}) {
6155
+ const commandRunner = options.commandRunner ?? defaultCommandRunner;
6156
+ const env = options.env ?? node_process_1.default.env;
6157
+ const environment = options.environment ?? PRODUCTION_GITHUB_ENVIRONMENT;
6158
+ const migration = (0, migrationEnv_js_1.resolveMigrationEnvironment)(env);
6159
+ if (!migration.envName.startsWith("MIGRATION_")) {
6160
+ throw new Error(`Load ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} in the process environment before running \`loom db migrations setup-github\`; application database fallbacks are not copied into GitHub.`);
6161
+ }
6162
+ if (!migration.direct) {
6163
+ throw new Error(`${migration.envName} appears pooled. Configure a direct, unpooled migration connection before storing it in GitHub.`);
6164
+ }
6165
+ const githubCli = await detectGithubCliCommand(cwd, commandRunner, env);
6166
+ if (!githubCli.command) {
6167
+ throw new Error("GitHub CLI is not available. Install and authenticate `gh` before running `loom db migrations setup-github`.");
6168
+ }
6169
+ await requireCommand(`Set GitHub ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} secret`, commandRunner, githubCli.command, [
6170
+ "secret",
6171
+ "set",
6172
+ GITHUB_MIGRATION_DATABASE_SECRET_NAME,
6173
+ "--env",
6174
+ environment,
6175
+ ], {
6176
+ cwd,
6177
+ env,
6178
+ input: env[migration.envName],
6179
+ stdio: "pipe",
6180
+ });
6181
+ await requireCommand(`Set GitHub ${GITHUB_MIGRATION_DATABASE_ROLE_VARIABLE_NAME} variable`, commandRunner, githubCli.command, [
6182
+ "variable",
6183
+ "set",
6184
+ GITHUB_MIGRATION_DATABASE_ROLE_VARIABLE_NAME,
6185
+ "--env",
6186
+ environment,
6187
+ "--body",
6188
+ migration.role,
6189
+ ], { cwd, env, stdio: "pipe" });
6190
+ return {
6191
+ notes: [
6192
+ `Stored ${GITHUB_MIGRATION_DATABASE_SECRET_NAME} in the protected GitHub \`${environment}\` environment.`,
6193
+ `Recorded migration role ${migration.role} as ${GITHUB_MIGRATION_DATABASE_ROLE_VARIABLE_NAME}.`,
6194
+ "Vercel application database variables were not changed.",
6195
+ ],
6196
+ };
6197
+ }
6086
6198
  async function setupGithubVercelRelease(cwd, options = {}) {
6087
6199
  const commandRunner = options.commandRunner ?? defaultCommandRunner;
6088
6200
  const env = options.env ?? node_process_1.default.env;
@@ -8545,7 +8657,11 @@ function printHelp({ out }) {
8545
8657
  out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
8546
8658
  out(" db neon setup Provision and connect a Vercel-managed Neon database for Production and Preview.");
8547
8659
  out(" db neon check Run the DB/Neon network checks registered for the active DB feature.");
8660
+ out(" db migrations verify-env Validate migration URL precedence and role metadata without printing credentials.");
8661
+ out(" db migrations setup-github Store an existing direct migration URL as a protected GitHub Environment secret.");
8548
8662
  out(" db release setup-github Create/update GitHub production release config for staged Vercel deploys.");
8663
+ out(" db release prepare-build-env <env> <metadata> <policy> <manifest> Prepare metadata-backed placeholders for an external Vercel build.");
8664
+ out(" db release verify-build-env <output> <manifest> Reject build-only placeholders in a deployable Vercel artifact.");
8549
8665
  out(" dev local Enable local Loom development using a managed file: override in pnpm-workspace.yaml.");
8550
8666
  out(" dev sync Rebuild the local Loom package and refresh this project's pnpm install when the managed local-dev override is active.");
8551
8667
  out(" dev published Remove the managed local-dev override and return to the published dependency.");
@@ -8574,6 +8690,7 @@ function printHelp({ out }) {
8574
8690
  out(" --configure-secrets Ask Vercel to prompt securely for missing R2 credentials; never replaces existing credentials.");
8575
8691
  out(" --repair Apply declared non-secret Files provider drift; never deletes resources or rotates credentials.");
8576
8692
  out(" --token-name <name> Override the Vercel token name for `loom db release setup-github`.");
8693
+ out(" --environment <name> GitHub Environment for migration credential setup (default production).");
8577
8694
  out(" --resource <name> Permission resource for API-key integration.");
8578
8695
  out(" --action <name> Permission action for API-key integration.");
8579
8696
  out(" --allow-query Allow the integration's explicit query credential transport.");
@@ -9100,14 +9217,39 @@ async function runDbNeon(cwd, command, io, options) {
9100
9217
  return 1;
9101
9218
  }
9102
9219
  }
9103
- async function runDbRelease(cwd, command, io, options) {
9220
+ async function runDbRelease(cwd, command, args, io, options) {
9104
9221
  if (!command) {
9105
9222
  io.err("Missing release subcommand. Example: `loom db release setup-github`.");
9106
9223
  return 1;
9107
9224
  }
9108
9225
  switch (command) {
9226
+ case "prepare-build-env": {
9227
+ if (args.length !== 4) {
9228
+ io.err("Usage: loom db release prepare-build-env <env-file> <metadata-file> <policy-file> <manifest-file>");
9229
+ return 1;
9230
+ }
9231
+ (0, vercelBuildEnv_js_1.prepareVercelBuildEnvironment)({
9232
+ envFile: (0, node_path_1.resolve)(cwd, args[0]),
9233
+ manifestFile: (0, node_path_1.resolve)(cwd, args[3]),
9234
+ metadataFile: (0, node_path_1.resolve)(cwd, args[1]),
9235
+ policyFile: (0, node_path_1.resolve)(cwd, args[2]),
9236
+ }, io);
9237
+ return 0;
9238
+ }
9239
+ case "verify-build-env": {
9240
+ if (args.length !== 2) {
9241
+ io.err("Usage: loom db release verify-build-env <output-directory> <manifest-file>");
9242
+ return 1;
9243
+ }
9244
+ (0, vercelBuildEnv_js_1.verifyVercelBuildArtifact)({
9245
+ manifestFile: (0, node_path_1.resolve)(cwd, args[1]),
9246
+ outputDirectory: (0, node_path_1.resolve)(cwd, args[0]),
9247
+ }, io);
9248
+ return 0;
9249
+ }
9109
9250
  case "setup-github": {
9110
9251
  const result = await setupGithubVercelRelease(cwd, {
9252
+ environment: options.environment,
9111
9253
  io,
9112
9254
  tokenName: options.tokenName,
9113
9255
  });
@@ -9123,6 +9265,39 @@ async function runDbRelease(cwd, command, io, options) {
9123
9265
  return 1;
9124
9266
  }
9125
9267
  }
9268
+ async function runDbMigrations(cwd, command, io, options) {
9269
+ if (!command) {
9270
+ io.err("Missing migrations subcommand. Example: `loom db migrations verify-env`.");
9271
+ return 1;
9272
+ }
9273
+ switch (command) {
9274
+ case "setup-github": {
9275
+ const result = await setupGithubMigrationCredential(cwd, {
9276
+ environment: options.environment,
9277
+ });
9278
+ for (const note of result.notes) {
9279
+ io.out(`Note: ${note}`);
9280
+ }
9281
+ io.out("Next step: update the release workflow to bind `secrets.MIGRATION_DATABASE_URL_UNPOOLED`, then run `loom check --production --network`.");
9282
+ return 0;
9283
+ }
9284
+ case "verify-env": {
9285
+ const result = (0, migrationEnv_js_1.resolveMigrationEnvironment)(node_process_1.default.env);
9286
+ io.out(`Migration database environment is usable: ${result.envName} selects role ${result.role} and database ${result.database}.`);
9287
+ if (!result.envName.startsWith("MIGRATION_")) {
9288
+ io.out("Warning: using the gradual-adoption application database fallback; prefer MIGRATION_DATABASE_URL_UNPOOLED after provisioning a dedicated migration credential.");
9289
+ }
9290
+ if (!result.direct) {
9291
+ io.out("Warning: the selected URL appears pooled; migrations should prefer a direct, unpooled connection.");
9292
+ }
9293
+ return 0;
9294
+ }
9295
+ default:
9296
+ io.err(`Unknown migrations subcommand: ${command}`);
9297
+ io.err("Run `loom --help` for usage.");
9298
+ return 1;
9299
+ }
9300
+ }
9126
9301
  async function runDb(cwd, command, args, io, options = {}) {
9127
9302
  if (!command) {
9128
9303
  io.err("Missing db subcommand. Example: `loom db schema-gen`.");
@@ -9137,8 +9312,10 @@ async function runDb(cwd, command, args, io, options = {}) {
9137
9312
  return await runDbSchemas(cwd, args[0], io);
9138
9313
  case "neon":
9139
9314
  return await runDbNeon(cwd, args[0], io, options);
9315
+ case "migrations":
9316
+ return await runDbMigrations(cwd, args[0], io, options);
9140
9317
  case "release":
9141
- return await runDbRelease(cwd, args[0], io, options);
9318
+ return await runDbRelease(cwd, args[0], args.slice(1), io, options);
9142
9319
  default:
9143
9320
  io.err(`Unknown db subcommand: ${command}`);
9144
9321
  io.err("Run `loom --help` for usage.");
@@ -9284,6 +9461,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
9284
9461
  "cleanup-batch-size": { type: "string" },
9285
9462
  "configure-secrets": { type: "boolean" },
9286
9463
  cwd: { type: "string" },
9464
+ environment: { type: "string" },
9287
9465
  force: { type: "boolean" },
9288
9466
  help: { short: "h", type: "boolean" },
9289
9467
  jurisdiction: { type: "string" },
@@ -9386,6 +9564,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
9386
9564
  case "db":
9387
9565
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
9388
9566
  name: parsed.values.name,
9567
+ environment: parsed.values.environment,
9389
9568
  noColor: parsed.values["no-color"],
9390
9569
  noProgress: parsed.values["no-progress"],
9391
9570
  neonAuth: parsed.values["neon-auth"],
@@ -0,0 +1,30 @@
1
+ type BuildPlaceholder = {
2
+ key: string;
3
+ marker: string;
4
+ requirement: string;
5
+ };
6
+ type CliOutput = {
7
+ out: (line: string) => void;
8
+ };
9
+ export declare function isUsablePulledValue(value: string | undefined): boolean;
10
+ /**
11
+ * Validates required Production variables and fills unreadable Sensitive values
12
+ * with unique build-only placeholders without replacing readable pulled values.
13
+ */
14
+ export declare function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataFile, policyFile, }: {
15
+ envFile: string;
16
+ manifestFile: string;
17
+ metadataFile: string;
18
+ policyFile: string;
19
+ }, io?: CliOutput): {
20
+ placeholders: BuildPlaceholder[];
21
+ };
22
+ /**
23
+ * Rejects a Vercel artifact containing any unique build-only marker.
24
+ */
25
+ export declare function verifyVercelBuildArtifact({ manifestFile, outputDirectory, }: {
26
+ manifestFile: string;
27
+ outputDirectory: string;
28
+ }, io?: CliOutput): void;
29
+ export {};
30
+ //# sourceMappingURL=vercelBuildEnv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercelBuildEnv.d.ts","sourceRoot":"","sources":["../../../src/src/cli/vercelBuildEnv.ts"],"names":[],"mappings":"AAyBA,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAMF,KAAK,SAAS,GAAG;IACf,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7B,CAAC;AAgBF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,WAG5D;AAmFD;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,EACE,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,UAAU,GACX,EAAE;IACD,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;CACpB,EACD,EAAE,GAAE,SAAgD;;EAoGrD;AAeD;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,EACE,YAAY,EACZ,eAAe,GAChB,EAAE;IACD,YAAY,EAAE,MAAM,CAAC;IACrB,eAAe,EAAE,MAAM,CAAC;CACzB,EACD,EAAE,GAAE,SAAgD,QAyCrD"}
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isUsablePulledValue = isUsablePulledValue;
4
+ exports.prepareVercelBuildEnvironment = prepareVercelBuildEnvironment;
5
+ exports.verifyVercelBuildArtifact = verifyVercelBuildArtifact;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const node_fs_1 = require("node:fs");
8
+ const node_path_1 = require("node:path");
9
+ const node_util_1 = require("node:util");
10
+ function readJson(path) {
11
+ return JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
12
+ }
13
+ function productionEntries(envs, keys) {
14
+ const keySet = new Set(keys);
15
+ return envs.filter((entry) => {
16
+ const targets = Array.isArray(entry.target) ? entry.target : [entry.target];
17
+ return typeof entry.key === "string" &&
18
+ keySet.has(entry.key) &&
19
+ targets.includes("production");
20
+ });
21
+ }
22
+ function isUsablePulledValue(value) {
23
+ return Boolean(value?.trim()) &&
24
+ !/(?:sensitive|redacted)/i.test(value ?? "");
25
+ }
26
+ function buildPlaceholder(kind) {
27
+ const marker = `loom-build-only-${(0, node_crypto_1.randomBytes)(32).toString("hex")}`;
28
+ if (kind === "secret") {
29
+ return { marker, value: marker };
30
+ }
31
+ if (kind === "postgres-url") {
32
+ return {
33
+ marker,
34
+ value: `postgresql://build:${marker}@127.0.0.1:1/build?sslmode=disable`,
35
+ };
36
+ }
37
+ throw new Error(`Unsupported placeholder kind: ${kind}`);
38
+ }
39
+ function setEnvValue(source, key, value) {
40
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(key)) {
41
+ throw new Error(`Invalid environment variable key in policy: ${key}`);
42
+ }
43
+ const line = `${key}=${JSON.stringify(value)}`;
44
+ const pattern = new RegExp(`^${key}=.*$`, "m");
45
+ if (pattern.test(source)) {
46
+ return source.replace(pattern, line);
47
+ }
48
+ return `${source.trimEnd()}\n${line}\n`;
49
+ }
50
+ function parsePolicyRequirement(value, index) {
51
+ if (typeof value !== "object" || value === null) {
52
+ throw new Error(`Vercel environment requirement ${index + 1} is invalid.`);
53
+ }
54
+ const requirement = value;
55
+ const name = typeof requirement.name === "string" &&
56
+ requirement.name.trim()
57
+ ? requirement.name
58
+ : `requirement ${index + 1}`;
59
+ const keys = Array.isArray(requirement.keys)
60
+ ? requirement.keys.filter((key) => typeof key === "string" && Boolean(key))
61
+ : [];
62
+ if (keys.length === 0) {
63
+ throw new Error(`Environment requirement "${name}" has no keys.`);
64
+ }
65
+ let placeholder;
66
+ if (requirement.placeholder !== undefined) {
67
+ if (typeof requirement.placeholder !== "object" ||
68
+ requirement.placeholder === null ||
69
+ typeof requirement.placeholder.key !== "string" ||
70
+ typeof requirement.placeholder.kind !== "string") {
71
+ throw new Error(`Environment requirement "${name}" has an invalid placeholder policy.`);
72
+ }
73
+ placeholder = {
74
+ key: requirement.placeholder.key,
75
+ kind: requirement.placeholder.kind,
76
+ };
77
+ }
78
+ return {
79
+ keys,
80
+ name,
81
+ placeholder,
82
+ sensitive: requirement.sensitive === true,
83
+ };
84
+ }
85
+ /**
86
+ * Validates required Production variables and fills unreadable Sensitive values
87
+ * with unique build-only placeholders without replacing readable pulled values.
88
+ */
89
+ function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataFile, policyFile, }, io = { out: (line) => console.log(line) }) {
90
+ let envSource = (0, node_fs_1.readFileSync)(envFile, "utf8");
91
+ const pulledValues = (0, node_util_1.parseEnv)(envSource);
92
+ const metadata = readJson(metadataFile);
93
+ const policy = readJson(policyFile);
94
+ const envs = typeof metadata === "object" && metadata !== null
95
+ ? metadata.envs
96
+ : undefined;
97
+ if (!Array.isArray(envs)) {
98
+ throw new Error("Vercel metadata did not contain an envs array.");
99
+ }
100
+ if (!Array.isArray(policy.requirements)) {
101
+ throw new Error("Vercel environment policy has no requirements array.");
102
+ }
103
+ const placeholders = [];
104
+ for (const [index, value] of policy.requirements.entries()) {
105
+ const requirement = parsePolicyRequirement(value, index);
106
+ const entries = productionEntries(envs, requirement.keys);
107
+ if (entries.length === 0) {
108
+ throw new Error(`Missing Vercel Production variable for ${requirement.name}: ${requirement.keys.join(" or ")}`);
109
+ }
110
+ const nonSensitive = entries.filter((entry) => entry.type !== "sensitive");
111
+ if (requirement.sensitive && nonSensitive.length > 0) {
112
+ throw new Error(`Vercel Production variable must be Sensitive for ${requirement.name}: ${nonSensitive
113
+ .map((entry) => entry.key)
114
+ .join(", ")}`);
115
+ }
116
+ const pulledKey = requirement.keys.find((key) => isUsablePulledValue(pulledValues[key]));
117
+ if (pulledKey) {
118
+ io.out(`Verified ${requirement.name} from vercel pull (${pulledKey}).`);
119
+ continue;
120
+ }
121
+ const unreadableSensitive = entries.every((entry) => entry.type === "sensitive");
122
+ if (!unreadableSensitive) {
123
+ throw new Error(`Vercel Production variable is empty after pull for ${requirement.name}: ${requirement.keys.join(" or ")}`);
124
+ }
125
+ if (!requirement.placeholder) {
126
+ throw new Error(`Sensitive Vercel Production variable has no build placeholder policy for ${requirement.name}.`);
127
+ }
128
+ const placeholderKey = requirement.placeholder.key;
129
+ if (isUsablePulledValue(pulledValues[placeholderKey])) {
130
+ io.out(`Preserved pulled ${placeholderKey} for ${requirement.name}.`);
131
+ continue;
132
+ }
133
+ const placeholder = buildPlaceholder(requirement.placeholder.kind);
134
+ envSource = setEnvValue(envSource, placeholderKey, placeholder.value);
135
+ pulledValues[placeholderKey] = placeholder.value;
136
+ placeholders.push({
137
+ key: placeholderKey,
138
+ marker: placeholder.marker,
139
+ requirement: requirement.name,
140
+ });
141
+ io.out(`Added a build-only ${placeholderKey} placeholder for ${requirement.name}.`);
142
+ }
143
+ (0, node_fs_1.writeFileSync)(envFile, envSource, { mode: 0o600 });
144
+ (0, node_fs_1.writeFileSync)(manifestFile, `${JSON.stringify({ placeholders }, null, 2)}\n`, { mode: 0o600 });
145
+ (0, node_fs_1.chmodSync)(envFile, 0o600);
146
+ (0, node_fs_1.chmodSync)(manifestFile, 0o600);
147
+ return { placeholders };
148
+ }
149
+ function regularFiles(root) {
150
+ const files = [];
151
+ for (const entry of (0, node_fs_1.readdirSync)(root, { withFileTypes: true })) {
152
+ const path = (0, node_path_1.join)(root, entry.name);
153
+ if (entry.isDirectory()) {
154
+ files.push(...regularFiles(path));
155
+ }
156
+ else if (entry.isFile()) {
157
+ files.push(path);
158
+ }
159
+ }
160
+ return files;
161
+ }
162
+ /**
163
+ * Rejects a Vercel artifact containing any unique build-only marker.
164
+ */
165
+ function verifyVercelBuildArtifact({ manifestFile, outputDirectory, }, io = { out: (line) => console.log(line) }) {
166
+ const manifest = readJson(manifestFile);
167
+ if (!Array.isArray(manifest.placeholders)) {
168
+ throw new Error("Build placeholder manifest is invalid.");
169
+ }
170
+ const placeholders = manifest.placeholders.filter((value) => typeof value === "object" &&
171
+ value !== null &&
172
+ typeof value.key === "string" &&
173
+ typeof value.marker === "string" &&
174
+ typeof value.requirement === "string");
175
+ if (placeholders.length !== manifest.placeholders.length) {
176
+ throw new Error("Build placeholder manifest is invalid.");
177
+ }
178
+ const leaks = [];
179
+ for (const path of regularFiles(outputDirectory)) {
180
+ const contents = (0, node_fs_1.readFileSync)(path);
181
+ for (const placeholder of placeholders) {
182
+ if (contents.includes(Buffer.from(placeholder.marker))) {
183
+ leaks.push(`${placeholder.key}: ${path}`);
184
+ }
185
+ }
186
+ }
187
+ if (leaks.length > 0) {
188
+ throw new Error(`Build-only environment placeholder reached the deployable artifact:\n${leaks.join("\n")}`);
189
+ }
190
+ io.out(`Verified ${placeholders.length} build-only placeholder(s) are absent from ${(0, node_path_1.basename)(outputDirectory)}.`);
191
+ }
@@ -68,8 +68,10 @@ from the consumer's working directory.
68
68
  values, add unique build-only placeholders only for confirmed Sensitive
69
69
  entries, and reject an artifact containing any placeholder marker. Preserve an
70
70
  untouched pull snapshot for migrations; once database variables are Sensitive,
71
- overlay a separately governed GitHub `DATABASE_URL_UNPOOLED` secret only for
72
- the migration command.
71
+ overlay a separately governed GitHub `MIGRATION_DATABASE_URL_UNPOOLED` secret
72
+ only for migration validation and the migration command. Readable pulled URLs
73
+ and the legacy `DATABASE_URL_UNPOOLED` secret remain supported during gradual
74
+ adoption.
73
75
 
74
76
  ## Re-establishing work context
75
77
 
@@ -29,9 +29,9 @@ Use this skill when working on the shared DB stack from a consuming app.
29
29
  should use the app's env-aware package scripts or
30
30
  `pnpm exec loom env -- <command>`. Do not add `dotenv` or `@next/env` imports
31
31
  to implementation files.
32
- - `createDrizzleConfig()` prefers `DATABASE_URL_UNPOOLED` when Vercel/Neon
33
- provides it and falls back to `DATABASE_URL`, so local environments do not
34
- need to define both.
32
+ - `createDrizzleConfig()` prefers `MIGRATION_DATABASE_URL_UNPOOLED`, then
33
+ `MIGRATION_DATABASE_URL`, before the gradual-adoption fallbacks
34
+ `DATABASE_URL_UNPOOLED` and `DATABASE_URL`.
35
35
  - App-specific fixture table selection, extra Valibot refinements, and auth
36
36
  integration should stay local unless they are being extracted deliberately.
37
37
 
@@ -73,15 +73,26 @@ Use this skill when working on the shared DB stack from a consuming app.
73
73
  uploads a staged production deployment with `--prebuilt --prod --skip-domain`,
74
74
  runs `db:migrate`, and then promotes the staged deployment. Before adding
75
75
  build-only placeholders, preserve an untouched copy of the pulled env file for
76
- migrations. When Vercel database variables become Sensitive, provide a
77
- separately governed GitHub Environment secret named `DATABASE_URL_UNPOOLED`
78
- and overlay it only for the migration step. `vercel pull` and `vercel env run`
79
- cannot recover Sensitive values. Pass `--scope "$VERCEL_ORG_ID"` to Vercel CLI
80
- release commands so multi-account CI jobs do not resolve the wrong team.
76
+ migrations. Before Vercel database variables become Sensitive, provide a
77
+ separately governed direct migration URL as the GitHub Environment secret
78
+ `MIGRATION_DATABASE_URL_UNPOOLED` and expose it only to validation and
79
+ migration steps. `vercel pull` and `vercel env run` cannot recover Sensitive
80
+ values. The pulled URL and legacy `DATABASE_URL_UNPOOLED` secret remain
81
+ supported during gradual adoption. Pass `--scope "$VERCEL_ORG_ID"` to Vercel
82
+ CLI release commands so multi-account CI jobs do not resolve the wrong team.
81
83
  - Query Vercel Production variable metadata before an external build. Preserve
82
84
  usable pulled values, insert unique placeholders only for confirmed unreadable
83
85
  Sensitive values, and scan `.vercel/output` for those markers before uploading
84
- the prebuilt artifact.
86
+ the prebuilt artifact. Prefer `loom db release prepare-build-env` and
87
+ `loom db release verify-build-env`; keep only the declarative requirements
88
+ policy app-local.
89
+ - Use `loom db migrations verify-env` before a migration. It validates the
90
+ selected URL, precedence, database role, and direct-vs-pooled endpoint without
91
+ printing credentials.
92
+ - Once a dedicated direct URL has been provisioned, load it as
93
+ `MIGRATION_DATABASE_URL_UNPOOLED` in the local process and run
94
+ `loom db migrations setup-github`. Loom sends the value to GitHub over stdin,
95
+ records `LOOM_MIGRATION_DATABASE_ROLE`, and does not change Vercel variables.
85
96
  - Use `loom check --network` after wiring a production release workflow so Loom
86
97
  can verify the linked Vercel project plus GitHub's `VERCEL_TOKEN`,
87
98
  `VERCEL_ORG_ID`, and `VERCEL_PROJECT_ID` release configuration.