@capxul/sandbox 1.0.0-alpha.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.
Files changed (2) hide show
  1. package/dist/main.mjs +848 -0
  2. package/package.json +51 -0
package/dist/main.mjs ADDED
@@ -0,0 +1,848 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { cancel, confirm, intro, isCancel, note, outro, select, spinner, text } from "@clack/prompts";
4
+ import { spawnSync } from "node:child_process";
5
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ 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;
185
+ }
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);
222
+ 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];
260
+ }
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;
302
+ }
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;
307
+ }
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;
312
+ }
313
+ function normalizeHttpOrigin(raw) {
314
+ const value = raw.trim();
315
+ if (value.length === 0) throw new Error("Origin is required.");
316
+ let url;
317
+ try {
318
+ url = new URL(value);
319
+ } catch {
320
+ throw new Error("Origin must be a valid URL, for example http://localhost:3000.");
321
+ }
322
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("Origin must use http or https.");
323
+ if (url.username || url.password) throw new Error("Origin must not include credentials.");
324
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error("Origin must not include a path, query, or hash.");
325
+ return `${url.protocol}//${url.host}`;
326
+ }
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
+ function extractField(output, field) {
364
+ const quoted = new RegExp(`"${field}"\\s*:\\s*"([^"]+)"`).exec(output);
365
+ if (quoted?.[1]) return quoted[1];
366
+ const jsLike = new RegExp(`${field}\\s*:\\s*"([^"]+)"`).exec(output);
367
+ if (jsLike?.[1]) return jsLike[1];
368
+ throw new Error(`Convex output did not include ${field}`);
369
+ }
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.11",
502
+ "sdk-react": "1.0.0-alpha.11"
503
+ };
504
+ const packageRoot = fileURLToPath(new URL("..", import.meta.url));
505
+ const FAUCET_DECIMALS = 6n;
506
+ const FAUCET_DECIMAL_PLACES = Number(FAUCET_DECIMALS);
507
+ const FAUCET_SCALE = 10n ** FAUCET_DECIMALS;
508
+ const FAUCET_MAX_BASE_UNITS = 10000n * FAUCET_SCALE;
509
+ const EVM_ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;
510
+ const PLATFORM_ENV_NAMES = [
511
+ "COMSPEC",
512
+ "ComSpec",
513
+ "PATHEXT",
514
+ "SystemRoot",
515
+ "WINDIR",
516
+ "windir"
517
+ ];
518
+ function convexArgsForDeployment(args, deployment, hasDeployKey) {
519
+ if (hasDeployKey) return [...args];
520
+ if (args[0] === "run") return [
521
+ "run",
522
+ "--deployment",
523
+ deployment,
524
+ ...args.slice(1)
525
+ ];
526
+ return [
527
+ ...args,
528
+ "--deployment",
529
+ deployment
530
+ ];
531
+ }
532
+ function convexChildEnv(deployment, sourceEnv) {
533
+ const env = {
534
+ CI: "true",
535
+ CONVEX_DEPLOYMENT: deployment,
536
+ HOME: homedir(),
537
+ PATH: process.env.PATH ?? "",
538
+ TMPDIR: process.env.TMPDIR ?? tmpdir()
539
+ };
540
+ const deployKey = sourceEnv.CONVEX_DEPLOY_KEY?.trim();
541
+ if (deployKey !== void 0 && deployKey.length > 0) env.CONVEX_DEPLOY_KEY = deployKey;
542
+ for (const name of PLATFORM_ENV_NAMES) {
543
+ const value = process.env[name];
544
+ if (value !== void 0 && value.length > 0) env[name] = value;
545
+ }
546
+ return env;
547
+ }
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
+ function createConvexPathRunner({ deployment, env: sourceEnv = process.env, spawn = spawnSync }) {
554
+ return (_deploymentEnvFile, args) => {
555
+ const childEnv = convexChildEnv(deployment, sourceEnv);
556
+ const result = spawn("convex", convexArgsForDeployment(args, deployment, childEnv.CONVEX_DEPLOY_KEY !== void 0), {
557
+ cwd: packageRoot,
558
+ env: childEnv,
559
+ encoding: "utf8",
560
+ stdio: [
561
+ "ignore",
562
+ "pipe",
563
+ "pipe"
564
+ ]
565
+ });
566
+ const processError = result.error instanceof Error ? result.error.message : "";
567
+ return {
568
+ ok: result.status === 0,
569
+ output: `${result.stdout ?? ""}${result.stderr ?? ""}${processError}`.trim()
570
+ };
571
+ };
572
+ }
573
+ function normalizeEvmAddress(value) {
574
+ const address = value.trim();
575
+ if (!EVM_ADDRESS_PATTERN.test(address)) throw new Error("Address must be a 0x-prefixed 20-byte EVM address.");
576
+ return address;
577
+ }
578
+ function usdAmountToBaseUnits(value) {
579
+ const amount = value.trim();
580
+ const match = /^([0-9]+)(?:\.([0-9]+))?$/.exec(amount);
581
+ if (match === null) throw new Error("Amount must be a positive decimal, for example 10 or 10.5.");
582
+ const whole = BigInt(match[1] ?? "0");
583
+ const fractional = match[2] ?? "";
584
+ if (fractional.length > FAUCET_DECIMAL_PLACES) throw new Error("Amount supports at most 6 decimal places.");
585
+ const fractionalBaseUnits = BigInt(fractional.padEnd(FAUCET_DECIMAL_PLACES, "0"));
586
+ const baseUnits = whole * FAUCET_SCALE + fractionalBaseUnits;
587
+ if (baseUnits <= 0n) throw new Error("Amount must be greater than 0.");
588
+ if (baseUnits > FAUCET_MAX_BASE_UNITS) throw new Error("Amount must not exceed 10000 USDX.");
589
+ return baseUnits.toString();
590
+ }
591
+ //#endregion
592
+ //#region src/commands/shared.ts
593
+ function errorMessage(error) {
594
+ return error instanceof Error ? error.message : String(error);
595
+ }
596
+ function canonicalConvexRunner(env = process.env) {
597
+ return createConvexPathRunner({
598
+ deployment: CANONICAL_QUICKSTART_DEPLOYMENT.deployment,
599
+ env
600
+ });
601
+ }
602
+ //#endregion
603
+ //#region src/commands/faucet-send.ts
604
+ const DEFAULT_FAUCET_AMOUNT = "10";
605
+ const FAUCET_FUNCTION = "dev/faucetMintTo:mintTo";
606
+ async function runFaucetSend() {
607
+ intro("Capxul sandbox faucet send");
608
+ note([
609
+ `Deployment: ${CANONICAL_QUICKSTART_DEPLOYMENT.deployment}`,
610
+ "Chain: Base Sepolia (84532)",
611
+ "Asset: test USDX, 6 decimals",
612
+ "This command calls the canonical backend dev faucet and cannot select live/mainnet."
613
+ ].join("\n"), "Canonical sandbox");
614
+ const addressPrompt = await text({
615
+ message: "Recipient EVM address",
616
+ validate(value) {
617
+ try {
618
+ normalizeEvmAddress(value ?? "");
619
+ } catch (error) {
620
+ return errorMessage(error);
621
+ }
622
+ }
623
+ });
624
+ if (isCancel(addressPrompt)) {
625
+ cancel("No faucet funds sent.");
626
+ return 0;
627
+ }
628
+ const amountPrompt = await text({
629
+ message: "USDX amount",
630
+ initialValue: DEFAULT_FAUCET_AMOUNT,
631
+ validate(value) {
632
+ try {
633
+ usdAmountToBaseUnits(value ?? "");
634
+ } catch (error) {
635
+ return errorMessage(error);
636
+ }
637
+ }
638
+ });
639
+ if (isCancel(amountPrompt)) {
640
+ cancel("No faucet funds sent.");
641
+ return 0;
642
+ }
643
+ const holderAddress = normalizeEvmAddress(addressPrompt);
644
+ const rawAmount = usdAmountToBaseUnits(amountPrompt);
645
+ const displayAmount = amountPrompt.trim();
646
+ const shouldSend = await confirm({
647
+ message: `Mint ${displayAmount} test USDX to ${holderAddress}?`,
648
+ initialValue: true
649
+ });
650
+ if (isCancel(shouldSend) || shouldSend === false) {
651
+ cancel("No faucet funds sent.");
652
+ return 0;
653
+ }
654
+ const s = spinner();
655
+ s.start("Minting testnet funds");
656
+ try {
657
+ const result = canonicalConvexRunner(loadOperatorEnv())("", [
658
+ "run",
659
+ FAUCET_FUNCTION,
660
+ JSON.stringify({
661
+ holderAddress,
662
+ rawAmount
663
+ })
664
+ ]);
665
+ if (!result.ok) throw new Error(result.output || "Faucet mint failed.");
666
+ const txHash = extractField(result.output, "txHash");
667
+ s.stop("Faucet funds sent");
668
+ note([
669
+ `Recipient: ${holderAddress}`,
670
+ `Amount: ${displayAmount} USDX`,
671
+ `Raw amount: ${rawAmount}`,
672
+ `Chain: Base Sepolia (84532)`,
673
+ `Transaction hash: ${txHash}`
674
+ ].join("\n"), "Funded");
675
+ outro("Done.");
676
+ return 0;
677
+ } catch (error) {
678
+ s.stop("Faucet send failed");
679
+ cancel(errorMessage(error));
680
+ return 1;
681
+ }
682
+ }
683
+ //#endregion
684
+ //#region src/commands/key-create.ts
685
+ async function runKeyCreate() {
686
+ intro("Capxul sandbox key create");
687
+ note([
688
+ `Deployment: ${CANONICAL_QUICKSTART_DEPLOYMENT.deployment}`,
689
+ `Site URL: ${CANONICAL_QUICKSTART_DEPLOYMENT.convexSiteUrl}`,
690
+ `Convex URL: ${CANONICAL_QUICKSTART_DEPLOYMENT.convexUrl}`,
691
+ "This npx CLI calls the already-deployed canonical backend; it does not push code."
692
+ ].join("\n"), "Canonical deployment");
693
+ const appNamePrompt = await text({
694
+ message: "Developer application name",
695
+ initialValue: DEFAULT_APP_NAME,
696
+ validate(value) {
697
+ if ((value ?? "").trim().length === 0) return "Application name is required.";
698
+ }
699
+ });
700
+ if (isCancel(appNamePrompt)) {
701
+ cancel("No key created.");
702
+ return 0;
703
+ }
704
+ const allowedOriginPrompt = await text({
705
+ message: "Allowed local origin",
706
+ initialValue: DEFAULT_ALLOWED_ORIGIN,
707
+ validate(value) {
708
+ try {
709
+ normalizeHttpOrigin(value ?? "");
710
+ } catch (error) {
711
+ return errorMessage(error);
712
+ }
713
+ }
714
+ });
715
+ if (isCancel(allowedOriginPrompt)) {
716
+ cancel("No key created.");
717
+ return 0;
718
+ }
719
+ const handoffPathPrompt = await text({
720
+ message: "Secure handoff file",
721
+ initialValue: DEFAULT_HANDOFF_PATH,
722
+ validate(value) {
723
+ if ((value ?? "").trim().length === 0) return "Handoff path is required.";
724
+ }
725
+ });
726
+ if (isCancel(handoffPathPrompt)) {
727
+ cancel("No key created.");
728
+ return 0;
729
+ }
730
+ const appName = appNamePrompt.trim();
731
+ const allowedOrigin = normalizeHttpOrigin(allowedOriginPrompt);
732
+ const handoffPath = handoffPathPrompt.trim();
733
+ const shouldCreate = await confirm({
734
+ message: `Create a test publishable key for ${appName}?`,
735
+ initialValue: true
736
+ });
737
+ if (isCancel(shouldCreate) || shouldCreate === false) {
738
+ cancel("No key created.");
739
+ return 0;
740
+ }
741
+ const s = spinner();
742
+ s.start("Creating developer application and test publishable key");
743
+ try {
744
+ const operatorEnv = loadOperatorEnv();
745
+ const result = await mintNextjsQuickstartKey({
746
+ env: operatorEnv,
747
+ ...CANONICAL_QUICKSTART_DEPLOYMENT,
748
+ appName,
749
+ allowedOrigin,
750
+ handoffPath,
751
+ environment: "test",
752
+ pushBackend: false
753
+ }, {
754
+ packageVersion: bundledPackageVersion,
755
+ runConvex: canonicalConvexRunner(operatorEnv)
756
+ });
757
+ s.stop("Publishable key captured in secure handoff");
758
+ note([
759
+ `Handoff: ${result.handoffPath}`,
760
+ `Application id: ${result.applicationId}`,
761
+ `Key id: ${result.keyId}`,
762
+ `Allowed origin: ${result.allowedOrigin}`,
763
+ `Capxul site URL: ${result.convexSiteUrl}`,
764
+ "Raw publishable key was not printed; copy it from the handoff file.",
765
+ "Before handoff, ensure CAPXUL_TRUSTED_ORIGINS and CORS_ALLOWED_ORIGINS include this origin."
766
+ ].join("\n"), "Created");
767
+ outro("Done.");
768
+ return 0;
769
+ } catch (error) {
770
+ s.stop("Publishable key creation failed");
771
+ cancel(errorMessage(error));
772
+ return 1;
773
+ }
774
+ }
775
+ //#endregion
776
+ //#region src/main.ts
777
+ const SANDBOX_COMMANDS = [{
778
+ value: "key create",
779
+ label: "Create publishable key",
780
+ usage: "npx @capxul/sandbox key create",
781
+ description: "Create a canonical quickstart test publishable key.",
782
+ run: runKeyCreate
783
+ }, {
784
+ value: "faucet send",
785
+ label: "Send testnet faucet funds",
786
+ usage: "npx @capxul/sandbox faucet send",
787
+ description: "Mint test USDX to an EVM address on Base Sepolia.",
788
+ run: runFaucetSend
789
+ }];
790
+ const HELP_COMMANDS = {
791
+ "--help": true,
792
+ "-h": true,
793
+ help: true
794
+ };
795
+ const COMMAND_BY_ARGS = {
796
+ "key create": "key create",
797
+ "faucet send": "faucet send"
798
+ };
799
+ const HELP_TEXT = [
800
+ "Usage:",
801
+ ...SANDBOX_COMMANDS.map(({ usage }) => ` ${usage}`),
802
+ "",
803
+ "Commands:",
804
+ ...SANDBOX_COMMANDS.map(({ value, description }) => ` ${value.padEnd(13)} ${description}`)
805
+ ].join("\n");
806
+ function commandFromArgs(argv) {
807
+ const command = (argv[0] === "--" ? argv.slice(1) : argv).join(" ");
808
+ if (command.length === 0) return null;
809
+ return HELP_COMMANDS[command] ? "help" : COMMAND_BY_ARGS[command] ?? "invalid";
810
+ }
811
+ async function selectCommand() {
812
+ const command = await select({
813
+ message: "Sandbox action",
814
+ options: SANDBOX_COMMANDS.map(({ value, label }) => ({
815
+ value,
816
+ label
817
+ }))
818
+ });
819
+ if (isCancel(command)) {
820
+ cancel("No sandbox command run.");
821
+ return null;
822
+ }
823
+ return command;
824
+ }
825
+ function runCommand(command) {
826
+ return SANDBOX_COMMANDS.find(({ value }) => value === command)?.run() ?? Promise.resolve(1);
827
+ }
828
+ async function main() {
829
+ const command = commandFromArgs(process.argv.slice(2)) ?? await selectCommand();
830
+ if (command === null) return 0;
831
+ if (command === "help") {
832
+ note(HELP_TEXT, "Capxul sandbox");
833
+ return 0;
834
+ }
835
+ if (command === "invalid") {
836
+ note(HELP_TEXT, "Invalid sandbox command");
837
+ return 1;
838
+ }
839
+ return runCommand(command);
840
+ }
841
+ main().then((code) => {
842
+ process.exitCode = code;
843
+ }).catch((error) => {
844
+ cancel(errorMessage(error));
845
+ process.exitCode = 1;
846
+ });
847
+ //#endregion
848
+ export {};
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@capxul/sandbox",
3
+ "version": "1.0.0-alpha.1",
4
+ "private": false,
5
+ "description": "Capxul sandbox CLI for canonical quickstart keys and testnet faucet funds.",
6
+ "keywords": [
7
+ "capxul",
8
+ "cli",
9
+ "sandbox",
10
+ "testnet"
11
+ ],
12
+ "homepage": "https://github.com/Xelmar-tech/infrastructure#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/Xelmar-tech/infrastructure/issues"
15
+ },
16
+ "license": "UNLICENSED",
17
+ "author": "Xelmar",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/Xelmar-tech/infrastructure.git",
21
+ "directory": "apps/sandbox"
22
+ },
23
+ "bin": {
24
+ "capxul-sandbox": "./dist/main.mjs",
25
+ "sandbox": "./dist/main.mjs"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "package.json"
30
+ ],
31
+ "type": "module",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@clack/prompts": "^1.7.0",
37
+ "convex": "^1.39.1"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.15.3",
41
+ "tsx": "^4.22.1",
42
+ "typescript": "5.9.2",
43
+ "vite": "npm:@voidzero-dev/vite-plus-core@0.1.23",
44
+ "vite-plus": "0.1.23"
45
+ },
46
+ "scripts": {
47
+ "dev": "bun run src/main.ts",
48
+ "check-types": "vp exec tsc -p tsconfig.json --noEmit",
49
+ "build": "NODE_OPTIONS=--max-old-space-size=4096 vp pack"
50
+ }
51
+ }