@capxul/sandbox 1.0.0-alpha.2 → 1.0.0-alpha.4

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 (3) hide show
  1. package/README.md +48 -0
  2. package/dist/main.mjs +265 -542
  3. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # Capxul Sandbox (`@capxul/sandbox`)
2
+
3
+ The published interactive CLI for two sandbox operator/developer tasks:
4
+
5
+ - `key create` mints a test publishable key for a local origin and writes the
6
+ canonical Next.js environment names to `.env.local`.
7
+ - `faucet send` mints test USDX on Base Sepolia to a Capxul email,
8
+ `@org-handle`, or an explicitly confirmed raw-address escape hatch.
9
+
10
+ ```bash
11
+ npx @capxul/sandbox key create
12
+ npx @capxul/sandbox faucet send
13
+
14
+ # Repository development
15
+ vp run --filter @capxul/sandbox dev -- --help
16
+ ```
17
+
18
+ `key create` uses the Little Sandpiper public staging quickstart endpoint and
19
+ needs no operator secret. `APP_ENV` does not retarget this public command; use
20
+ the returned key only with the staging tuple.
21
+ `faucet send` invokes the canonical Convex deployment and requires operator
22
+ access in the process environment: inside the infrastructure repository, run
23
+ it through the one env entry point
24
+ (`vp exec bash scripts/capxul-env.sh npx @capxul/sandbox faucet send`); outside
25
+ it, supply the deploy key directly
26
+ (`CONVEX_DEPLOY_KEY=… npx @capxul/sandbox faucet send`). Never print or commit
27
+ those values.
28
+
29
+ ## Verify in the repository
30
+
31
+ ```bash
32
+ vp run --filter @capxul/sandbox check-types
33
+ vp test run apps/sandbox
34
+ vp run --filter @capxul/sandbox build
35
+ ```
36
+
37
+ These checks prove parsing, environment-file rewriting, bounded amount
38
+ conversion, Convex command construction, and packing. They do not prove a live
39
+ key mint, faucet transaction, or installed CLI artifact.
40
+
41
+ Repository Rule 4 names `vp run --filter @capxul/sandbox proofs:live` as the
42
+ live-only ProofKit boundary, but that command does not exist yet. Keep live
43
+ acceptance unproven until [#920](https://github.com/Xelmar-tech/infrastructure/issues/920)
44
+ lands. [#922](https://github.com/Xelmar-tech/infrastructure/issues/922) tracks
45
+ the separate packed-install/bin smoke gap.
46
+
47
+ Read [CONTEXT.md](./CONTEXT.md) before changing command, secret, deployment, or
48
+ proof behavior.
package/dist/main.mjs CHANGED
@@ -1,315 +1,134 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
2
  import { cancel, confirm, intro, isCancel, note, outro, select, spinner, text } from "@clack/prompts";
4
3
  import { spawnSync } from "node:child_process";
5
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
4
  import { homedir, tmpdir } from "node:os";
7
- import { dirname, join, resolve } from "node:path";
8
- import { fileURLToPath } from "node:url";
9
- //#region \0rolldown/runtime.js
10
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
11
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
12
- //#endregion
13
- //#region ../../packages/backend/scripts/publishable-key-minting.ts
14
- var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
15
- const fs = __require("fs");
16
- const path = __require("path");
17
- const os = __require("os");
18
- const crypto = __require("crypto");
19
- const TIPS = [
20
- " encrypted .env [www.dotenvx.com]",
21
- " secrets for agents [www.dotenvx.com]",
22
- " auth for agents [www.vestauth.com]",
23
- "⌘ custom filepath { path: '/custom/path/.env' }",
24
- "⌘ enable debugging { debug: true }",
25
- "⌘ override existing { override: true }",
26
- " suppress logs { quiet: true }",
27
- "⌘ multiple files { path: ['.env.local', '.env'] }"
28
- ];
29
- function _getRandomTip() {
30
- return TIPS[Math.floor(Math.random() * TIPS.length)];
31
- }
32
- function parseBoolean(value) {
33
- if (typeof value === "string") return ![
34
- "false",
35
- "0",
36
- "no",
37
- "off",
38
- ""
39
- ].includes(value.toLowerCase());
40
- return Boolean(value);
41
- }
42
- function supportsAnsi() {
43
- return process.stdout.isTTY;
44
- }
45
- function dim(text) {
46
- return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
47
- }
48
- const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
49
- function parse(src) {
50
- const obj = {};
51
- let lines = src.toString();
52
- lines = lines.replace(/\r\n?/gm, "\n");
53
- let match;
54
- while ((match = LINE.exec(lines)) != null) {
55
- const key = match[1];
56
- let value = match[2] || "";
57
- value = value.trim();
58
- const maybeQuote = value[0];
59
- value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
60
- if (maybeQuote === "\"") {
61
- value = value.replace(/\\n/g, "\n");
62
- value = value.replace(/\\r/g, "\r");
63
- }
64
- obj[key] = value;
65
- }
66
- return obj;
67
- }
68
- function _parseVault(options) {
69
- options = options || {};
70
- const vaultPath = _vaultPath(options);
71
- options.path = vaultPath;
72
- const result = DotenvModule.configDotenv(options);
73
- if (!result.parsed) {
74
- const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
75
- err.code = "MISSING_DATA";
76
- throw err;
77
- }
78
- const keys = _dotenvKey(options).split(",");
79
- const length = keys.length;
80
- let decrypted;
81
- for (let i = 0; i < length; i++) try {
82
- const attrs = _instructions(result, keys[i].trim());
83
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
84
- break;
85
- } catch (error) {
86
- if (i + 1 >= length) throw error;
87
- }
88
- return DotenvModule.parse(decrypted);
89
- }
90
- function _warn(message) {
91
- console.error(`⚠ ${message}`);
92
- }
93
- function _debug(message) {
94
- console.log(`┆ ${message}`);
95
- }
96
- function _log(message) {
97
- console.log(`◇ ${message}`);
98
- }
99
- function _dotenvKey(options) {
100
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
101
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
102
- return "";
103
- }
104
- function _instructions(result, dotenvKey) {
105
- let uri;
106
- try {
107
- uri = new URL(dotenvKey);
108
- } catch (error) {
109
- if (error.code === "ERR_INVALID_URL") {
110
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
111
- err.code = "INVALID_DOTENV_KEY";
112
- throw err;
113
- }
114
- throw error;
115
- }
116
- const key = uri.password;
117
- if (!key) {
118
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
119
- err.code = "INVALID_DOTENV_KEY";
120
- throw err;
121
- }
122
- const environment = uri.searchParams.get("environment");
123
- if (!environment) {
124
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
125
- err.code = "INVALID_DOTENV_KEY";
126
- throw err;
127
- }
128
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
129
- const ciphertext = result.parsed[environmentKey];
130
- if (!ciphertext) {
131
- const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
132
- err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
133
- throw err;
134
- }
135
- return {
136
- ciphertext,
137
- key
138
- };
139
- }
140
- function _vaultPath(options) {
141
- let possibleVaultPath = null;
142
- if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
143
- for (const filepath of options.path) if (fs.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
144
- } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
145
- else possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
146
- if (fs.existsSync(possibleVaultPath)) return possibleVaultPath;
147
- return null;
148
- }
149
- function _resolveHome(envPath) {
150
- return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
151
- }
152
- function _configVault(options) {
153
- const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
154
- const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
155
- if (debug || !quiet) _log("loading env from encrypted .env.vault");
156
- const parsed = DotenvModule._parseVault(options);
157
- let processEnv = process.env;
158
- if (options && options.processEnv != null) processEnv = options.processEnv;
159
- DotenvModule.populate(processEnv, parsed, options);
160
- return { parsed };
161
- }
162
- function configDotenv(options) {
163
- const dotenvPath = path.resolve(process.cwd(), ".env");
164
- let encoding = "utf8";
165
- let processEnv = process.env;
166
- if (options && options.processEnv != null) processEnv = options.processEnv;
167
- let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
168
- let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
169
- if (options && options.encoding) encoding = options.encoding;
170
- else if (debug) _debug("no encoding is specified (UTF-8 is used by default)");
171
- let optionPaths = [dotenvPath];
172
- if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
173
- else {
174
- optionPaths = [];
175
- for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
176
- }
177
- let lastError;
178
- const parsedAll = {};
179
- for (const path of optionPaths) try {
180
- const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
181
- DotenvModule.populate(parsedAll, parsed, options);
182
- } catch (e) {
183
- if (debug) _debug(`failed to load ${path} ${e.message}`);
184
- lastError = e;
5
+ import path, { resolve } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { readFile, writeFile } from "node:fs/promises";
8
+ //#region ../../config/deployment-topology.json
9
+ var deployment_topology_default = {
10
+ schemaVersion: 1,
11
+ product: "capxul-platform",
12
+ environments: {
13
+ "development": {
14
+ "appEnv": "development",
15
+ "productRole": "development",
16
+ "convexProject": "capxul-platform-dev",
17
+ "deployment": "dev:incredible-possum-990",
18
+ "deploymentReference": "dev/aaron-griffith",
19
+ "name": "incredible-possum-990",
20
+ "convexType": "dev",
21
+ "convexUrl": "https://incredible-possum-990.convex.cloud",
22
+ "convexSiteUrl": "https://incredible-possum-990.convex.site",
23
+ "chainId": 84532,
24
+ "expectedFingerprints": {
25
+ "applicationId": "e0deb415da6714f8",
26
+ "openfortPublishableKey": "f8fed245b357f1c3",
27
+ "shieldPublishableKey": "d8eb8898a1ff1d9a"
28
+ },
29
+ "proofCommand": "APP_ENV=development vp exec bash scripts/capxul-env.sh vp exec node scripts/prove-deployment-bootstrap.mjs"
30
+ },
31
+ "staging": {
32
+ "appEnv": "staging",
33
+ "productRole": "staging",
34
+ "convexProject": "capxul-platform-effect",
35
+ "deployment": "prod:little-sandpiper-974",
36
+ "deploymentReference": "production",
37
+ "name": "little-sandpiper-974",
38
+ "convexType": "prod",
39
+ "convexUrl": "https://little-sandpiper-974.convex.cloud",
40
+ "convexSiteUrl": "https://little-sandpiper-974.convex.site",
41
+ "chainId": 84532,
42
+ "expectedFingerprints": {
43
+ "applicationId": "4e2989ea295fc269",
44
+ "openfortPublishableKey": "aab42edbcdc683e7",
45
+ "shieldPublishableKey": "a323489c9a8d8da2"
46
+ },
47
+ "proofCommand": "APP_ENV=staging vp exec bash scripts/capxul-env.sh vp exec node scripts/prove-deployment-bootstrap.mjs"
185
48
  }
186
- const populated = DotenvModule.populate(processEnv, parsedAll, options);
187
- debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
188
- quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
189
- if (debug || !quiet) {
190
- const keysCount = Object.keys(populated).length;
191
- const shortPaths = [];
192
- for (const filePath of optionPaths) try {
193
- const relative = path.relative(process.cwd(), filePath);
194
- shortPaths.push(relative);
195
- } catch (e) {
196
- if (debug) _debug(`failed to load ${filePath} ${e.message}`);
197
- lastError = e;
198
- }
199
- _log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`);
200
- }
201
- if (lastError) return {
202
- parsed: parsedAll,
203
- error: lastError
204
- };
205
- else return { parsed: parsedAll };
206
- }
207
- function config(options) {
208
- if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
209
- const vaultPath = _vaultPath(options);
210
- if (!vaultPath) {
211
- _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`);
212
- return DotenvModule.configDotenv(options);
213
- }
214
- return DotenvModule._configVault(options);
215
- }
216
- function decrypt(encrypted, keyStr) {
217
- const key = Buffer.from(keyStr.slice(-64), "hex");
218
- let ciphertext = Buffer.from(encrypted, "base64");
219
- const nonce = ciphertext.subarray(0, 12);
220
- const authTag = ciphertext.subarray(-16);
221
- ciphertext = ciphertext.subarray(12, -16);
49
+ },
50
+ production: null
51
+ };
52
+ //#endregion
53
+ //#region ../../scripts/deployment-topology.mjs
54
+ const SUPPORTED_APP_ENVS = ["development", "staging"];
55
+ function loadDeploymentTopology() {
56
+ const topology = structuredClone(deployment_topology_default);
57
+ const environmentNames = Object.keys(topology.environments ?? {}).sort();
58
+ if (topology.schemaVersion !== 1 || topology.product !== "capxul-platform" || topology.production !== null || JSON.stringify(environmentNames) !== JSON.stringify(SUPPORTED_APP_ENVS)) throw new Error("Invalid Capxul deployment topology: expected development + staging and no production tier");
59
+ return topology;
60
+ }
61
+ function resolveDeploymentTier(appEnv) {
62
+ const tier = loadDeploymentTopology().environments[appEnv];
63
+ if (tier === void 0) throw new Error(`Unsupported APP_ENV '${String(appEnv)}'; expected development or staging (production is not provisioned)`);
64
+ return tier;
65
+ }
66
+ function assertDeploymentTuple(appEnv, values) {
67
+ const tier = resolveDeploymentTier(appEnv);
68
+ const expected = {
69
+ CONVEX_DEPLOYMENT: tier.deployment,
70
+ CONVEX_URL: tier.convexUrl,
71
+ CONVEX_SITE_URL: tier.convexSiteUrl
72
+ };
73
+ const mismatches = Object.entries(expected).flatMap(([name, expectedValue]) => {
74
+ const actual = values[name]?.trim();
75
+ return actual === expectedValue ? [] : [`${name}: expected '${expectedValue}', received '${actual ?? "<missing>"}'`];
76
+ });
77
+ const deployKey = values.CONVEX_DEPLOY_KEY?.trim();
78
+ if (deployKey !== void 0 && deployKey.length > 0) {
79
+ const separatorIndex = deployKey.indexOf("|");
80
+ const candidateDeployment = separatorIndex > 0 && deployKey.slice(separatorIndex + 1).trim().length > 0 ? deployKey.slice(0, separatorIndex) : "";
81
+ const keyDeployment = /^(?:dev|prod):[a-z0-9-]+$/u.test(candidateDeployment) ? candidateDeployment : void 0;
82
+ if (keyDeployment !== tier.deployment) mismatches.push(`CONVEX_DEPLOY_KEY: expected a key bound to '${tier.deployment}', received a key for '${keyDeployment ?? "<invalid>"}'`);
83
+ }
84
+ for (const optionalUrlName of ["CAPXUL_E2E_BOOTSTRAP_URL", "CAPXUL_E2E_BOOTSTRAP_BASE_URL"]) {
85
+ const raw = values[optionalUrlName]?.trim();
86
+ if (raw === void 0 || raw.length === 0) continue;
87
+ let actualHost;
222
88
  try {
223
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
224
- aesgcm.setAuthTag(authTag);
225
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
226
- } catch (error) {
227
- const isRange = error instanceof RangeError;
228
- const invalidKeyLength = error.message === "Invalid key length";
229
- const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
230
- if (isRange || invalidKeyLength) {
231
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
232
- err.code = "INVALID_DOTENV_KEY";
233
- throw err;
234
- } else if (decryptionFailed) {
235
- const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
236
- err.code = "DECRYPTION_FAILED";
237
- throw err;
238
- } else throw error;
239
- }
240
- }
241
- function populate(processEnv, parsed, options = {}) {
242
- const debug = Boolean(options && options.debug);
243
- const override = Boolean(options && options.override);
244
- const populated = {};
245
- if (typeof parsed !== "object") {
246
- const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
247
- err.code = "OBJECT_REQUIRED";
248
- throw err;
249
- }
250
- for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
251
- if (override === true) {
252
- processEnv[key] = parsed[key];
253
- populated[key] = parsed[key];
254
- }
255
- if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
256
- else _debug(`"${key}" is already defined and was NOT overwritten`);
257
- } else {
258
- processEnv[key] = parsed[key];
259
- populated[key] = parsed[key];
89
+ actualHost = new URL(raw).host;
90
+ } catch {
91
+ mismatches.push(`${optionalUrlName}: expected a URL for ${tier.name}, received an invalid URL`);
92
+ continue;
260
93
  }
261
- return populated;
262
- }
263
- const DotenvModule = {
264
- configDotenv,
265
- _configVault,
266
- _parseVault,
267
- config,
268
- decrypt,
269
- parse,
270
- populate
271
- };
272
- module.exports.configDotenv = DotenvModule.configDotenv;
273
- module.exports._configVault = DotenvModule._configVault;
274
- module.exports._parseVault = DotenvModule._parseVault;
275
- module.exports.config = DotenvModule.config;
276
- module.exports.decrypt = DotenvModule.decrypt;
277
- module.exports.parse = DotenvModule.parse;
278
- module.exports.populate = DotenvModule.populate;
279
- module.exports = DotenvModule;
280
- })))();
281
- const backendRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
282
- const repoRoot = resolve(backendRoot, "..", "..");
283
- const defaultOperatorSecretsPath = resolve(homedir(), ".config/capxul/secrets.env");
284
- const DEFAULT_APP_NAME = "Customer Next.js Quickstart";
285
- const DEFAULT_ALLOWED_ORIGIN = "http://localhost:3000";
286
- const DEFAULT_HANDOFF_PATH = resolve(homedir(), ".config/capxul/quickstart-handoffs/customer-nextjs-quickstart.md");
287
- const CANONICAL_QUICKSTART_DEPLOYMENT = {
288
- deployment: "dev:glad-jaguar-154",
289
- convexUrl: "https://glad-jaguar-154.convex.cloud",
290
- convexSiteUrl: "https://glad-jaguar-154.convex.site"
291
- };
292
- function loadOperatorEnv(sourceEnv = process.env) {
293
- const env = { ...sourceEnv };
294
- const envFiles = [defaultOperatorSecretsPath, env.CAPXUL_SECRETS_FILE ? resolve(env.CAPXUL_SECRETS_FILE) : void 0].filter((path) => path !== void 0);
295
- for (const path of envFiles) if (existsSync(path)) {
296
- const parsed = (0, import_main.config)({
297
- path,
298
- processEnv: env,
299
- override: true
300
- });
301
- if (parsed.error !== void 0) throw parsed.error;
94
+ if (actualHost !== new URL(tier.convexSiteUrl).host) mismatches.push(`${optionalUrlName}: expected host '${new URL(tier.convexSiteUrl).host}', received '${actualHost}'`);
302
95
  }
303
- env.CONVEX_URL ||= env.CAPXUL_E2E_CONVEX_URL;
304
- env.CONVEX_SITE_URL ||= env.CAPXUL_E2E_CONVEX_SITE_URL;
305
- env.CAPXUL_E2E_ORIGIN ||= env.CAPXUL_E2E_BOOTSTRAP_URL || env.SITE_URL;
306
- return env;
96
+ if (mismatches.length > 0) throw new Error(`Deployment tuple mismatch: expected ${appEnv} '${tier.name}'. Refusing to continue.\n${mismatches.join("\n")}`);
97
+ return tier;
307
98
  }
