@gadicc/loom 1.32.0 → 1.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants as fsConstants } from "node:fs";
4
- import { access, lstat, mkdir, readdir, readFile, readlink, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
4
+ import { access, chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
5
5
  import { createRequire } from "node:module";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
7
  import process from "node:process";
8
+ import { createInterface } from "node:readline/promises";
9
+ import { tmpdir } from "node:os";
8
10
  import { parseArgs } from "node:util";
9
11
  import { filesR2PolicyIssues, parseWranglerR2Cors, r2CorsMatchesPolicy, } from "./filesR2Policy.js";
10
12
  import { resolveProductionBranch, } from "./releaseConfig.js";
@@ -175,7 +177,7 @@ const DB_DEFAULT_DEPENDENCIES = {
175
177
  "valibot": "^1.4.2",
176
178
  };
177
179
  const DB_DEFAULT_DEV_DEPENDENCIES = {
178
- "@electric-sql/pglite": "^0.3.15",
180
+ "@electric-sql/pglite": "^0.5.8",
179
181
  "drizzle-kit": "^0.31.10",
180
182
  "drizzle-valibot": "^0.4.2",
181
183
  "tsx": "^4.23.1",
@@ -209,6 +211,7 @@ const FILES_S3_NON_SECRET_ENV_VALUES = {
209
211
  };
210
212
  const FILES_R2_ENVIRONMENTS = ["production", "preview"];
211
213
  const DEFAULT_MINIO_ENDPOINT = "http://127.0.0.1:9000";
214
+ const FILES_LOCAL_ENV_NAMES = FILES_S3_REQUIRED_ENV_NAMES;
212
215
  const API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION = 3;
213
216
  const API_KEY_AUDIT_SCHEMA_DEFAULT_EXPORT = "loomApiKeyAuditEventsTable";
214
217
  const API_KEY_AUDIT_SCHEMA_DEFAULT_TABLE = "loom_api_key_audit_events";
@@ -5772,17 +5775,31 @@ export async function configureFilesIdGeneration(cwd, idGeneration) {
5772
5775
  }
5773
5776
  function parseEnvValue(rawValue) {
5774
5777
  const trimmed = rawValue.trim();
5775
- if (trimmed.length >= 2 &&
5776
- ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
5777
- (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
5778
- return trimmed.slice(1, -1);
5778
+ const quote = trimmed[0];
5779
+ if (quote === '"' || quote === "'" || quote === "`") {
5780
+ for (let index = 1; index < trimmed.length; index++) {
5781
+ if (trimmed[index] === "\\") {
5782
+ index++;
5783
+ continue;
5784
+ }
5785
+ if (trimmed[index] !== quote)
5786
+ continue;
5787
+ const trailing = trimmed.slice(index + 1).trim();
5788
+ if (!trailing || trailing.startsWith("#")) {
5789
+ const value = trimmed.slice(1, index);
5790
+ return quote === '"'
5791
+ ? value.replaceAll("\\n", "\n").replaceAll("\\r", "\r")
5792
+ : value;
5793
+ }
5794
+ break;
5795
+ }
5779
5796
  }
5780
- return trimmed;
5797
+ return trimmed.split("#", 1)[0].trim();
5781
5798
  }
5782
5799
  function readEnvAssignments(text) {
5783
5800
  const assignments = new Map();
5784
5801
  for (const [lineIndex, line] of normalizeText(text).split("\n").entries()) {
5785
- const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
5802
+ const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
5786
5803
  if (!match)
5787
5804
  continue;
5788
5805
  assignments.set(match[1], {
@@ -5969,32 +5986,66 @@ async function promptForVercelSecret(cwd, commandRunner, env, vercelCommand, nam
5969
5986
  }
5970
5987
  const VERCEL_FILES_ENV_PROBE_SCRIPT = "process.stdout.write(JSON.stringify({FILES_S3_BUCKET:process.env.FILES_S3_BUCKET,FILES_S3_ENDPOINT:process.env.FILES_S3_ENDPOINT,FILES_S3_FORCE_PATH_STYLE:process.env.FILES_S3_FORCE_PATH_STYLE,FILES_S3_REGION:process.env.FILES_S3_REGION,FILES_STORAGE_PROVIDER:process.env.FILES_STORAGE_PROVIDER}))";
5971
5988
  /** Builds the Vercel env-run probe that prints only non-secret Files values. */
5972
- export function buildVercelFilesEnvProbeArgs(environment) {
5989
+ export function buildVercelFilesEnvProbeArgs(environment, project) {
5973
5990
  return [
5991
+ ...(project ? ["--scope", project.orgId] : []),
5974
5992
  "env",
5975
5993
  "run",
5976
5994
  "-e",
5977
5995
  environment,
5996
+ ...(project ? ["--project", project.projectId] : []),
5978
5997
  "--",
5979
5998
  "node",
5980
5999
  "-e",
5981
6000
  VERCEL_FILES_ENV_PROBE_SCRIPT,
5982
6001
  ];
5983
6002
  }
6003
+ function buildVercelFilesEnvListArgs(environment, project) {
6004
+ return [
6005
+ "--scope",
6006
+ project.orgId,
6007
+ "env",
6008
+ "ls",
6009
+ environment,
6010
+ "--project",
6011
+ project.projectId,
6012
+ ];
6013
+ }
6014
+ function withoutInheritedVercelProject(env) {
6015
+ const result = { ...env };
6016
+ delete result.VERCEL_ORG_ID;
6017
+ delete result.VERCEL_PROJECT_ID;
6018
+ return result;
6019
+ }
5984
6020
  async function readVercelFilesNonSecretValues(cwd, commandRunner, env, vercelCommand, environment) {
5985
- const result = await commandRunner(vercelCommand, buildVercelFilesEnvProbeArgs(environment), { cwd, env, stdio: "pipe" });
5986
- if (result.code !== 0)
5987
- return null;
5988
- const jsonLine = normalizeText(result.stdout).split("\n").findLast((line) => line.trim().startsWith("{"));
5989
- if (!jsonLine)
6021
+ const link = await readVercelProjectLink(cwd);
6022
+ if (!link.linked || !link.orgId || !link.projectId)
5990
6023
  return null;
6024
+ const probeEnv = withoutInheritedVercelProject(env);
6025
+ for (const name of Object.keys(probeEnv)) {
6026
+ if (name.startsWith("FILES_"))
6027
+ delete probeEnv[name];
6028
+ }
6029
+ const probeCwd = await mkdtemp(join(tmpdir(), "loom-vercel-files-probe-"));
5991
6030
  try {
6031
+ // Vercel env run loads .env.local from cwd and preserves inherited values.
6032
+ // Probe the linked project from an empty directory so local MinIO cannot
6033
+ // masquerade as remote R2 drift.
6034
+ const result = await commandRunner(vercelCommand, buildVercelFilesEnvProbeArgs(environment, link), { cwd: probeCwd, env: probeEnv, stdio: "pipe" });
6035
+ if (result.code !== 0)
6036
+ return null;
6037
+ const jsonLine = normalizeText(result.stdout).split("\n").findLast((line) => line.trim().startsWith("{"));
6038
+ if (!jsonLine)
6039
+ return null;
5992
6040
  const parsed = JSON.parse(jsonLine);
5993
6041
  return isJsonObject(parsed) ? parsed : null;
5994
6042
  }
5995
6043
  catch {
5996
6044
  return null;
5997
6045
  }
6046
+ finally {
6047
+ await rm(probeCwd, { recursive: true, force: true });
6048
+ }
5998
6049
  }
5999
6050
  async function detectMinioClient(cwd, commandRunner, env) {
6000
6051
  for (const command of ["mcli", "mc"]) {
@@ -6043,6 +6094,420 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
6043
6094
  ok: false,
6044
6095
  };
6045
6096
  }
6097
+ async function promptForLocalFilesValue(question, secret = false) {
6098
+ if (!process.stdin.isTTY) {
6099
+ throw new Error("MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment.");
6100
+ }
6101
+ if (!secret) {
6102
+ const input = createInterface({
6103
+ input: process.stdin,
6104
+ output: process.stderr,
6105
+ });
6106
+ try {
6107
+ return (await input.question(question)).trim();
6108
+ }
6109
+ finally {
6110
+ input.close();
6111
+ }
6112
+ }
6113
+ process.stderr.write(question);
6114
+ const stdin = process.stdin;
6115
+ const wasRaw = stdin.isRaw;
6116
+ stdin.setRawMode(true);
6117
+ stdin.resume();
6118
+ try {
6119
+ return await new Promise((resolvePromise, rejectPromise) => {
6120
+ let value = "";
6121
+ const onData = (chunk) => {
6122
+ for (const character of new TextDecoder().decode(chunk)) {
6123
+ if (character === "\r" || character === "\n") {
6124
+ stdin.off("data", onData);
6125
+ process.stderr.write("\n");
6126
+ resolvePromise(value);
6127
+ return;
6128
+ }
6129
+ if (character === "\u0003") {
6130
+ stdin.off("data", onData);
6131
+ rejectPromise(new Error("MinIO setup was cancelled."));
6132
+ return;
6133
+ }
6134
+ if (character === "\u007f" || character === "\b") {
6135
+ value = value.slice(0, -1);
6136
+ }
6137
+ else {
6138
+ value += character;
6139
+ }
6140
+ }
6141
+ };
6142
+ stdin.on("data", onData);
6143
+ });
6144
+ }
6145
+ finally {
6146
+ stdin.setRawMode(wasRaw);
6147
+ stdin.pause();
6148
+ }
6149
+ }
6150
+ function minioHostEnv(env, endpoint, accessKey, secretKey) {
6151
+ const url = new URL(endpoint);
6152
+ url.username = accessKey;
6153
+ url.password = secretKey;
6154
+ return { ...env, MC_HOST_loomlocal: url.toString() };
6155
+ }
6156
+ async function checkMinioAdmin(cwd, runner, command, env, endpoint, user, password) {
6157
+ const result = await runner(command, ["admin", "info", "loomlocal"], {
6158
+ cwd,
6159
+ env: minioHostEnv(env, endpoint, user, password),
6160
+ stdio: "pipe",
6161
+ });
6162
+ return result.code === 0;
6163
+ }
6164
+ function filesBucketPolicy(bucket) {
6165
+ return {
6166
+ Version: "2012-10-17",
6167
+ Statement: [
6168
+ {
6169
+ Effect: "Allow",
6170
+ Action: ["s3:GetBucketLocation", "s3:ListBucket"],
6171
+ Resource: [`arn:aws:s3:::${bucket}`],
6172
+ },
6173
+ {
6174
+ Effect: "Allow",
6175
+ Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
6176
+ Resource: [`arn:aws:s3:::${bucket}/*`],
6177
+ },
6178
+ ],
6179
+ };
6180
+ }
6181
+ async function verifyMinioReadWrite(cwd, runner, command, env, endpoint, bucket, accessKey, secretKey) {
6182
+ const target = `loomlocal/${bucket}/.loom-setup-${randomUUID()}`;
6183
+ const keyEnv = minioHostEnv(env, endpoint, accessKey, secretKey);
6184
+ const payload = "loom-files-local-check\n";
6185
+ const put = await runner(command, ["pipe", target], {
6186
+ cwd,
6187
+ env: keyEnv,
6188
+ input: payload,
6189
+ stdio: "pipe",
6190
+ });
6191
+ if (put.code !== 0) {
6192
+ throw new Error("The MinIO access key cannot write to its bucket.");
6193
+ }
6194
+ let readOk = false;
6195
+ let removeOk = false;
6196
+ try {
6197
+ const get = await runner(command, ["cat", target], {
6198
+ cwd,
6199
+ env: keyEnv,
6200
+ stdio: "pipe",
6201
+ });
6202
+ readOk = get.code === 0 && get.stdout === payload;
6203
+ }
6204
+ finally {
6205
+ const remove = await runner(command, ["rm", target], {
6206
+ cwd,
6207
+ env: keyEnv,
6208
+ stdio: "pipe",
6209
+ });
6210
+ removeOk = remove.code === 0;
6211
+ }
6212
+ if (!removeOk) {
6213
+ throw new Error("The MinIO access key could not remove its setup verification object.");
6214
+ }
6215
+ if (!readOk) {
6216
+ throw new Error("The MinIO access key cannot read from its bucket.");
6217
+ }
6218
+ }
6219
+ /**
6220
+ * Configures Files against local MinIO, preserving any existing app key and
6221
+ * verifying a newly created bucket-scoped key before writing it to .env.local.
6222
+ */
6223
+ export async function setupLocalFiles(cwd, options = {}) {
6224
+ const runner = options.commandRunner ?? defaultCommandRunner;
6225
+ const env = options.env ?? process.env;
6226
+ const prompt = options.prompt ?? promptForLocalFilesValue;
6227
+ const manifestPath = join(cwd, "loom.json");
6228
+ const manifestText = await readTextIfExists(manifestPath);
6229
+ if (!manifestText) {
6230
+ throw new Error("Missing loom.json. Run `loom add files` first.");
6231
+ }
6232
+ const manifest = parseJson(manifestText, "loom.json");
6233
+ const feature = manifest.features.files;
6234
+ if (feature?.status !== "active") {
6235
+ throw new Error("The files feature is not active. Run `loom add files` first.");
6236
+ }
6237
+ const { packageJson } = await readProjectPackageJson(cwd);
6238
+ const framework = await detectFramework(cwd, packageJson);
6239
+ const dbFeature = manifest.features.db;
6240
+ if (dbFeature?.status !== "active") {
6241
+ throw new Error("The files feature requires the active DB feature.");
6242
+ }
6243
+ const config = getFilesConfig(framework, mergeDbConfig(framework, dbFeature.config), feature.config);
6244
+ if (config.storage.provider?.localDevelopment.kind === "none") {
6245
+ throw new Error("Files local storage is disabled in loom.json. Change the provider policy before running local setup.");
6246
+ }
6247
+ if (config.storage.provider?.localDevelopment.kind === "r2") {
6248
+ throw new Error("Files local storage is set to R2. Change the local provider policy to MinIO before running local setup.");
6249
+ }
6250
+ const storagePath = join(cwd, config.modules.storageModule);
6251
+ const storageText = await readTextIfExists(storagePath);
6252
+ if (storageText && !isGeneratedFilesStorageStub(storageText) &&
6253
+ config.storage.adapter !== "s3") {
6254
+ throw new Error(`Files uses a custom storage adapter at ${config.modules.storageModule}; configure it locally without replacing it.`);
6255
+ }
6256
+ const envPath = join(cwd, ".env.local");
6257
+ const envText = await readTextIfExists(envPath);
6258
+ const tracked = await runner("git", [
6259
+ "ls-files",
6260
+ "--error-unmatch",
6261
+ "--",
6262
+ ".env.local",
6263
+ ], { cwd, env, stdio: "pipe" });
6264
+ if (tracked.code === 0) {
6265
+ throw new Error(".env.local is tracked by Git. Remove it from the index before Loom writes Files credentials.");
6266
+ }
6267
+ try {
6268
+ if ((await lstat(envPath)).isSymbolicLink()) {
6269
+ throw new Error(".env.local is a symlink; Loom will not write credentials through it.");
6270
+ }
6271
+ }
6272
+ catch (error) {
6273
+ if (!isNodeErrorCode(error, "ENOENT"))
6274
+ throw error;
6275
+ }
6276
+ const assignments = readEnvAssignments(envText ?? "");
6277
+ const bucket = normalizeBucketName(options.localBucket ??
6278
+ assignments.get("FILES_S3_BUCKET")?.value ??
6279
+ config.storage.provider?.localDevelopment.bucket ??
6280
+ `${getDefaultFilesBucketBase(cwd, packageJson, manifest)}-dev`, "--local-bucket");
6281
+ let endpoint = options.localEndpoint ??
6282
+ assignments.get("FILES_S3_ENDPOINT")?.value ??
6283
+ config.storage.provider?.localDevelopment.endpoint ??
6284
+ DEFAULT_MINIO_ENDPOINT;
6285
+ function validateEndpoint(value) {
6286
+ let url;
6287
+ try {
6288
+ url = new URL(value);
6289
+ }
6290
+ catch {
6291
+ throw new Error("--local-endpoint must be an HTTP(S) origin without credentials or a path.");
6292
+ }
6293
+ if (!["http:", "https:"].includes(url.protocol) || url.username ||
6294
+ url.password || url.pathname !== "/" || url.search || url.hash) {
6295
+ throw new Error("--local-endpoint must be an HTTP(S) origin without credentials or a path.");
6296
+ }
6297
+ return url.origin;
6298
+ }
6299
+ endpoint = validateEndpoint(endpoint);
6300
+ const client = await detectMinioClient(cwd, runner, env);
6301
+ if (!client) {
6302
+ throw new Error("MinIO Client is unavailable. Install `mcli` (Arch: `sudo pacman -S minio-client`) or `mc`, then rerun `loom files local setup`.");
6303
+ }
6304
+ const existingAccess = assignments.get("FILES_S3_ACCESS_KEY_ID")?.value;
6305
+ const existingSecret = assignments.get("FILES_S3_SECRET_ACCESS_KEY")?.value;
6306
+ if ((assignments.has("FILES_S3_ACCESS_KEY_ID") && !existingAccess) ||
6307
+ (assignments.has("FILES_S3_SECRET_ACCESS_KEY") && !existingSecret)) {
6308
+ throw new Error(".env.local contains an empty Files credential. Remove the empty assignment before local setup.");
6309
+ }
6310
+ if (Boolean(existingAccess) !== Boolean(existingSecret)) {
6311
+ throw new Error(".env.local has only one Files access credential. Restore the matching key and secret before local setup; Loom will not replace either one.");
6312
+ }
6313
+ let bucketStatus = existingAccess && existingSecret
6314
+ ? await ensureMinioBucket(cwd, runner, env, endpoint, bucket, existingAccess, existingSecret, { create: false })
6315
+ : null;
6316
+ if (bucketStatus?.ok && existingAccess && existingSecret) {
6317
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, existingAccess, existingSecret);
6318
+ }
6319
+ let createdKey = null;
6320
+ if (!bucketStatus?.ok) {
6321
+ if (Boolean(env.MINIO_ROOT_USER) !== Boolean(env.MINIO_ROOT_PASSWORD)) {
6322
+ throw new Error("Set both MINIO_ROOT_USER and MINIO_ROOT_PASSWORD, or leave both unset for interactive MinIO setup.");
6323
+ }
6324
+ let adminUser = env.MINIO_ROOT_USER || "minioadmin";
6325
+ let adminPassword = env.MINIO_ROOT_PASSWORD || "minioadmin";
6326
+ let authenticated = await checkMinioAdmin(cwd, runner, client, env, endpoint, adminUser, adminPassword);
6327
+ if (!authenticated) {
6328
+ const promptedEndpoint = (await prompt(`MinIO endpoint [${endpoint}]: `)).trim();
6329
+ if (promptedEndpoint)
6330
+ endpoint = validateEndpoint(promptedEndpoint);
6331
+ adminUser = (await prompt("MinIO admin user: ")).trim();
6332
+ adminPassword = await prompt("MinIO admin password: ", true);
6333
+ authenticated = await checkMinioAdmin(cwd, runner, client, env, endpoint, adminUser, adminPassword);
6334
+ }
6335
+ if (!authenticated) {
6336
+ throw new Error("Could not authenticate to MinIO. Check the server endpoint and admin credentials, then rerun local setup.");
6337
+ }
6338
+ const adminEnv = minioHostEnv(env, endpoint, adminUser, adminPassword);
6339
+ bucketStatus = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, adminUser, adminPassword);
6340
+ if (!bucketStatus.ok) {
6341
+ throw new Error(`Could not create or reuse MinIO bucket \`${bucket}\`. Check admin permissions and the endpoint.`);
6342
+ }
6343
+ if (existingAccess && existingSecret) {
6344
+ const existingCheck = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, existingAccess, existingSecret, { create: false });
6345
+ if (!existingCheck.ok) {
6346
+ throw new Error("Existing FILES_S3 credentials cannot access the bucket. Loom preserved them; repair or remove them manually before rerunning setup.");
6347
+ }
6348
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, existingAccess, existingSecret);
6349
+ }
6350
+ else {
6351
+ const policyDir = await mkdtemp(join(tmpdir(), "loom-files-policy-"));
6352
+ const policyPath = join(policyDir, "bucket.json");
6353
+ try {
6354
+ await writeFile(policyPath, `${JSON.stringify(filesBucketPolicy(bucket))}\n`, { mode: 0o600 });
6355
+ const result = await runner(client, [
6356
+ "--json",
6357
+ "admin",
6358
+ "accesskey",
6359
+ "create",
6360
+ "loomlocal/",
6361
+ "--policy",
6362
+ policyPath,
6363
+ ], { cwd, env: adminEnv, stdio: "pipe" });
6364
+ if (result.code !== 0) {
6365
+ throw new Error("MinIO could not create a bucket-scoped access key. Check that the client supports `admin accesskey create` and the admin account has permission.");
6366
+ }
6367
+ let parsed = {};
6368
+ try {
6369
+ parsed = JSON.parse(result.stdout.trim());
6370
+ }
6371
+ catch {
6372
+ throw new Error("MinIO returned malformed JSON while creating a local access key.");
6373
+ }
6374
+ if (typeof parsed.accessKey !== "string" ||
6375
+ typeof parsed.secretKey !== "string") {
6376
+ throw new Error("MinIO did not return an access key and secret key in JSON output.");
6377
+ }
6378
+ createdKey = {
6379
+ accessKey: parsed.accessKey,
6380
+ secretKey: parsed.secretKey,
6381
+ };
6382
+ }
6383
+ finally {
6384
+ await rm(policyDir, { recursive: true, force: true });
6385
+ }
6386
+ try {
6387
+ const keyCheck = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, createdKey.accessKey, createdKey.secretKey, { create: false });
6388
+ if (!keyCheck.ok) {
6389
+ throw new Error("The new MinIO access key could not read its bucket. Check the MinIO policy before rerunning setup.");
6390
+ }
6391
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, createdKey.accessKey, createdKey.secretKey);
6392
+ }
6393
+ catch (error) {
6394
+ const cleanup = await runner(client, ["admin", "accesskey", "remove", "loomlocal/", createdKey.accessKey], { cwd, env: adminEnv, stdio: "pipe" });
6395
+ if (cleanup.code !== 0) {
6396
+ throw new Error("The new MinIO key failed verification and could not be removed automatically. Remove the newly created key in MinIO before retrying.");
6397
+ }
6398
+ throw error;
6399
+ }
6400
+ }
6401
+ }
6402
+ const desired = {
6403
+ FILES_S3_BUCKET: bucket,
6404
+ FILES_S3_ENDPOINT: endpoint,
6405
+ FILES_S3_FORCE_PATH_STYLE: "true",
6406
+ FILES_S3_REGION: "auto",
6407
+ FILES_STORAGE_PROVIDER: "minio",
6408
+ FILES_S3_ACCESS_KEY_ID: existingAccess ?? createdKey?.accessKey ?? "",
6409
+ FILES_S3_SECRET_ACCESS_KEY: existingSecret ?? createdKey?.secretKey ?? "",
6410
+ };
6411
+ const merged = mergeEnvValues(envText, desired, {
6412
+ neverReplace: new Set([
6413
+ "FILES_S3_ACCESS_KEY_ID",
6414
+ "FILES_S3_SECRET_ACCESS_KEY",
6415
+ ]),
6416
+ repair: true,
6417
+ });
6418
+ if (merged.conflicts.length) {
6419
+ throw new Error(`Could not preserve existing Files credentials: ${merged.conflicts.join(", ")}.`);
6420
+ }
6421
+ const changedFiles = [];
6422
+ const notes = [];
6423
+ const gitignorePath = join(cwd, ".gitignore");
6424
+ const gitignore = await readTextIfExists(gitignorePath) ?? "";
6425
+ const lastIgnoreRule = normalizeText(gitignore).split("\n")
6426
+ .map((line) => line.trim()).filter(Boolean).at(-1);
6427
+ if (lastIgnoreRule !== ".env.local" && lastIgnoreRule !== "/.env.local") {
6428
+ if (await writeTextIfChanged(gitignorePath, `${gitignore && !gitignore.endsWith("\n") ? `${gitignore}\n` : gitignore}.env.local\n`))
6429
+ changedFiles.push(".gitignore");
6430
+ }
6431
+ if (envText !== merged.text) {
6432
+ await writeFile(envPath, merged.text, { mode: 0o600 });
6433
+ await chmod(envPath, 0o600);
6434
+ changedFiles.push(".env.local");
6435
+ }
6436
+ const tooling = await getProjectTooling(cwd, manifest);
6437
+ const dependencyUpdate = await mutateProjectDependencies(cwd, tooling.dependencies, { dependencies: FILES_S3_DEPENDENCIES });
6438
+ if (dependencyUpdate.changed) {
6439
+ changedFiles.push(dependencyUpdate.config);
6440
+ notes.push(`Run ${tooling.dependencies.manager} install to update the dependency lockfile.`);
6441
+ }
6442
+ if (!storageText || isGeneratedFilesStorageStub(storageText)) {
6443
+ if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
6444
+ changedFiles.push(config.modules.storageModule);
6445
+ }
6446
+ }
6447
+ config.storage.adapter = "s3";
6448
+ if (config.storage.provider) {
6449
+ config.storage.provider.localDevelopment = {
6450
+ kind: "minio",
6451
+ bucket,
6452
+ endpoint,
6453
+ };
6454
+ }
6455
+ feature.config = config;
6456
+ if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
6457
+ changedFiles.push("loom.json");
6458
+ }
6459
+ return {
6460
+ changedFiles,
6461
+ notes: [
6462
+ bucketStatus?.detail ?? `MinIO bucket \`${bucket}\` is ready.`,
6463
+ createdKey
6464
+ ? "Created a bucket-scoped MinIO access key and saved it to .env.local."
6465
+ : "Reused existing Files access credentials.",
6466
+ ...notes,
6467
+ ],
6468
+ };
6469
+ }
6470
+ async function checkLocalFilesEnvironment(cwd, options = {}) {
6471
+ const issues = [];
6472
+ const suggestions = [];
6473
+ const warnings = [];
6474
+ const text = await readTextIfExists(join(cwd, ".env.local"));
6475
+ const assignments = readEnvAssignments(text ?? "");
6476
+ const missing = FILES_LOCAL_ENV_NAMES.filter((name) => !assignments.get(name)?.value);
6477
+ if (!text || missing.length) {
6478
+ issues.push(!text
6479
+ ? "Files local storage is missing .env.local."
6480
+ : `Files .env.local is missing ${missing.join(", ")}.`);
6481
+ suggestions.push("Run `loom files local setup` to configure local MinIO.");
6482
+ suggestions.push("Install and start a MinIO server with `mcli` or `mc`, or configure another S3-compatible service with the canonical FILES_S3_* variables.");
6483
+ return { issues, suggestions, warnings };
6484
+ }
6485
+ const endpoint = assignments.get("FILES_S3_ENDPOINT")?.value ?? "";
6486
+ try {
6487
+ const url = new URL(endpoint);
6488
+ if (!["http:", "https:"].includes(url.protocol) || url.username ||
6489
+ url.password)
6490
+ throw new Error("invalid");
6491
+ }
6492
+ catch {
6493
+ issues.push("FILES_S3_ENDPOINT in .env.local must be an HTTP(S) URL without credentials.");
6494
+ }
6495
+ if (assignments.get("FILES_S3_FORCE_PATH_STYLE")?.value !== "true" &&
6496
+ assignments.get("FILES_STORAGE_PROVIDER")?.value === "minio") {
6497
+ issues.push("Local MinIO requires FILES_S3_FORCE_PATH_STYLE=true.");
6498
+ }
6499
+ if (options.verifyBucket && !issues.length) {
6500
+ const verified = await ensureMinioBucket(cwd, options.commandRunner ?? defaultCommandRunner, options.env ?? process.env, endpoint, assignments.get("FILES_S3_BUCKET")?.value ?? "", assignments.get("FILES_S3_ACCESS_KEY_ID")?.value ?? "", assignments.get("FILES_S3_SECRET_ACCESS_KEY")?.value ?? "", { create: false });
6501
+ if (!verified.ok) {
6502
+ issues.push("Files local bucket or credentials could not be verified.");
6503
+ suggestions.push("Start the configured storage server and check its endpoint, bucket, and credentials; use `loom files local setup` for MinIO.");
6504
+ if (verified.detail.includes("not available")) {
6505
+ suggestions.push("Install MinIO Client as `mcli` (Arch: `sudo pacman -S minio-client`) or `mc`.");
6506
+ }
6507
+ }
6508
+ }
6509
+ return { issues, suggestions, warnings };
6510
+ }
6046
6511
  function filesR2ProviderMatches(existing, desired) {
6047
6512
  if (!existing)
6048
6513
  return true;
@@ -6207,7 +6672,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
6207
6672
  const envLocalText = await readTextIfExists(envLocalPath);
6208
6673
  const localAssignments = readEnvAssignments(envLocalText ?? "");
6209
6674
  const localBucket = normalizeBucketName(options.localBucket ?? existingProvider?.localDevelopment.bucket ??
6210
- localAssignments.get("FILES_S3_BUCKET")?.value ?? `${baseName}-files`, "--local-bucket");
6675
+ localAssignments.get("FILES_S3_BUCKET")?.value ?? `${baseName}-dev`, "--local-bucket");
6211
6676
  const localEndpoint = options.localEndpoint ??
6212
6677
  existingProvider?.localDevelopment.endpoint ??
6213
6678
  localAssignments.get("FILES_S3_ENDPOINT")?.value ??
@@ -6289,13 +6754,6 @@ export async function setupCloudflareR2(cwd, options = {}) {
6289
6754
  ? "minio"
6290
6755
  : "cloudflare-r2",
6291
6756
  };
6292
- if (!localAssignments.has("FILES_S3_ACCESS_KEY_ID") && env.MINIO_ROOT_USER) {
6293
- desiredLocalValues.FILES_S3_ACCESS_KEY_ID = env.MINIO_ROOT_USER;
6294
- }
6295
- if (!localAssignments.has("FILES_S3_SECRET_ACCESS_KEY") &&
6296
- env.MINIO_ROOT_PASSWORD) {
6297
- desiredLocalValues.FILES_S3_SECRET_ACCESS_KEY = env.MINIO_ROOT_PASSWORD;
6298
- }
6299
6757
  const localMerge = mergeEnvValues(envLocalText, desiredLocalValues, {
6300
6758
  neverReplace: new Set([
6301
6759
  "FILES_S3_ACCESS_KEY_ID",
@@ -6319,7 +6777,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
6319
6777
  notes.push(minio.detail);
6320
6778
  }
6321
6779
  else if (!localAccessKey || !localSecretKey) {
6322
- notes.push("Local storage credentials were not found. Add FILES_S3_ACCESS_KEY_ID and FILES_S3_SECRET_ACCESS_KEY to gitignored .env.local; Loom did not synthesize credentials.");
6780
+ notes.push("Local storage credentials were not found. Run `loom files local setup` to create a bucket-scoped MinIO key, or add credentials for another S3-compatible provider to gitignored .env.local.");
6323
6781
  }
6324
6782
  }
6325
6783
  const envListings = new Map();
@@ -7151,6 +7609,7 @@ function checkFilesNetworkFeature(context) {
7151
7609
  accountAvailable: false,
7152
7610
  vercelCommand: null,
7153
7611
  vercelLinked: false,
7612
+ vercelProject: null,
7154
7613
  wranglerCommand: null,
7155
7614
  };
7156
7615
  const providerEnv = {
@@ -7300,6 +7759,9 @@ function checkFilesNetworkFeature(context) {
7300
7759
  state.vercelCommand = detected.command;
7301
7760
  const link = await readVercelProjectLink(context.cwd);
7302
7761
  state.vercelLinked = link.linked;
7762
+ state.vercelProject = link.linked && link.orgId && link.projectId
7763
+ ? { orgId: link.orgId, projectId: link.projectId }
7764
+ : null;
7303
7765
  if (!state.vercelCommand || !state.vercelLinked) {
7304
7766
  return networkCheckResult("issue", !state.vercelCommand ? "Vercel CLI is unavailable." : link.detail, {
7305
7767
  issues: [
@@ -7329,10 +7791,14 @@ function checkFilesNetworkFeature(context) {
7329
7791
  steps.push({
7330
7792
  label: `Vercel ${environment} has all Files R2 variables`,
7331
7793
  run: async () => {
7332
- if (!state.vercelCommand || !state.vercelLinked) {
7794
+ if (!state.vercelCommand || !state.vercelLinked || !state.vercelProject) {
7333
7795
  return networkCheckResult("skipped", "Skipped until Vercel CLI/link checks pass.");
7334
7796
  }
7335
- const result = await context.commandRunner(state.vercelCommand, ["env", "ls", environment], { cwd: context.cwd, env: context.env, stdio: "pipe" });
7797
+ const result = await context.commandRunner(state.vercelCommand, buildVercelFilesEnvListArgs(environment, state.vercelProject), {
7798
+ cwd: context.cwd,
7799
+ env: withoutInheritedVercelProject(context.env),
7800
+ stdio: "pipe",
7801
+ });
7336
7802
  if (result.code !== 0) {
7337
7803
  return networkCheckResult("warning", `Could not list Vercel ${environment} env vars.`, {
7338
7804
  warnings: [
@@ -7360,7 +7826,7 @@ function checkFilesNetworkFeature(context) {
7360
7826
  `Could not inspect non-secret Files values in Vercel ${environment}.`,
7361
7827
  ],
7362
7828
  suggestions: [
7363
- `Run \`vercel env run -e ${environment} -- node -e '<inspect only FILES_S3_BUCKET/ENDPOINT/provider settings>'\` manually without printing credentials.`,
7829
+ `Run a non-secret Files probe from a temporary directory with \`vercel env run -e ${environment} --project <linked-project> --scope <linked-scope> -- node -e '<inspect only FILES_S3_BUCKET/ENDPOINT/provider settings>'\`.`,
7364
7830
  ],
7365
7831
  });
7366
7832
  }
@@ -7387,10 +7853,14 @@ function checkFilesNetworkFeature(context) {
7387
7853
  steps.push({
7388
7854
  label: "Vercel Development has no R2 Files credentials",
7389
7855
  run: async () => {
7390
- if (!state.vercelCommand || !state.vercelLinked) {
7856
+ if (!state.vercelCommand || !state.vercelLinked || !state.vercelProject) {
7391
7857
  return networkCheckResult("skipped", "Skipped until Vercel CLI/link checks pass.");
7392
7858
  }
7393
- const result = await context.commandRunner(state.vercelCommand, ["env", "ls", "development"], { cwd: context.cwd, env: context.env, stdio: "pipe" });
7859
+ const result = await context.commandRunner(state.vercelCommand, buildVercelFilesEnvListArgs("development", state.vercelProject), {
7860
+ cwd: context.cwd,
7861
+ env: withoutInheritedVercelProject(context.env),
7862
+ stdio: "pipe",
7863
+ });
7394
7864
  if (result.code !== 0) {
7395
7865
  return networkCheckResult("warning", "Could not list Vercel Development env vars.");
7396
7866
  }
@@ -7415,7 +7885,7 @@ function checkFilesNetworkFeature(context) {
7415
7885
  if (!text) {
7416
7886
  return networkCheckResult("issue", "Gitignored .env.local is missing.", {
7417
7887
  issues: ["Local MinIO Files configuration is missing."],
7418
- suggestions: ["Run `loom files r2 setup`."],
7888
+ suggestions: ["Run `loom files local setup`."],
7419
7889
  });
7420
7890
  }
7421
7891
  const assignments = readEnvAssignments(text);
@@ -7426,7 +7896,7 @@ function checkFilesNetworkFeature(context) {
7426
7896
  `Local MinIO Files variables are incomplete: ${missing.join(", ")}.`,
7427
7897
  ],
7428
7898
  suggestions: [
7429
- "Add the existing MinIO credentials to .env.local; Loom never synthesizes or replaces them.",
7899
+ "Run `loom files local setup` to create a scoped MinIO key, or add an existing credential pair to .env.local.",
7430
7900
  ],
7431
7901
  });
7432
7902
  }
@@ -7440,7 +7910,7 @@ function checkFilesNetworkFeature(context) {
7440
7910
  "Local MinIO is configured but the bucket could not be verified.",
7441
7911
  ],
7442
7912
  suggestions: [
7443
- "Start MinIO or correct FILES_S3_ENDPOINT, then rerun `loom files r2 check`.",
7913
+ "Start MinIO or correct FILES_S3_ENDPOINT, then rerun `loom files local check`.",
7444
7914
  ],
7445
7915
  });
7446
7916
  },
@@ -9042,6 +9512,17 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9042
9512
  : "Rerun `loom files r2 setup`; existing buckets and working credentials will be reused.");
9043
9513
  }
9044
9514
  }
9515
+ if (!options.production && provider?.localDevelopment.kind !== "none" &&
9516
+ (config.storage.adapter === "s3" ||
9517
+ (storageText !== null && isGeneratedFilesStorageStub(storageText)))) {
9518
+ const local = await checkLocalFilesEnvironment(cwd);
9519
+ if (config.storage.adapter === "s3")
9520
+ issues.push(...local.issues);
9521
+ else
9522
+ warnings.push(...local.issues);
9523
+ for (const suggestion of local.suggestions)
9524
+ suggestions.add(suggestion);
9525
+ }
9045
9526
  const routeText = await readTextIfExists(join(cwd, config.entrypoints.routeHandler));
9046
9527
  if (!routeText) {
9047
9528
  issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
@@ -10774,8 +11255,9 @@ function printHelp({ out }) {
10774
11255
  out(" init Set up package/Deno config, loom.json, managed AGENTS.md guidance, first-party links, and package skills.");
10775
11256
  out(" add <feature> Activate a shared feature. Run `loom add` to list available features.");
10776
11257
  out(" files id-generation uuid-v4|uuid-v7 Select the managed Files schema ID default.");
10777
- out(" files r2 setup Create/reuse private Cloudflare R2 buckets, configure Vercel Production/Preview, and configure local MinIO by default.");
10778
- out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local MinIO, and Files adapter wiring.");
11258
+ out(" files local setup|check Provision or verify local MinIO and .env.local without R2/Vercel.");
11259
+ out(" files r2 setup Create/reuse private Cloudflare R2 buckets and configure Vercel Production/Preview.");
11260
+ out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local storage, and Files adapter wiring.");
10779
11261
  out(" api-keys integrate jobs Record an explicit API-key jobs integration after the route has session/admin authorization.");
10780
11262
  out(" api-keys retention enable|disable Record API-key audit cleanup policy; scheduling remains app-owned.");
10781
11263
  out(" status Show the Loom package, manifest, active features, local-dev state, and project skill state.");
@@ -10889,8 +11371,53 @@ async function runFiles(cwd, command, target, options, io) {
10889
11371
  io.out(`Note: ${note}`);
10890
11372
  return 0;
10891
11373
  }
11374
+ if (command === "local") {
11375
+ if (target === "setup") {
11376
+ const result = await setupLocalFiles(cwd, {
11377
+ localBucket: options.localBucket,
11378
+ localEndpoint: options.localEndpoint,
11379
+ });
11380
+ io.out(result.changedFiles.length
11381
+ ? `Updated ${result.changedFiles.join(", ")}.`
11382
+ : "Files local storage already matches the configuration.");
11383
+ for (const note of result.notes)
11384
+ io.out(`Note: ${note}`);
11385
+ return 0;
11386
+ }
11387
+ if (target === "check") {
11388
+ const manifestText = await readTextIfExists(join(cwd, "loom.json"));
11389
+ const manifest = manifestText
11390
+ ? parseJson(manifestText, "loom.json")
11391
+ : null;
11392
+ if (manifest?.features.files?.status !== "active") {
11393
+ io.err("The files feature is not active. Run `loom add files` first.");
11394
+ return 1;
11395
+ }
11396
+ const filesConfig = manifest.features.files.config;
11397
+ if (filesConfig?.storage?.provider?.localDevelopment.kind === "none") {
11398
+ io.out("Files local storage is disabled in loom.json.");
11399
+ return 0;
11400
+ }
11401
+ const result = await checkLocalFilesEnvironment(cwd, {
11402
+ verifyBucket: true,
11403
+ });
11404
+ if (result.issues.length) {
11405
+ io.err("loom files local check found setup issues:");
11406
+ for (const issue of result.issues)
11407
+ io.err(`- ${issue}`);
11408
+ for (const suggestion of result.suggestions) {
11409
+ io.err(`Suggestion: ${suggestion}`);
11410
+ }
11411
+ return 1;
11412
+ }
11413
+ io.out("loom files local check: setup looks good.");
11414
+ return 0;
11415
+ }
11416
+ io.err("Usage: loom files local setup|check [--local-endpoint <url>] [--local-bucket <name>]");
11417
+ return 1;
11418
+ }
10892
11419
  if (command !== "r2" || !target) {
10893
- io.err("Usage: loom files id-generation uuid-v4|uuid-v7\n or: loom files r2 setup|check [R2 options]");
11420
+ io.err("Usage: loom files id-generation uuid-v4|uuid-v7\n or: loom files local setup|check\n or: loom files r2 setup|check [R2 options]");
10894
11421
  return 1;
10895
11422
  }
10896
11423
  const jurisdiction = options.jurisdiction;