@capxul/sandbox 1.0.0-alpha.1 → 1.0.0-alpha.3

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 +42 -0
  2. package/dist/main.mjs +217 -270
  3. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,42 @@
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 public quickstart endpoint and needs no operator secret.
19
+ `faucet send` invokes the canonical Convex deployment and requires operator
20
+ configuration from `~/.config/capxul/secrets.env`; never print or commit those
21
+ values.
22
+
23
+ ## Verify in the repository
24
+
25
+ ```bash
26
+ vp run --filter @capxul/sandbox check-types
27
+ vp test run apps/sandbox
28
+ vp run --filter @capxul/sandbox build
29
+ ```
30
+
31
+ These checks prove parsing, environment-file rewriting, bounded amount
32
+ conversion, Convex command construction, and packing. They do not prove a live
33
+ key mint, faucet transaction, or installed CLI artifact.
34
+
35
+ Repository Rule 4 names `vp run --filter @capxul/sandbox proofs:live` as the
36
+ live-only ProofKit boundary, but that command does not exist yet. Keep live
37
+ acceptance unproven until [#920](https://github.com/Xelmar-tech/infrastructure/issues/920)
38
+ lands. [#922](https://github.com/Xelmar-tech/infrastructure/issues/922) tracks
39
+ the separate packed-install/bin smoke gap.
40
+
41
+ Read [CONTEXT.md](./CONTEXT.md) before changing command, secret, deployment, or
42
+ proof behavior.
package/dist/main.mjs CHANGED
@@ -2,10 +2,11 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { cancel, confirm, intro, isCancel, note, outro, select, spinner, text } from "@clack/prompts";
4
4
  import { spawnSync } from "node:child_process";
5
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { existsSync } from "node:fs";
6
6
  import { homedir, tmpdir } from "node:os";
7
- import { dirname, join, resolve } from "node:path";
7
+ import { resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { readFile, writeFile } from "node:fs/promises";
9
10
  //#region \0rolldown/runtime.js
10
11
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
11
12
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
@@ -278,16 +279,12 @@ var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
278
279
  module.exports.populate = DotenvModule.populate;
279
280
  module.exports = DotenvModule;
280
281
  })))();
281
- const backendRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
282
- const repoRoot = resolve(backendRoot, "..", "..");
282
+ resolve(resolve(fileURLToPath(new URL("..", import.meta.url))), "..", "..");
283
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
284
  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"
285
+ deployment: "prod:little-sandpiper-974",
286
+ convexUrl: "https://little-sandpiper-974.convex.cloud",
287
+ convexSiteUrl: "https://little-sandpiper-974.convex.site"
291
288
  };