308
- function requiredEnv(env, name) {
309
- const value = env[name]?.trim();
310
- if (value === void 0 || value.length === 0) throw new Error(`Missing required env: ${name}`);
311
- return value;
99
+ function runCli() {
100
+ const command = process.argv[2] ?? "check";
101
+ const appEnvIndex = process.argv.indexOf("--app-env");
102
+ const appEnv = appEnvIndex === -1 ? process.env.APP_ENV ?? "development" : process.argv[appEnvIndex + 1];
103
+ if (command === "print") {
104
+ process.stdout.write(`${JSON.stringify(resolveDeploymentTier(appEnv), null, 2)}\n`);
105
+ return;
106
+ }
107
+ if (command === "field") {
108
+ const fieldIndex = process.argv.indexOf("--field");
109
+ const field = fieldIndex === -1 ? void 0 : process.argv[fieldIndex + 1];
110
+ const tier = resolveDeploymentTier(appEnv);
111
+ if (field === void 0 || !Object.hasOwn(tier, field)) throw new Error(`Unknown deployment topology field '${String(field)}'`);
112
+ process.stdout.write(`${String(tier[field])}\n`);
113
+ return;
114
+ }
115
+ if (command !== "check") throw new Error(`Unknown deployment-topology command '${command}'; expected check, print, or field`);
116
+ const tier = assertDeploymentTuple(appEnv, process.env);
117
+ process.stdout.write(`Capxul ${tier.productRole} tuple verified: ${tier.deployment} (${tier.convexProject})\n`);
312
118
  }
119
+ if (process.argv[1] !== void 0 && path.basename(process.argv[1]) === "deployment-topology.mjs" && import.meta.url === pathToFileURL(process.argv[1]).href) try {
120
+ runCli();
121
+ } catch (error) {
122
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
123
+ process.exitCode = 1;
124
+ }
125
+ resolve(resolve(fileURLToPath(new URL("..", import.meta.url))), "..", "..");
126
+ const standingStaging = resolveDeploymentTier("staging");
127
+ const CANONICAL_QUICKSTART_DEPLOYMENT = {
128
+ deployment: standingStaging.deployment,
129
+ convexUrl: standingStaging.convexUrl,
130
+ convexSiteUrl: standingStaging.convexSiteUrl
131
+ };
313
132
  function normalizeHttpOrigin(raw) {
314
133
  const value = raw.trim();
315
134
  if (value.length === 0) throw new Error("Origin is required.");
@@ -324,42 +143,6 @@ function normalizeHttpOrigin(raw) {
324
143
  if (url.pathname !== "/" || url.search || url.hash) throw new Error("Origin must not include a path, query, or hash.");
325
144
  return `${url.protocol}//${url.host}`;
326
145
  }
327
- function writeConvexDeploymentEnvFile(deployment) {
328
- const path = resolve(mkdtempSync(resolve(tmpdir(), "capxul-convex-")), "deployment.env");
329
- writeFileSync(path, `CONVEX_DEPLOYMENT=${deployment}\n`, {
330
- encoding: "utf8",
331
- mode: 384
332
- });
333
- return path;
334
- }
335
- function minimalConvexEnv() {
336
- return {
337
- CI: "true",
338
- HOME: homedir(),
339
- PATH: process.env.PATH ?? "",
340
- TMPDIR: process.env.TMPDIR ?? tmpdir()
341
- };
342
- }
343
- function runConvex(deploymentEnvFile, args) {
344
- const result = spawnSync(resolve(backendRoot, "node_modules/.bin/convex"), [
345
- ...args,
346
- "--env-file",
347
- deploymentEnvFile
348
- ], {
349
- cwd: backendRoot,
350
- env: minimalConvexEnv(),
351
- encoding: "utf8",
352
- stdio: [
353
- "ignore",
354
- "pipe",
355
- "pipe"
356
- ]
357
- });
358
- return {
359
- ok: result.status === 0,
360
- output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim()
361
- };
362
- }
363
146
  function extractField(output, field) {
364
147
  const quoted = new RegExp(`"${field}"\\s*:\\s*"([^"]+)"`).exec(output);
365
148
  if (quoted?.[1]) return quoted[1];
@@ -367,140 +150,6 @@ function extractField(output, field) {
367
150
  if (jsLike?.[1]) return jsLike[1];
368
151
  throw new Error(`Convex output did not include ${field}`);
369
152
  }
370
- function packageVersion(packageDir) {
371
- const pkg = JSON.parse(readFileSync(resolve(repoRoot, "packages", packageDir, "package.json"), "utf8"));
372
- if (!pkg.version) throw new Error(`Missing version in packages/${packageDir}/package.json`);
373
- return pkg.version;
374
- }
375
- function redactPublishableKeys(output) {
376
- return output.replace(/cap_pk_(test|live)_[0-9A-HJKMNP-TV-Z]+/g, "cap_pk_$1_REDACTED");
377
- }
378
- function writeSecureHandoff(path, values) {
379
- const handoffDir = dirname(path);
380
- const handoffDirAlreadyExisted = existsSync(handoffDir);
381
- mkdirSync(handoffDir, {
382
- recursive: true,
383
- mode: 448
384
- });
385
- if (!handoffDirAlreadyExisted) chmodSync(handoffDir, 448);
386
- const body = `# Capxul Next.js Quickstart Secure Handoff
387
-
388
- Generated: ${(/* @__PURE__ */ new Date()).toISOString()}
389
-
390
- | Value | Customer value |
391
- | --- | --- |
392
- | Package versions | @capxul/sdk@${values.sdkVersion}, @capxul/sdk-react@${values.sdkReactVersion} |
393
- | npm dist tag | alpha |
394
- | Environment | ${values.environment} |
395
- | Developer application | ${values.appName} |
396
- | Application id | ${values.applicationId} |
397
- | Publishable key id | ${values.keyId} |
398
- | Publishable key | ${values.publishableKey} |
399
- | Capxul site URL | ${values.convexSiteUrl} |
400
- | Convex URL | ${values.convexUrl} |
401
- | Local allowed origin | ${values.allowedOrigin} |
402
- | Production allowed origin | <set after customer domain is known> |
403
- | Auth method | Email OTP |
404
-
405
- Put the publishable key in \`.env.local\` as
406
- \`NEXT_PUBLIC_CAPXUL_PUBLISHABLE_KEY\`, and set server-side
407
- \`CAPXUL_SITE_URL=${values.convexSiteUrl}\` for the Next.js rewrites. Do not send
408
- backend secrets, private keys, Convex deploy keys, Resend keys, Openfort server
409
- keys, or operator credentials to the customer.
410
- `;
411
- const tmpDir = mkdtempSync(join(handoffDir, ".handoff-"));
412
- try {
413
- const tmpPath = join(tmpDir, "quickstart.md");
414
- writeFileSync(tmpPath, body, {
415
- encoding: "utf8",
416
- mode: 384
417
- });
418
- chmodSync(tmpPath, 384);
419
- renameSync(tmpPath, path);
420
- chmodSync(path, 384);
421
- } finally {
422
- rmSync(tmpDir, {
423
- recursive: true,
424
- force: true
425
- });
426
- }
427
- }
428
- async function mintNextjsQuickstartKey(input, deps = {}) {
429
- const environment = input.environment ?? "test";
430
- const pushBackend = input.pushBackend ?? true;
431
- const openfortPublishableKey = requiredEnv(input.env, "OPENFORT_PUBLISHABLE_KEY");
432
- const shieldPublishableKey = requiredEnv(input.env, "SHIELD_PUBLISHABLE_KEY");
433
- const allowedOrigin = normalizeHttpOrigin(input.allowedOrigin);
434
- const convexSiteUrl = input.convexSiteUrl.replace(/\/$/, "");
435
- const convexUrl = input.convexUrl.replace(/\/$/, "");
436
- const authBaseUrl = `${convexSiteUrl}/api/auth`;
437
- const deploymentEnvFile = writeConvexDeploymentEnvFile(input.deployment);
438
- const run = deps.runConvex ?? runConvex;
439
- const resolvePackageVersion = deps.packageVersion ?? packageVersion;
440
- if (pushBackend) {
441
- const deploy = run(deploymentEnvFile, ["dev", "--once"]);
442
- if (!deploy.ok) throw new Error(deploy.output || "Convex deploy failed.");
443
- }
444
- const publishableKeyConfig = {
445
- allowedOrigins: [allowedOrigin],
446
- authBaseUrl,
447
- convexUrl,
448
- siteBaseUrl: convexSiteUrl,
449
- openfortPublishableKey,
450
- shieldPublishableKey
451
- };
452
- const app = run(deploymentEnvFile, [
453
- "run",
454
- "credentials/mutations:createDeveloperApplication",
455
- JSON.stringify({
456
- name: input.appName,
457
- ...publishableKeyConfig
458
- })
459
- ]);
460
- if (!app.ok) throw new Error(app.output || "Developer application creation failed.");
461
- const applicationId = extractField(app.output, "applicationId");
462
- const key = run(deploymentEnvFile, [
463
- "run",
464
- "credentials/mutations:mintPublishableKey",
465
- JSON.stringify({
466
- applicationId,
467
- environment,
468
- ...publishableKeyConfig
469
- })
470
- ]);
471
- if (!key.ok) throw new Error(redactPublishableKeys(key.output || "Publishable key mint failed."));
472
- const keyId = extractField(key.output, "keyId");
473
- const publishableKey = extractField(key.output, "publishableKey");
474
- writeSecureHandoff(input.handoffPath, {
475
- appName: input.appName,
476
- applicationId,
477
- keyId,
478
- publishableKey,
479
- allowedOrigin,
480
- convexSiteUrl,
481
- convexUrl,
482
- sdkVersion: resolvePackageVersion("sdk"),
483
- sdkReactVersion: resolvePackageVersion("sdk-react"),
484
- environment
485
- });
486
- return {
487
- appName: input.appName,
488
- applicationId,
489
- keyId,
490
- publishableKey,
491
- allowedOrigin,
492
- convexSiteUrl,
493
- convexUrl,
494
- handoffPath: input.handoffPath,
495
- environment
496
- };
497
- }
498
- //#endregion
499
- //#region src/runtime.ts
500
- const bundledPackageVersions = {
501
- sdk: "1.0.0-alpha.14",
502
- "sdk-react": "1.0.0-alpha.14"
503
- };
504
153
  const packageRoot = fileURLToPath(new URL("..", import.meta.url));
505
154
  const FAUCET_DECIMALS = 6n;
506
155
  const FAUCET_DECIMAL_PLACES = Number(FAUCET_DECIMALS);
@@ -545,11 +194,6 @@ function convexChildEnv(deployment, sourceEnv) {
545
194
  }
546
195
  return env;
547
196
  }
548
- function bundledPackageVersion(packageDir) {
549
- const version = bundledPackageVersions[packageDir];
550
- if (version === void 0 || version.length === 0) throw new Error(`Missing bundled package version for ${packageDir}`);
551
- return version;
552
- }
553
197
  function createConvexPathRunner({ deployment, env: sourceEnv = process.env, spawn = spawnSync }) {
554
198
  return (_deploymentEnvFile, args) => {
555
199
  const childEnv = convexChildEnv(deployment, sourceEnv);
@@ -696,7 +340,7 @@ async function runFaucetSend() {
696
340
  const s = spinner();
697
341
  s.start("Minting testnet funds");
698
342
  try {
699
- const runConvex = canonicalConvexRunner(loadOperatorEnv());
343
+ const runConvex = canonicalConvexRunner();
700
344
  const result = recipient.kind === "address" ? runConvex("", [
701
345
  "run",
702
346
  FAUCET_ADDRESS_FUNCTION,
@@ -728,34 +372,127 @@ async function runFaucetSend() {
728
372
  return 0;
729
373
  } catch (error) {
730
374
  s.stop("Faucet send failed");
731
- cancel(errorMessage(error));
375
+ const hint = process.env.CONVEX_DEPLOY_KEY === void 0 ? "\nHint: CONVEX_DEPLOY_KEY is not set — the faucet needs operator access to the canonical deployment. Supply it (CONVEX_DEPLOY_KEY=… npx @capxul/sandbox faucet send) or, inside the infrastructure repo, run through scripts/capxul-env.sh." : "";
376
+ cancel(errorMessage(error) + hint);
732
377
  return 1;
733
378
  }
734
379
  }
380
+ /** Default developer origin when the caller passes no origin. */
381
+ const DEFAULT_ORIGIN = "http://localhost:3000";
382
+ /**
383
+ * Origins the shared sandbox deployment pre-trusts for email/OTP auth. Mirrors
384
+ * `QUICKSTART_ORIGINS` in `scripts/sync-convex-env.sh` (which unions these into
385
+ * the deployment's `CAPXUL_TRUSTED_ORIGINS`). A minted key scopes *bootstrap* to
386
+ * whatever origin you pass, but the deployment-level trusted-origin gate
387
+ * (`authFactory.buildTrustedOrigins`) rejects OTP/auth requests from origins
388
+ * outside this set — and a self-serve `npx` caller cannot change that env var.
389
+ * So an origin outside this set bootstraps but never completes sign-in. Keep in
390
+ * sync with `sync-convex-env.sh`.
391
+ */
392
+ const PRETRUSTED_QUICKSTART_ORIGINS = ["http://localhost:3000", "http://localhost:3100"];
393
+ function isPretrustedQuickstartOrigin(origin) {
394
+ return PRETRUSTED_QUICKSTART_ORIGINS.includes(origin);
395
+ }
396
+ const ENV_FILE_NAME = ".env.local";
397
+ const PUBLISHABLE_KEY_VAR = "NEXT_PUBLIC_CAPXUL_PUBLISHABLE_KEY";
398
+ const SITE_URL_VAR = "CAPXUL_SITE_URL";
399
+ function resolveOrigin(options) {
400
+ return options.origin ?? "http://localhost:3000";
401
+ }
402
+ function isMintResponse(value) {
403
+ if (typeof value !== "object" || value === null) return false;
404
+ const candidate = value;
405
+ return typeof candidate.publishableKey === "string" && typeof candidate.convexSiteUrl === "string" && typeof candidate.authBaseUrl === "string" && Array.isArray(candidate.allowedOrigins) && candidate.allowedOrigins.every((origin) => typeof origin === "string");
406
+ }
407
+ /**
408
+ * Upsert `key=value` into env-file text: replace the line if the key already
409
+ * exists (preserving every other line), otherwise append. Keeps a developer's
410
+ * existing `.env.local` intact rather than overwriting it.
411
+ */
412
+ function upsertEnvVar(contents, key, value) {
413
+ const line = `${key}=${value}`;
414
+ const lines = contents.length === 0 ? [] : contents.split("\n");
415
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
416
+ const pattern = new RegExp(`^${key}=`);
417
+ let replaced = false;
418
+ const next = lines.map((existing) => {
419
+ if (pattern.test(existing)) {
420
+ replaced = true;
421
+ return line;
422
+ }
423
+ return existing;
424
+ });
425
+ if (!replaced) next.push(line);
426
+ return `${next.join("\n")}\n`;
427
+ }
428
+ function rewriteSnippet() {
429
+ return [
430
+ "Add these rewrites to next.config.ts so browser requests stay same-origin:",
431
+ "",
432
+ " import type { NextConfig } from \"next\";",
433
+ " import { loadEnvConfig } from \"@next/env\";",
434
+ "",
435
+ " loadEnvConfig(process.cwd());",
436
+ "",
437
+ " const capxulSiteUrl = process.env.CAPXUL_SITE_URL;",
438
+ " if (!capxulSiteUrl) {",
439
+ " throw new Error(\"CAPXUL_SITE_URL is required\");",
440
+ " }",
441
+ "",
442
+ " const nextConfig: NextConfig = {",
443
+ " async rewrites() {",
444
+ " return [",
445
+ " {",
446
+ " source: \"/v1/client/bootstrap\",",
447
+ " destination: `${capxulSiteUrl}/v1/client/bootstrap`,",
448
+ " },",
449
+ " {",
450
+ " source: \"/api/auth/:path*\",",
451
+ " destination: `${capxulSiteUrl}/api/auth/:path*`,",
452
+ " },",
453
+ " ];",
454
+ " },",
455
+ " };",
456
+ "",
457
+ " export default nextConfig;"
458
+ ].join("\n");
459
+ }
460
+ async function runQuickstart(options, deps) {
461
+ const origin = resolveOrigin(options);
462
+ const endpoint = `${deps.baseUrl.replace(/\/$/, "")}/v1/client/mint-quickstart-key`;
463
+ deps.log(`Requesting a sandbox publishable key for ${origin} ...`);
464
+ const response = await deps.fetch(endpoint, {
465
+ method: "POST",
466
+ headers: { "content-type": "application/json" },
467
+ body: JSON.stringify({ origin })
468
+ });
469
+ if (!response.ok) {
470
+ const detail = await response.text().catch(() => "");
471
+ throw new Error(`Mint request failed (HTTP ${response.status})${detail ? `: ${detail}` : ""}`);
472
+ }
473
+ const payload = await response.json();
474
+ if (!isMintResponse(payload)) throw new Error("Mint response did not match the expected shape.");
475
+ let updated = upsertEnvVar(await deps.readEnvFile() ?? "", PUBLISHABLE_KEY_VAR, payload.publishableKey);
476
+ updated = upsertEnvVar(updated, SITE_URL_VAR, payload.convexSiteUrl);
477
+ await deps.writeEnvFile(updated);
478
+ deps.log(`Wrote ${PUBLISHABLE_KEY_VAR} and ${SITE_URL_VAR} to ${ENV_FILE_NAME}.`);
479
+ deps.log(`Key is scoped to: ${payload.allowedOrigins.join(", ")}`);
480
+ deps.log("");
481
+ deps.log(rewriteSnippet());
482
+ return payload;
483
+ }
735
484
  //#endregion
736
485
  //#region src/commands/key-create.ts
737
486
  async function runKeyCreate() {
738
487
  intro("Capxul sandbox key create");
739
488
  note([
740
- `Deployment: ${CANONICAL_QUICKSTART_DEPLOYMENT.deployment}`,
741
- `Site URL: ${CANONICAL_QUICKSTART_DEPLOYMENT.convexSiteUrl}`,
742
- `Convex URL: ${CANONICAL_QUICKSTART_DEPLOYMENT.convexUrl}`,
743
- "This npx CLI calls the already-deployed canonical backend; it does not push code."
744
- ].join("\n"), "Canonical deployment");
745
- const appNamePrompt = await text({
746
- message: "Developer application name",
747
- initialValue: DEFAULT_APP_NAME,
748
- validate(value) {
749
- if ((value ?? "").trim().length === 0) return "Application name is required.";
750
- }
751
- });
752
- if (isCancel(appNamePrompt)) {
753
- cancel("No key created.");
754
- return 0;
755
- }
756
- const allowedOriginPrompt = await text({
489
+ "Mints a sandbox test publishable key from the public Capxul backend.",
490
+ "No secrets, no login — nothing to configure. The key is written to",
491
+ ".env.local in this directory (existing values are preserved)."
492
+ ].join("\n"), "Quickstart");
493
+ const originPrompt = await text({
757
494
  message: "Allowed local origin",
758
- initialValue: DEFAULT_ALLOWED_ORIGIN,
495
+ initialValue: DEFAULT_ORIGIN,
759
496
  validate(value) {
760
497
  try {
761
498
  normalizeHttpOrigin(value ?? "");
@@ -764,58 +501,44 @@ async function runKeyCreate() {
764
501
  }
765
502
  }
766
503
  });
767
- if (isCancel(allowedOriginPrompt)) {
768
- cancel("No key created.");
769
- return 0;
770
- }
771
- const handoffPathPrompt = await text({
772
- message: "Secure handoff file",
773
- initialValue: DEFAULT_HANDOFF_PATH,
774
- validate(value) {
775
- if ((value ?? "").trim().length === 0) return "Handoff path is required.";
776
- }
777
- });
778
- if (isCancel(handoffPathPrompt)) {
779
- cancel("No key created.");
780
- return 0;
781
- }
782
- const appName = appNamePrompt.trim();
783
- const allowedOrigin = normalizeHttpOrigin(allowedOriginPrompt);
784
- const handoffPath = handoffPathPrompt.trim();
785
- const shouldCreate = await confirm({
786
- message: `Create a test publishable key for ${appName}?`,
787
- initialValue: true
788
- });
789
- if (isCancel(shouldCreate) || shouldCreate === false) {
504
+ if (isCancel(originPrompt)) {
790
505
  cancel("No key created.");
791
506
  return 0;
792
507
  }
508
+ const origin = normalizeHttpOrigin(originPrompt);
509
+ const baseUrl = process.env.CAPXUL_QUICKSTART_URL ?? "https://little-sandpiper-974.convex.site";
510
+ const envPath = resolve(process.cwd(), ".env.local");
793
511
  const s = spinner();
794
- s.start("Creating developer application and test publishable key");
512
+ s.start("Requesting a sandbox publishable key");
795
513
  try {
796
- const operatorEnv = loadOperatorEnv();
797
- const result = await mintNextjsQuickstartKey({
798
- env: operatorEnv,
799
- ...CANONICAL_QUICKSTART_DEPLOYMENT,
800
- appName,
801
- allowedOrigin,
802
- handoffPath,
803
- environment: "test",
804
- pushBackend: false
805
- }, {
806
- packageVersion: bundledPackageVersion,
807
- runConvex: canonicalConvexRunner(operatorEnv)
514
+ const result = await runQuickstart({ origin }, {
515
+ baseUrl,
516
+ fetch: globalThis.fetch,
517
+ readEnvFile: async () => {
518
+ try {
519
+ return await readFile(envPath, "utf8");
520
+ } catch {
521
+ return null;
522
+ }
523
+ },
524
+ writeEnvFile: (contents) => writeFile(envPath, contents, { mode: 384 }),
525
+ log: () => {}
808
526
  });
809
- s.stop("Publishable key captured in secure handoff");
527
+ s.stop("Publishable key written to .env.local");
810
528
  note([
811
- `Handoff: ${result.handoffPath}`,
812
- `Application id: ${result.applicationId}`,
813
- `Key id: ${result.keyId}`,
814
- `Allowed origin: ${result.allowedOrigin}`,
815
- `Capxul site URL: ${result.convexSiteUrl}`,
816
- "Raw publishable key was not printed; copy it from the handoff file.",
817
- "Before handoff, ensure CAPXUL_TRUSTED_ORIGINS and CORS_ALLOWED_ORIGINS include this origin."
818
- ].join("\n"), "Created");
529
+ "Wrote NEXT_PUBLIC_CAPXUL_PUBLISHABLE_KEY and CAPXUL_SITE_URL to .env.local",
530
+ "(any other lines were preserved).",
531
+ `Key is scoped to: ${result.allowedOrigins.join(", ")}`
532
+ ].join("\n"), "Written");
533
+ if (!isPretrustedQuickstartOrigin(origin)) note([
534
+ `The shared sandbox only completes email/OTP sign-in for its pre-trusted`,
535
+ `origins: ${PRETRUSTED_QUICKSTART_ORIGINS.join(", ")}.`,
536
+ ``,
537
+ `${origin} will bootstrap, but sign-in requests are rejected until Capxul`,
538
+ `adds it. For the self-serve quickstart, run your app on a pre-trusted`,
539
+ `origin (for example http://localhost:3000).`
540
+ ].join("\n"), "Origin not pre-trusted");
541
+ note(rewriteSnippet(), "Next steps");
819
542
  outro("Done.");
820
543
  return 0;
821
544
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/sandbox",
3
- "version": "1.0.0-alpha.2",
3
+ "version": "1.0.0-alpha.4",
4
4
  "private": false,
5
5
  "description": "Capxul sandbox CLI for canonical quickstart keys and testnet faucet funds.",
6
6
  "keywords": [