292
289
  function loadOperatorEnv(sourceEnv = process.env) {
293
290
  const env = { ...sourceEnv };
@@ -305,11 +302,6 @@ function loadOperatorEnv(sourceEnv = process.env) {
305
302
  env.CAPXUL_E2E_ORIGIN ||= env.CAPXUL_E2E_BOOTSTRAP_URL || env.SITE_URL;
306
303
  return env;
307
304
  }
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
305
  function normalizeHttpOrigin(raw) {
314
306
  const value = raw.trim();
315
307
  if (value.length === 0) throw new Error("Origin is required.");
@@ -324,42 +316,6 @@ function normalizeHttpOrigin(raw) {
324
316
  if (url.pathname !== "/" || url.search || url.hash) throw new Error("Origin must not include a path, query, or hash.");
325
317
  return `${url.protocol}//${url.host}`;
326
318
  }
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
319
  function extractField(output, field) {
364
320
  const quoted = new RegExp(`"${field}"\\s*:\\s*"([^"]+)"`).exec(output);
365
321
  if (quoted?.[1]) return quoted[1];
@@ -367,140 +323,6 @@ function extractField(output, field) {
367
323
  if (jsLike?.[1]) return jsLike[1];
368
324
  throw new Error(`Convex output did not include ${field}`);
369
325
  }
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
326
  const packageRoot = fileURLToPath(new URL("..", import.meta.url));
505
327
  const FAUCET_DECIMALS = 6n;
506
328
  const FAUCET_DECIMAL_PLACES = Number(FAUCET_DECIMALS);
@@ -545,11 +367,6 @@ function convexChildEnv(deployment, sourceEnv) {
545
367
  }
546
368
  return env;
547
369
  }
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
370
  function createConvexPathRunner({ deployment, env: sourceEnv = process.env, spawn = spawnSync }) {
554
371
  return (_deploymentEnvFile, args) => {
555
372
  const childEnv = convexChildEnv(deployment, sourceEnv);
@@ -570,10 +387,28 @@ function createConvexPathRunner({ deployment, env: sourceEnv = process.env, spaw
570
387
  };
571
388
  };
572
389
  }
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;
390
+ const ORG_HANDLE_SHAPE_PATTERN = /^[a-zA-Z0-9-]+$/;
391
+ /**
392
+ * Classify a faucet recipient prompt value: Capxul email, @org-handle, or
393
+ * as an explicit escape hatch — a raw EVM address. Canonical normalization
394
+ * (email lowercasing, handle validation) is left to the backend resolver.
395
+ */
396
+ function parseFaucetRecipient(value) {
397
+ const trimmed = value.trim();
398
+ if (EVM_ADDRESS_PATTERN.test(trimmed)) return {
399
+ kind: "address",
400
+ address: trimmed
401
+ };
402
+ if (trimmed.indexOf("@") > 0) return {
403
+ kind: "email",
404
+ email: trimmed
405
+ };
406
+ const orgHandle = trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
407
+ if (orgHandle.length > 0 && !orgHandle.toLowerCase().startsWith("0x") && ORG_HANDLE_SHAPE_PATTERN.test(orgHandle)) return {
408
+ kind: "orgHandle",
409
+ orgHandle
410
+ };
411
+ throw new Error("Recipient must be a Capxul email, @org-handle, or 0x address (escape hatch).");
577
412
  }
578
413
  function usdAmountToBaseUnits(value) {
579
414
  const amount = value.trim();
@@ -602,7 +437,20 @@ function canonicalConvexRunner(env = process.env) {
602
437
  //#endregion
603
438
  //#region src/commands/faucet-send.ts
604
439
  const DEFAULT_FAUCET_AMOUNT = "10";
605
- const FAUCET_FUNCTION = "dev/faucetMintTo:mintTo";
440
+ const FAUCET_ADDRESS_FUNCTION = "dev/faucetMintTo:mintTo";
441
+ const FAUCET_RECIPIENT_FUNCTION = "dev/faucetMintTo:mintToRecipient";
442
+ function recipientLabel(recipient) {
443
+ switch (recipient.kind) {
444
+ case "address": return recipient.address;
445
+ case "email": return recipient.email;
446
+ case "orgHandle": return `@${recipient.orgHandle}`;
447
+ }
448
+ }
449
+ function mintFailureMessage(recipient, output) {
450
+ const message = output.length > 0 ? output : "Faucet mint failed.";
451
+ if (recipient.kind === "orgHandle" && message.includes("INVALID_INPUT")) return [message, "Hint: personal payee handles are owner-scoped and cannot be funded by the faucet — use a Capxul email or an org handle."].join("\n");
452
+ return message;
453
+ }
606
454
  async function runFaucetSend() {
607
455
  intro("Capxul sandbox faucet send");
608
456
  note([
@@ -611,20 +459,21 @@ async function runFaucetSend() {
611
459
  "Asset: test USDX, 6 decimals",
612
460
  "This command calls the canonical backend dev faucet and cannot select live/mainnet."
613
461
  ].join("\n"), "Canonical sandbox");
614
- const addressPrompt = await text({
615
- message: "Recipient EVM address",
462
+ const recipientPrompt = await text({
463
+ message: "Recipient (Capxul email or @org-handle)",
616
464
  validate(value) {
617
465
  try {
618
- normalizeEvmAddress(value ?? "");
466
+ parseFaucetRecipient(value ?? "");
619
467
  } catch (error) {
620
468
  return errorMessage(error);
621
469
  }
622
470
  }
623
471
  });
624
- if (isCancel(addressPrompt)) {
472
+ if (isCancel(recipientPrompt)) {
625
473
  cancel("No faucet funds sent.");
626
474
  return 0;
627
475
  }
476
+ const recipient = parseFaucetRecipient(recipientPrompt);
628
477
  const amountPrompt = await text({
629
478
  message: "USDX amount",
630
479
  initialValue: DEFAULT_FAUCET_AMOUNT,
@@ -640,11 +489,21 @@ async function runFaucetSend() {
640
489
  cancel("No faucet funds sent.");
641
490
  return 0;
642
491
  }
643
- const holderAddress = normalizeEvmAddress(addressPrompt);
644
492
  const rawAmount = usdAmountToBaseUnits(amountPrompt);
645
493
  const displayAmount = amountPrompt.trim();
494
+ const identity = recipientLabel(recipient);
495
+ if (recipient.kind === "address") {
496
+ const escapeHatch = await confirm({
497
+ message: `Raw-address escape hatch — this skips Capxul identity resolution. Fund ${identity} directly?`,
498
+ initialValue: false
499
+ });
500
+ if (isCancel(escapeHatch) || escapeHatch === false) {
501
+ cancel("No faucet funds sent.");
502
+ return 0;
503
+ }
504
+ }
646
505
  const shouldSend = await confirm({
647
- message: `Mint ${displayAmount} test USDX to ${holderAddress}?`,
506
+ message: `Mint ${displayAmount} test USDX to ${identity}?`,
648
507
  initialValue: true
649
508
  });
650
509
  if (isCancel(shouldSend) || shouldSend === false) {
@@ -654,19 +513,29 @@ async function runFaucetSend() {
654
513
  const s = spinner();
655
514
  s.start("Minting testnet funds");
656
515
  try {
657
- const result = canonicalConvexRunner(loadOperatorEnv())("", [
516
+ const runConvex = canonicalConvexRunner(loadOperatorEnv());
517
+ const result = recipient.kind === "address" ? runConvex("", [
658
518
  "run",
659
- FAUCET_FUNCTION,
519
+ FAUCET_ADDRESS_FUNCTION,
660
520
  JSON.stringify({
661
- holderAddress,
521
+ holderAddress: recipient.address,
522
+ rawAmount
523
+ })
524
+ ]) : runConvex("", [
525
+ "run",
526
+ FAUCET_RECIPIENT_FUNCTION,
527
+ JSON.stringify({
528
+ recipient,
662
529
  rawAmount
663
530
  })
664
531
  ]);
665
- if (!result.ok) throw new Error(result.output || "Faucet mint failed.");
532
+ if (!result.ok) throw new Error(mintFailureMessage(recipient, result.output));
666
533
  const txHash = extractField(result.output, "txHash");
534
+ const safeAddress = recipient.kind === "address" ? recipient.address : extractField(result.output, "safeAddress");
667
535
  s.stop("Faucet funds sent");
668
536
  note([
669
- `Recipient: ${holderAddress}`,
537
+ `Recipient: ${identity}`,
538
+ `Safe address: ${safeAddress}`,
670
539
  `Amount: ${displayAmount} USDX`,
671
540
  `Raw amount: ${rawAmount}`,
672
541
  `Chain: Base Sepolia (84532)`,
@@ -680,30 +549,122 @@ async function runFaucetSend() {
680
549
  return 1;
681
550
  }
682
551
  }
552
+ /** Default developer origin when the caller passes no origin. */
553
+ const DEFAULT_ORIGIN = "http://localhost:3000";
554
+ /**
555
+ * Origins the shared sandbox deployment pre-trusts for email/OTP auth. Mirrors
556
+ * `QUICKSTART_ORIGINS` in `scripts/sync-convex-env.sh` (which unions these into
557
+ * the deployment's `CAPXUL_TRUSTED_ORIGINS`). A minted key scopes *bootstrap* to
558
+ * whatever origin you pass, but the deployment-level trusted-origin gate
559
+ * (`authFactory.buildTrustedOrigins`) rejects OTP/auth requests from origins
560
+ * outside this set — and a self-serve `npx` caller cannot change that env var.
561
+ * So an origin outside this set bootstraps but never completes sign-in. Keep in
562
+ * sync with `sync-convex-env.sh`.
563
+ */
564
+ const PRETRUSTED_QUICKSTART_ORIGINS = ["http://localhost:3000", "http://localhost:3100"];
565
+ function isPretrustedQuickstartOrigin(origin) {
566
+ return PRETRUSTED_QUICKSTART_ORIGINS.includes(origin);
567
+ }
568
+ const ENV_FILE_NAME = ".env.local";
569
+ const PUBLISHABLE_KEY_VAR = "NEXT_PUBLIC_CAPXUL_PUBLISHABLE_KEY";
570
+ const SITE_URL_VAR = "CAPXUL_SITE_URL";
571
+ function resolveOrigin(options) {
572
+ return options.origin ?? "http://localhost:3000";
573
+ }
574
+ function isMintResponse(value) {
575
+ if (typeof value !== "object" || value === null) return false;
576
+ const candidate = value;
577
+ return typeof candidate.publishableKey === "string" && typeof candidate.convexSiteUrl === "string" && typeof candidate.authBaseUrl === "string" && Array.isArray(candidate.allowedOrigins) && candidate.allowedOrigins.every((origin) => typeof origin === "string");
578
+ }
579
+ /**
580
+ * Upsert `key=value` into env-file text: replace the line if the key already
581
+ * exists (preserving every other line), otherwise append. Keeps a developer's
582
+ * existing `.env.local` intact rather than overwriting it.
583
+ */
584
+ function upsertEnvVar(contents, key, value) {
585
+ const line = `${key}=${value}`;
586
+ const lines = contents.length === 0 ? [] : contents.split("\n");
587
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
588
+ const pattern = new RegExp(`^${key}=`);
589
+ let replaced = false;
590
+ const next = lines.map((existing) => {
591
+ if (pattern.test(existing)) {
592
+ replaced = true;
593
+ return line;
594
+ }
595
+ return existing;
596
+ });
597
+ if (!replaced) next.push(line);
598
+ return `${next.join("\n")}\n`;
599
+ }
600
+ function rewriteSnippet() {
601
+ return [
602
+ "Add these rewrites to next.config.ts so browser requests stay same-origin:",
603
+ "",
604
+ " import type { NextConfig } from \"next\";",
605
+ " import { loadEnvConfig } from \"@next/env\";",
606
+ "",
607
+ " loadEnvConfig(process.cwd());",
608
+ "",
609
+ " const capxulSiteUrl = process.env.CAPXUL_SITE_URL;",
610
+ " if (!capxulSiteUrl) {",
611
+ " throw new Error(\"CAPXUL_SITE_URL is required\");",
612
+ " }",
613
+ "",
614
+ " const nextConfig: NextConfig = {",
615
+ " async rewrites() {",
616
+ " return [",
617
+ " {",
618
+ " source: \"/v1/client/bootstrap\",",
619
+ " destination: `${capxulSiteUrl}/v1/client/bootstrap`,",
620
+ " },",
621
+ " {",
622
+ " source: \"/api/auth/:path*\",",
623
+ " destination: `${capxulSiteUrl}/api/auth/:path*`,",
624
+ " },",
625
+ " ];",
626
+ " },",
627
+ " };",
628
+ "",
629
+ " export default nextConfig;"
630
+ ].join("\n");
631
+ }
632
+ async function runQuickstart(options, deps) {
633
+ const origin = resolveOrigin(options);
634
+ const endpoint = `${deps.baseUrl.replace(/\/$/, "")}/v1/client/mint-quickstart-key`;
635
+ deps.log(`Requesting a sandbox publishable key for ${origin} ...`);
636
+ const response = await deps.fetch(endpoint, {
637
+ method: "POST",
638
+ headers: { "content-type": "application/json" },
639
+ body: JSON.stringify({ origin })
640
+ });
641
+ if (!response.ok) {
642
+ const detail = await response.text().catch(() => "");
643
+ throw new Error(`Mint request failed (HTTP ${response.status})${detail ? `: ${detail}` : ""}`);
644
+ }
645
+ const payload = await response.json();
646
+ if (!isMintResponse(payload)) throw new Error("Mint response did not match the expected shape.");
647
+ let updated = upsertEnvVar(await deps.readEnvFile() ?? "", PUBLISHABLE_KEY_VAR, payload.publishableKey);
648
+ updated = upsertEnvVar(updated, SITE_URL_VAR, payload.convexSiteUrl);
649
+ await deps.writeEnvFile(updated);
650
+ deps.log(`Wrote ${PUBLISHABLE_KEY_VAR} and ${SITE_URL_VAR} to ${ENV_FILE_NAME}.`);
651
+ deps.log(`Key is scoped to: ${payload.allowedOrigins.join(", ")}`);
652
+ deps.log("");
653
+ deps.log(rewriteSnippet());
654
+ return payload;
655
+ }
683
656
  //#endregion
684
657
  //#region src/commands/key-create.ts
685
658
  async function runKeyCreate() {
686
659
  intro("Capxul sandbox key create");
687
660
  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({
661
+ "Mints a sandbox test publishable key from the public Capxul backend.",
662
+ "No secrets, no login — nothing to configure. The key is written to",
663
+ ".env.local in this directory (existing values are preserved)."
664
+ ].join("\n"), "Quickstart");
665
+ const originPrompt = await text({
705
666
  message: "Allowed local origin",
706
- initialValue: DEFAULT_ALLOWED_ORIGIN,
667
+ initialValue: DEFAULT_ORIGIN,
707
668
  validate(value) {
708
669
  try {
709
670
  normalizeHttpOrigin(value ?? "");
@@ -712,58 +673,44 @@ async function runKeyCreate() {
712
673
  }
713
674
  }
714
675
  });
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) {
676
+ if (isCancel(originPrompt)) {
738
677
  cancel("No key created.");
739
678
  return 0;
740
679
  }
680
+ const origin = normalizeHttpOrigin(originPrompt);
681
+ const baseUrl = process.env.CAPXUL_QUICKSTART_URL ?? "https://little-sandpiper-974.convex.site";
682
+ const envPath = resolve(process.cwd(), ".env.local");
741
683
  const s = spinner();
742
- s.start("Creating developer application and test publishable key");
684
+ s.start("Requesting a sandbox publishable key");
743
685
  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)
686
+ const result = await runQuickstart({ origin }, {
687
+ baseUrl,
688
+ fetch: globalThis.fetch,
689
+ readEnvFile: async () => {
690
+ try {
691
+ return await readFile(envPath, "utf8");
692
+ } catch {
693
+ return null;
694
+ }
695
+ },
696
+ writeEnvFile: (contents) => writeFile(envPath, contents, { mode: 384 }),
697
+ log: () => {}
756
698
  });
757
- s.stop("Publishable key captured in secure handoff");
699
+ s.stop("Publishable key written to .env.local");
758
700
  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");
701
+ "Wrote NEXT_PUBLIC_CAPXUL_PUBLISHABLE_KEY and CAPXUL_SITE_URL to .env.local",
702
+ "(any other lines were preserved).",
703
+ `Key is scoped to: ${result.allowedOrigins.join(", ")}`
704
+ ].join("\n"), "Written");
705
+ if (!isPretrustedQuickstartOrigin(origin)) note([
706
+ `The shared sandbox only completes email/OTP sign-in for its pre-trusted`,
707
+ `origins: ${PRETRUSTED_QUICKSTART_ORIGINS.join(", ")}.`,
708
+ ``,
709
+ `${origin} will bootstrap, but sign-in requests are rejected until Capxul`,
710
+ `adds it. For the self-serve quickstart, run your app on a pre-trusted`,
711
+ `origin (for example http://localhost:3000).`
712
+ ].join("\n"), "Origin not pre-trusted");
713
+ note(rewriteSnippet(), "Next steps");
767
714
  outro("Done.");
768
715
  return 0;
769
716
  } catch (error) {
@@ -784,7 +731,7 @@ const SANDBOX_COMMANDS = [{
784
731
  value: "faucet send",
785
732
  label: "Send testnet faucet funds",
786
733
  usage: "npx @capxul/sandbox faucet send",
787
- description: "Mint test USDX to an EVM address on Base Sepolia.",
734
+ description: "Mint test USDX to a Capxul identity (email or org handle) on Base Sepolia.",
788
735
  run: runFaucetSend
789
736
  }];
790
737
  const HELP_COMMANDS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/sandbox",
3
- "version": "1.0.0-alpha.1",
3
+ "version": "1.0.0-alpha.3",
4
4
  "private": false,
5
5
  "description": "Capxul sandbox CLI for canonical quickstart keys and testnet faucet funds.",
6
6
  "keywords": [