pontive 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +129 -3
  2. package/dist/cli.js +1225 -36
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,33 +1,22 @@
1
1
  #!/usr/bin/env node
2
+ import { randomBytes, generateKeyPairSync, randomUUID } from "node:crypto";
3
+ import { existsSync, readFileSync, writeFileSync, openSync, closeSync, statSync, unlinkSync, mkdirSync, renameSync } from "node:fs";
4
+ import { join, dirname, basename, resolve } from "node:path";
5
+ import { calculateJwkThumbprint, decodeProtectedHeader, compactDecrypt } from "jose";
6
+ import { spawnSync, spawn } from "node:child_process";
2
7
  import { parseArgs } from "node:util";
3
- import { resolve } from "node:path";
4
- import { spawn } from "node:child_process";
5
8
  import { createInterface } from "node:readline/promises";
6
- const AGENT_VARIABLES = [
7
- ["CLAUDECODE", "claude-code"],
8
- ["CURSOR_AGENT", "cursor"],
9
- ["CODEX_SANDBOX", "codex"],
10
- ["GEMINI_CLI", "gemini-cli"]
11
- ];
12
- function isSet(value) {
13
- return value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
14
- }
15
- function detectAgent(env) {
16
- for (const [variable, agent] of AGENT_VARIABLES) {
17
- if (isSet(env[variable])) return agent;
18
- }
19
- return void 0;
20
- }
21
- function isAgentMode(env, json) {
22
- return json || detectAgent(env) !== void 0 || isSet(env.CI);
23
- }
24
9
  const ExitCode = {
25
10
  /** Done. */
26
11
  Success: 0,
27
12
  /** Anything else that went wrong. */
28
13
  Error: 1,
29
14
  /** The user, or a missing `--yes` in agent mode, declined. */
30
- Cancelled: 2
15
+ Cancelled: 2,
16
+ /** Pontive rate limited the call; the JSON carries `retry_after` in seconds. */
17
+ RateLimited: 3,
18
+ /** The unclaimed instance expired or was claimed by someone else. */
19
+ ExpiredOrClaimedAway: 5
31
20
  };
32
21
  class CliError extends Error {
33
22
  code;
@@ -41,7 +30,1207 @@ class CliError extends Error {
41
30
  this.extra = extra;
42
31
  }
43
32
  }
44
- const modules = /* @__PURE__ */ Object.assign({});
33
+ function cancelled(message, extra = {}) {
34
+ return new CliError("cancelled", message, ExitCode.Cancelled, extra);
35
+ }
36
+ const DEFAULT_API_URL = "https://api.pontive.com";
37
+ function apiBaseUrl(env) {
38
+ return (env.PONTIVE_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
39
+ }
40
+ function retryAfterSeconds(header, now) {
41
+ if (!header) return void 0;
42
+ const trimmed = header.trim();
43
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
44
+ const at = Date.parse(trimmed);
45
+ if (Number.isNaN(at)) return void 0;
46
+ return Math.max(0, Math.ceil((at - now.getTime()) / 1e3));
47
+ }
48
+ async function errorOf(response) {
49
+ try {
50
+ const body = await response.json();
51
+ return {
52
+ code: typeof body.error?.code === "string" ? body.error.code : void 0,
53
+ message: typeof body.error?.message === "string" ? body.error.message : void 0
54
+ };
55
+ } catch {
56
+ return {};
57
+ }
58
+ }
59
+ const MAX_RETRY_WAIT_SECONDS = 30;
60
+ class PontiveApi {
61
+ constructor(options) {
62
+ this.options = options;
63
+ }
64
+ options;
65
+ /** Provisions an unclaimed development instance. Retried with the same idempotency key, so a retry never makes a second one. */
66
+ provision(body, idempotencyKey) {
67
+ return this.request("POST", "/v1/unclaimed-instances", {
68
+ body,
69
+ headers: { "x-idempotency-key": idempotencyKey }
70
+ });
71
+ }
72
+ getUnclaimed(instanceId, claimToken) {
73
+ return this.request("GET", `/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {
74
+ headers: { "x-pontive-claim-token": claimToken }
75
+ });
76
+ }
77
+ mintClaimLink(instanceId, claimToken) {
78
+ return this.request("POST", `/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {
79
+ headers: { "x-pontive-claim-token": claimToken }
80
+ });
81
+ }
82
+ async request(method, path, init) {
83
+ const { baseUrl, fetch: fetch2, sleep, now, signal, userAgent } = this.options;
84
+ const retries = this.options.retries ?? 3;
85
+ const url = `${baseUrl}${path}`;
86
+ for (let attempt = 0; ; attempt++) {
87
+ const backoff = 1e3 * 2 ** attempt;
88
+ let response;
89
+ try {
90
+ response = await fetch2(url, {
91
+ method,
92
+ headers: {
93
+ accept: "application/json",
94
+ "user-agent": userAgent,
95
+ ...init.body !== void 0 ? { "content-type": "application/json" } : {},
96
+ ...init.headers
97
+ },
98
+ body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
99
+ signal
100
+ });
101
+ } catch (error) {
102
+ if (signal?.aborted) throw error;
103
+ if (attempt < retries) {
104
+ await sleep(backoff, signal);
105
+ continue;
106
+ }
107
+ throw new CliError("network_error", `Could not reach ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
108
+ }
109
+ if (response.ok) return await response.json();
110
+ const retryAfter = retryAfterSeconds(response.headers.get("retry-after"), now());
111
+ if (response.status >= 500 && attempt < retries) {
112
+ const wait = retryAfter !== void 0 && retryAfter <= MAX_RETRY_WAIT_SECONDS ? retryAfter * 1e3 : backoff;
113
+ await response.body?.cancel();
114
+ await sleep(wait, signal);
115
+ continue;
116
+ }
117
+ throw await this.failure(response, retryAfter);
118
+ }
119
+ }
120
+ async failure(response, retryAfter) {
121
+ const { code: code2, message } = await errorOf(response);
122
+ const extra = retryAfter !== void 0 ? { retry_after: retryAfter } : {};
123
+ if (response.status === 429) {
124
+ return new CliError(
125
+ code2 ?? "rate_limited",
126
+ message ?? `Pontive rate limited the request${retryAfter !== void 0 ? `; retry in ${retryAfter}s` : ""}.`,
127
+ ExitCode.RateLimited,
128
+ { retry_after: retryAfter ?? 60 }
129
+ );
130
+ }
131
+ if (response.status === 401) {
132
+ return new CliError(
133
+ code2 ?? "unauthorized",
134
+ "Pontive refused the instance's credentials: the unclaimed instance expired or was claimed by someone else. Run pontive init --reset for a new one.",
135
+ ExitCode.ExpiredOrClaimedAway
136
+ );
137
+ }
138
+ if (response.status === 404 && (code2 === "unclaimed_instance_not_found" || code2 === void 0)) {
139
+ return new CliError(
140
+ "unclaimed_instance_not_found",
141
+ "Pontive no longer knows this unclaimed instance: it expired, or its claim token is no longer valid. Run pontive init --reset for a new one.",
142
+ ExitCode.ExpiredOrClaimedAway
143
+ );
144
+ }
145
+ return new CliError(
146
+ code2 ?? `http_${response.status}`,
147
+ message ?? `Pontive answered ${response.status} ${response.statusText}.`.replace(/ \./, "."),
148
+ ExitCode.Error,
149
+ extra
150
+ );
151
+ }
152
+ }
153
+ const ENV_FILE = ".env.local";
154
+ const PONTIVE_DIR = ".pontive";
155
+ const KEYLESS_FILE = join(PONTIVE_DIR, "keyless.json");
156
+ const LOCK_FILE = join(PONTIVE_DIR, "keyless.lock");
157
+ const CONTRACT_VARIABLES = [
158
+ "PONTIVE_ISSUER",
159
+ "PONTIVE_CLIENT_ID",
160
+ "PONTIVE_CLIENT_SECRET",
161
+ "PONTIVE_SESSION_SECRET",
162
+ "PONTIVE_SECRET_KEY",
163
+ "PONTIVE_INSTANCE_ID"
164
+ ];
165
+ function writeAtomic(path, contents) {
166
+ mkdirSync(dirname(path), { recursive: true });
167
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
168
+ writeFileSync(tmp, contents, { mode: 384 });
169
+ renameSync(tmp, path);
170
+ }
171
+ function ensurePontiveDir(cwd) {
172
+ const dir = join(cwd, PONTIVE_DIR);
173
+ mkdirSync(dir, { recursive: true, mode: 448 });
174
+ const ignore = join(dir, ".gitignore");
175
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
176
+ }
177
+ function readKeyless(cwd) {
178
+ const path = join(cwd, KEYLESS_FILE);
179
+ if (!existsSync(path)) return null;
180
+ let parsed;
181
+ try {
182
+ parsed = JSON.parse(readFileSync(path, "utf8"));
183
+ } catch {
184
+ throw new CliError("invalid_keyless_file", `${KEYLESS_FILE} is not valid JSON.`);
185
+ }
186
+ const k = parsed;
187
+ for (const field of ["instance_id", "issuer", "app_id", "expires_at", "region"]) {
188
+ if (typeof k?.[field] !== "string") throw new CliError("invalid_keyless_file", `${KEYLESS_FILE} has no ${field}.`);
189
+ }
190
+ return parsed;
191
+ }
192
+ function writeKeyless(cwd, keyless) {
193
+ ensurePontiveDir(cwd);
194
+ const ordered = {
195
+ instance_id: keyless.instance_id,
196
+ issuer: keyless.issuer,
197
+ app_id: keyless.app_id,
198
+ ...keyless.claim_token ? { claim_token: keyless.claim_token } : {},
199
+ expires_at: keyless.expires_at,
200
+ region: keyless.region
201
+ };
202
+ writeAtomic(join(cwd, KEYLESS_FILE), `${JSON.stringify(ordered, null, 2)}
203
+ `);
204
+ }
205
+ async function withKeylessLock(cwd, options, fn) {
206
+ ensurePontiveDir(cwd);
207
+ const path = join(cwd, LOCK_FILE);
208
+ const waitMs = options.waitMs ?? 3e4;
209
+ const staleMs = options.staleMs ?? 12e4;
210
+ const step = 250;
211
+ for (let waited = 0; ; waited += step) {
212
+ try {
213
+ const fd = openSync(path, "wx", 384);
214
+ writeFileSync(fd, `${JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString(), by: "pontive-cli" })}
215
+ `);
216
+ closeSync(fd);
217
+ break;
218
+ } catch (error) {
219
+ if (error.code !== "EEXIST") throw error;
220
+ try {
221
+ if (Date.now() - statSync(path).mtimeMs > staleMs) {
222
+ unlinkSync(path);
223
+ continue;
224
+ }
225
+ } catch {
226
+ continue;
227
+ }
228
+ if (waited >= waitMs) {
229
+ throw new CliError(
230
+ "keyless_locked",
231
+ `${LOCK_FILE} is held by another process (a dev server provisioning?). Try again shortly, or remove the file if nothing is running.`
232
+ );
233
+ }
234
+ await options.sleep(step, options.signal);
235
+ }
236
+ }
237
+ try {
238
+ return await fn();
239
+ } finally {
240
+ try {
241
+ unlinkSync(path);
242
+ } catch {
243
+ }
244
+ }
245
+ }
246
+ const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
247
+ function unquote(raw) {
248
+ const value = raw.trim();
249
+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) return value.slice(1, -1);
250
+ return value.replace(/\s+#.*$/, "");
251
+ }
252
+ function readEnvFile(cwd) {
253
+ const path = join(cwd, ENV_FILE);
254
+ const vars = /* @__PURE__ */ new Map();
255
+ if (!existsSync(path)) return vars;
256
+ for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
257
+ const match = ENV_LINE.exec(line);
258
+ if (match && !vars.has(match[1])) vars.set(match[1], unquote(match[2]));
259
+ }
260
+ return vars;
261
+ }
262
+ function formatValue(value) {
263
+ return /^[A-Za-z0-9_\-.:/+=@]*$/.test(value) ? value : JSON.stringify(value);
264
+ }
265
+ function writeEnv(cwd, entries, replace = /* @__PURE__ */ new Set()) {
266
+ const path = join(cwd, ENV_FILE);
267
+ const original = existsSync(path) ? readFileSync(path, "utf8") : "";
268
+ const lines = original === "" ? [] : original.replace(/\r?\n$/, "").split(/\r?\n/);
269
+ const result = { added: [], kept: [], replaced: [] };
270
+ const wanted = new Map(entries);
271
+ for (let i = 0; i < lines.length; i++) {
272
+ const match = ENV_LINE.exec(lines[i]);
273
+ if (!match || !wanted.has(match[1])) continue;
274
+ const name = match[1];
275
+ if (replace.has(name) && !result.replaced.includes(name)) {
276
+ lines[i] = `${name}=${formatValue(wanted.get(name))}`;
277
+ result.replaced.push(name);
278
+ } else if (!result.kept.includes(name) && !result.replaced.includes(name)) {
279
+ result.kept.push(name);
280
+ }
281
+ }
282
+ const missing = entries.filter(([name]) => !result.kept.includes(name) && !result.replaced.includes(name));
283
+ if (missing.length > 0) {
284
+ if (lines.length > 0 && lines.at(-1).trim() !== "") lines.push("");
285
+ lines.push("# Pontive: written by pontive init. See https://docs.pontive.com/unclaimed-instances");
286
+ for (const [name, value] of missing) {
287
+ lines.push(`${name}=${formatValue(value)}`);
288
+ result.added.push(name);
289
+ }
290
+ }
291
+ if (result.added.length > 0 || result.replaced.length > 0) writeAtomic(path, `${lines.join("\n")}
292
+ `);
293
+ return result;
294
+ }
295
+ function sessionSecret() {
296
+ return randomBytes(32).toString("base64url");
297
+ }
298
+ function patternMatches(pattern, path, isDir2) {
299
+ let p = pattern.trim();
300
+ if (p === "" || p.startsWith("#") || p.startsWith("!")) return false;
301
+ if (p.endsWith("/")) {
302
+ if (!isDir2) return false;
303
+ p = p.slice(0, -1);
304
+ }
305
+ p = p.replace(/^\//, "").replace(/^\*\*\//, "");
306
+ if (p.includes("/")) return false;
307
+ const regex = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")}$`);
308
+ return regex.test(path);
309
+ }
310
+ function ensureGitignore(cwd, entries) {
311
+ const path = join(cwd, ".gitignore");
312
+ const original = existsSync(path) ? readFileSync(path, "utf8") : "";
313
+ const patterns = original.split(/\r?\n/);
314
+ const added = [];
315
+ for (const entry of entries) {
316
+ const isDir2 = entry.endsWith("/");
317
+ const name = entry.replace(/\/$/, "");
318
+ const exact = (p) => [name, `/${name}`, `${name}/`, `/${name}/`].includes(p.trim());
319
+ if (patterns.some((p) => exact(p) || patternMatches(p, name, isDir2))) continue;
320
+ added.push(entry);
321
+ }
322
+ if (added.length > 0) {
323
+ const prefix = original === "" || original.endsWith("\n") ? original : `${original}
324
+ `;
325
+ writeFileSync(path, `${prefix}${prefix === "" ? "" : "\n"}# Pontive: secrets for local development
326
+ ${added.join("\n")}
327
+ `);
328
+ }
329
+ return added;
330
+ }
331
+ function apiFor(ctx) {
332
+ return new PontiveApi({
333
+ baseUrl: apiBaseUrl(ctx.env),
334
+ fetch: ctx.fetch,
335
+ sleep: ctx.sleep,
336
+ now: ctx.now,
337
+ signal: ctx.signal,
338
+ userAgent: `pontive-cli/${ctx.version}`
339
+ });
340
+ }
341
+ function isExpired(keyless, now) {
342
+ const at = Date.parse(keyless.expires_at);
343
+ return !Number.isNaN(at) && at <= now.getTime();
344
+ }
345
+ async function markClaimed(ctx) {
346
+ await withKeylessLock(ctx.cwd, { sleep: ctx.sleep, signal: ctx.signal }, async () => {
347
+ const current = readKeyless(ctx.cwd);
348
+ if (!current?.claim_token) return;
349
+ const { claim_token: _dead, ...rest } = current;
350
+ writeKeyless(ctx.cwd, rest);
351
+ });
352
+ }
353
+ function humanDate(iso) {
354
+ const at = new Date(iso);
355
+ if (Number.isNaN(at.getTime())) return iso;
356
+ return at.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
357
+ }
358
+ function box(lines) {
359
+ const width = Math.max(...lines.map((l) => l.length));
360
+ return [`┌${"─".repeat(width + 2)}┐`, ...lines.map((l) => `│ ${l.padEnd(width)} │`), `└${"─".repeat(width + 2)}┘`];
361
+ }
362
+ const POLL_INTERVAL_MS = 5e3;
363
+ const DEFAULT_TIMEOUT_SECONDS = 300;
364
+ function claimed(instanceId) {
365
+ return {
366
+ data: { instance_id: instanceId, status: "claimed" },
367
+ human: [`Instance ${instanceId} is claimed. Your keys keep working; nothing in your app changes.`]
368
+ };
369
+ }
370
+ function timeoutSeconds(ctx) {
371
+ const raw = ctx.values.timeout;
372
+ if (raw === void 0) return DEFAULT_TIMEOUT_SECONDS;
373
+ const n = Number(raw);
374
+ if (!Number.isInteger(n) || n < 0) throw new CliError("invalid_arguments", "--timeout must be a whole number of seconds.");
375
+ return n;
376
+ }
377
+ async function run$3(ctx) {
378
+ const timeout = timeoutSeconds(ctx);
379
+ const keyless = readKeyless(ctx.cwd);
380
+ if (!keyless) {
381
+ throw new CliError("no_unclaimed_instance", `No ${KEYLESS_FILE} here, so no unclaimed instance to claim. Run pontive init first.`);
382
+ }
383
+ if (!keyless.claim_token) return claimed(keyless.instance_id);
384
+ if (isExpired(keyless, ctx.now())) {
385
+ throw new CliError(
386
+ "instance_expired",
387
+ `The unclaimed instance ${keyless.instance_id} expired on ${humanDate(keyless.expires_at)}. Run pontive init --reset for a new one.`,
388
+ ExitCode.ExpiredOrClaimedAway,
389
+ { instance_id: keyless.instance_id }
390
+ );
391
+ }
392
+ const api = apiFor(ctx);
393
+ let link;
394
+ try {
395
+ link = await api.mintClaimLink(keyless.instance_id, keyless.claim_token);
396
+ } catch (error) {
397
+ if (error instanceof CliError && error.code === "instance_claimed") {
398
+ await markClaimed(ctx);
399
+ return claimed(keyless.instance_id);
400
+ }
401
+ throw error;
402
+ }
403
+ const opened = ctx.agentMode ? false : await ctx.openUrl(link.url);
404
+ ctx.out.info(
405
+ opened ? `Opened the claim page in your browser. If it did not open: ${link.url}` : `Open this link to claim the instance (valid until ${link.expires_at}, once):
406
+ ${link.url}`
407
+ );
408
+ const pending = (waited) => ({
409
+ data: {
410
+ instance_id: keyless.instance_id,
411
+ status: "unclaimed",
412
+ claim_url: link.url,
413
+ claim_url_expires_at: link.expires_at,
414
+ expires_at: keyless.expires_at,
415
+ waited_seconds: waited
416
+ },
417
+ human: [
418
+ `Not claimed yet. The link works until ${link.expires_at}: ${link.url}`,
419
+ "The instance keeps working meanwhile; run pontive status to check, or pontive claim for a new link."
420
+ ]
421
+ });
422
+ if (ctx.values["no-wait"] === true || timeout === 0) return pending(0);
423
+ ctx.out.info("Waiting for the claim…");
424
+ const started = ctx.now().getTime();
425
+ for (; ; ) {
426
+ const elapsed = ctx.now().getTime() - started;
427
+ if (elapsed >= timeout * 1e3) return pending(Math.round(elapsed / 1e3));
428
+ await ctx.sleep(Math.min(POLL_INTERVAL_MS, timeout * 1e3 - elapsed), ctx.signal);
429
+ const status = await api.getUnclaimed(keyless.instance_id, keyless.claim_token);
430
+ if (status.status === "claimed") {
431
+ await markClaimed(ctx);
432
+ return claimed(keyless.instance_id);
433
+ }
434
+ }
435
+ }
436
+ const command$2 = {
437
+ name: "claim",
438
+ summary: "Claim this app's unclaimed instance into your Pontive workspace",
439
+ help: `Mints a claim link (single use, valid for an hour), opens it in your browser
440
+ (prints it in agent mode or when there is no browser), and waits up to
441
+ 5 minutes for the claim. Once claimed, the claim token is removed from
442
+ ${KEYLESS_FILE}. The instance's keys keep working throughout.
443
+
444
+ Options:
445
+ --no-wait Print the link and return without waiting
446
+ --timeout <seconds> How long to wait for the claim (default ${DEFAULT_TIMEOUT_SECONDS})`,
447
+ options: {
448
+ "no-wait": { type: "boolean" },
449
+ timeout: { type: "string" }
450
+ },
451
+ run: run$3
452
+ };
453
+ const __vite_glob_0_0 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
454
+ __proto__: null,
455
+ command: command$2
456
+ }, Symbol.toStringTag, { value: "Module" }));
457
+ async function confirm(ctx, question) {
458
+ if (ctx.yes) return true;
459
+ if (ctx.agentMode || !ctx.interactive) return false;
460
+ return ctx.ask(question);
461
+ }
462
+ async function ephemeralKey() {
463
+ const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
464
+ const jwk = publicKey.export({ format: "jwk" });
465
+ const publicJwk = { kty: "EC", crv: "P-256", x: String(jwk.x), y: String(jwk.y) };
466
+ return { publicJwk, privateKey, thumbprint: await calculateJwkThumbprint(publicJwk, "sha256") };
467
+ }
468
+ function invalid(message) {
469
+ return new CliError("invalid_encrypted_secrets", message);
470
+ }
471
+ async function decryptSecrets(jwe, key) {
472
+ let header;
473
+ try {
474
+ header = decodeProtectedHeader(jwe);
475
+ } catch {
476
+ throw invalid("Pontive answered encrypted_secrets that is not a compact JWE.");
477
+ }
478
+ if (header.alg !== "ECDH-ES" || header.enc !== "A256GCM") {
479
+ throw invalid(`encrypted_secrets uses ${String(header.alg)}/${String(header.enc)}; expected ECDH-ES/A256GCM.`);
480
+ }
481
+ if (header.kid !== void 0 && header.kid !== key.thumbprint) {
482
+ throw invalid("encrypted_secrets was sealed to another key.");
483
+ }
484
+ let plaintext;
485
+ try {
486
+ ({ plaintext } = await compactDecrypt(jwe, key.privateKey, {
487
+ keyManagementAlgorithms: ["ECDH-ES"],
488
+ contentEncryptionAlgorithms: ["A256GCM"]
489
+ }));
490
+ } catch {
491
+ throw invalid("encrypted_secrets could not be decrypted.");
492
+ }
493
+ let secrets;
494
+ try {
495
+ secrets = JSON.parse(new TextDecoder().decode(plaintext));
496
+ } catch {
497
+ throw invalid("encrypted_secrets does not hold a JSON object.");
498
+ }
499
+ const s = secrets;
500
+ if (typeof s !== "object" || s === null || typeof s.secret_key !== "string" || typeof s.claim_token !== "string") {
501
+ throw invalid("encrypted_secrets is missing secret_key or claim_token.");
502
+ }
503
+ if (s.client_secret !== void 0 && s.client_secret !== null && typeof s.client_secret !== "string") {
504
+ throw invalid("encrypted_secrets carries a client_secret that is not a string.");
505
+ }
506
+ return {
507
+ secret_key: s.secret_key,
508
+ claim_token: s.claim_token,
509
+ ...typeof s.client_secret === "string" ? { client_secret: s.client_secret } : {}
510
+ };
511
+ }
512
+ async function loadLogin(_env) {
513
+ return null;
514
+ }
515
+ const FRAMEWORKS = ["nextjs", "vite-react", "express", "node"];
516
+ function readJson(path) {
517
+ try {
518
+ return JSON.parse(readFileSync(path, "utf8"));
519
+ } catch {
520
+ return void 0;
521
+ }
522
+ }
523
+ function isDir(path) {
524
+ try {
525
+ return statSync(path).isDirectory();
526
+ } catch {
527
+ return false;
528
+ }
529
+ }
530
+ function hasDependency(pkg, name) {
531
+ return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
532
+ }
533
+ const LOCKFILES = [
534
+ ["pnpm-lock.yaml", "pnpm"],
535
+ ["bun.lock", "bun"],
536
+ ["bun.lockb", "bun"],
537
+ ["yarn.lock", "yarn"],
538
+ ["package-lock.json", "npm"]
539
+ ];
540
+ function detectPackageManager(cwd, pkg) {
541
+ for (let dir = cwd; ; dir = dirname(dir)) {
542
+ for (const [file, pm] of LOCKFILES) {
543
+ if (existsSync(join(dir, file))) return pm;
544
+ }
545
+ if (dirname(dir) === dir) break;
546
+ }
547
+ const declared = pkg.packageManager?.split("@")[0];
548
+ if (declared === "pnpm" || declared === "yarn" || declared === "bun" || declared === "npm") return declared;
549
+ return "npm";
550
+ }
551
+ function detectFramework(pkg) {
552
+ if (hasDependency(pkg, "next")) return "nextjs";
553
+ if (hasDependency(pkg, "vite") && hasDependency(pkg, "react")) return "vite-react";
554
+ if (hasDependency(pkg, "express")) return "express";
555
+ return "node";
556
+ }
557
+ function nextMajor(cwd, pkg) {
558
+ const installed = readJson(join(cwd, "node_modules", "next", "package.json"))?.version;
559
+ const declared = pkg.dependencies?.next ?? pkg.devDependencies?.next;
560
+ const match = /(\d+)/.exec(installed ?? declared ?? "");
561
+ return match ? Number(match[1]) : void 0;
562
+ }
563
+ function detectProject(cwd, framework) {
564
+ const pkg = readJson(join(cwd, "package.json"));
565
+ if (!pkg) {
566
+ throw new CliError("no_package_json", `No package.json in ${cwd}. Run pontive init in your app's directory, or create one with npm init.`);
567
+ }
568
+ const fw = framework ?? detectFramework(pkg);
569
+ const srcDir = fw === "nextjs" ? isDir(join(cwd, "src", "app")) || isDir(join(cwd, "src")) && !isDir(join(cwd, "app")) : isDir(join(cwd, "src"));
570
+ return {
571
+ cwd,
572
+ framework: fw,
573
+ packageManager: detectPackageManager(cwd, pkg),
574
+ packageJson: pkg,
575
+ typescript: existsSync(join(cwd, "tsconfig.json")),
576
+ esm: pkg.type === "module",
577
+ srcDir,
578
+ ...fw === "nextjs" ? { nextMajor: nextMajor(cwd, pkg) } : {}
579
+ };
580
+ }
581
+ function installCommand(pm, packages) {
582
+ return pm === "npm" ? ["npm", ["install", ...packages]] : [pm, ["add", ...packages]];
583
+ }
584
+ function isInstalled(project, name) {
585
+ return hasDependency(project.packageJson, name);
586
+ }
587
+ function projectName(project) {
588
+ const raw = (project.packageJson.name ?? basename(project.cwd)).replace(/^@[^/]+\//, "");
589
+ const words = raw.split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1));
590
+ const name = words.join(" ").slice(0, 100).trim();
591
+ return name === "" ? "Untitled app" : name;
592
+ }
593
+ const MCP_AGENTS = ["claude-code", "cursor", "gemini-cli", "codex"];
594
+ const TARGETS = {
595
+ "claude-code": {
596
+ file: ".mcp.json",
597
+ entry: (url, key) => ({ type: "http", url, headers: { Authorization: `Bearer ${key}` } })
598
+ },
599
+ cursor: {
600
+ file: join(".cursor", "mcp.json"),
601
+ entry: (url, key) => ({ url, headers: { Authorization: `Bearer ${key}` } })
602
+ },
603
+ "gemini-cli": {
604
+ file: join(".gemini", "settings.json"),
605
+ entry: (url, key) => ({ httpUrl: url, headers: { Authorization: `Bearer ${key}` } })
606
+ }
607
+ };
608
+ function mcpUrl(apiUrl, region, env) {
609
+ if (env.PONTIVE_MCP_URL) return env.PONTIVE_MCP_URL;
610
+ let base = "pontive.com";
611
+ try {
612
+ const host = new URL(apiUrl).hostname;
613
+ if (host.startsWith("api.")) base = host.slice("api.".length);
614
+ } catch {
615
+ }
616
+ return `https://mcp.${region}.${base}/mcp`;
617
+ }
618
+ function agentFromProject(cwd) {
619
+ if (existsSync(join(cwd, ".mcp.json")) || existsSync(join(cwd, ".claude")) || existsSync(join(cwd, "CLAUDE.md"))) return "claude-code";
620
+ if (existsSync(join(cwd, ".cursor"))) return "cursor";
621
+ if (existsSync(join(cwd, ".gemini")) || existsSync(join(cwd, "GEMINI.md"))) return "gemini-cli";
622
+ return void 0;
623
+ }
624
+ function isMcpAgent(agent) {
625
+ return MCP_AGENTS.includes(agent ?? "");
626
+ }
627
+ function mcpConfigFile(agent) {
628
+ return TARGETS[agent]?.file;
629
+ }
630
+ function mcpManualStep(agent, url) {
631
+ if (agent === "codex") {
632
+ return `Add to ~/.codex/config.toml: [mcp_servers.pontive] url = "${url}" bearer_token_env_var = "PONTIVE_SECRET_KEY", with PONTIVE_SECRET_KEY from .env.local exported.`;
633
+ }
634
+ return `Connect the Pontive MCP server at ${url} with the header Authorization: Bearer <PONTIVE_SECRET_KEY from .env.local>.`;
635
+ }
636
+ function tracked(cwd, file) {
637
+ const result = spawnSync("git", ["ls-files", "--error-unmatch", file], { cwd, stdio: "ignore" });
638
+ return result.status === 0;
639
+ }
640
+ function writeMcpConfig(cwd, agent, url, secretKey) {
641
+ const target = TARGETS[agent];
642
+ const manual = mcpManualStep(agent, url);
643
+ if (!target) return { written: false, agent, url, reason: "no project-level config for this agent", manual };
644
+ const path = join(cwd, target.file);
645
+ if (tracked(cwd, target.file)) {
646
+ return { written: false, agent, file: target.file, url, reason: `${target.file} is tracked by git, and a secret key must not be committed`, manual };
647
+ }
648
+ let config = {};
649
+ if (existsSync(path)) {
650
+ try {
651
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
652
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error();
653
+ config = parsed;
654
+ } catch {
655
+ return { written: false, agent, file: target.file, url, reason: `${target.file} is not a JSON object`, manual };
656
+ }
657
+ }
658
+ const servers = typeof config.mcpServers === "object" && config.mcpServers !== null ? config.mcpServers : {};
659
+ config.mcpServers = { ...servers, pontive: target.entry(url, secretKey) };
660
+ mkdirSync(dirname(path), { recursive: true });
661
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}
662
+ `, { mode: 384 });
663
+ return { written: true, agent, file: target.file, url, gitignore: ensureGitignore(cwd, [target.file.split("\\").join("/")]) };
664
+ }
665
+ const HEADER = "Written by `pontive init`. The values come from .env.local, the PONTIVE_* variables.";
666
+ function nextjs(project) {
667
+ const ts = project.typescript;
668
+ const ext = ts ? "ts" : "js";
669
+ const base = project.srcDir ? "src/" : "";
670
+ const bang = ts ? "!" : "";
671
+ const proxyFile = (project.nextMajor ?? 0) >= 16;
672
+ const middlewareName = proxyFile ? "proxy" : "middleware";
673
+ const middlewarePath = `${base}${middlewareName}.${ext}`;
674
+ const lib = `import { pontiveAuth } from "@pontive/pontkit-nextjs/server";
675
+
676
+ // ${HEADER}
677
+ export const pontive = pontiveAuth({
678
+ issuer: process.env.PONTIVE_ISSUER${bang},
679
+ clientId: process.env.PONTIVE_CLIENT_ID${bang},
680
+ clientSecret: process.env.PONTIVE_CLIENT_SECRET,
681
+ sessionSecret: process.env.PONTIVE_SESSION_SECRET,
682
+ });
683
+ `;
684
+ const route = `// Pontive's sign-in routes: /api/auth/login, /api/auth/callback, /api/auth/logout.
685
+ import { pontive } from "../../../../lib/pontive";
686
+
687
+ export const { GET, POST } = pontive.handlers;
688
+ `;
689
+ const middleware = `${ts ? 'import type { NextRequest } from "next/server";\n' : ""}import { pontive } from "./lib/pontive";
690
+
691
+ // Keeps the Pontive session current before anything renders. Read it anywhere
692
+ // on the server with \`await pontive.auth()\`.
693
+ export function ${middlewareName}(req${ts ? ": NextRequest" : ""}) {
694
+ return pontive.middleware(req);
695
+ }
696
+
697
+ export const config = {
698
+ matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
699
+ };
700
+ `;
701
+ const otherMiddleware = ["middleware", "proxy"].flatMap((n) => [`${base}${n}.ts`, `${base}${n}.js`]);
702
+ return {
703
+ packages: ["@pontive/pontkit-nextjs"],
704
+ appType: "web",
705
+ files: [
706
+ { path: `${base}lib/pontive.${ext}`, contents: lib },
707
+ { path: `${base}app/api/auth/[...pontive]/route.${ext}`, contents: route },
708
+ {
709
+ path: middlewarePath,
710
+ contents: middleware,
711
+ unlessExists: otherMiddleware,
712
+ manual: `Your ${middlewareName} file already exists: return pontive.middleware(req) from it (import { pontive } from "./lib/pontive").`
713
+ }
714
+ ],
715
+ nextSteps: [
716
+ "Sign in at /api/auth/login and out at /api/auth/logout.",
717
+ "Read the session on the server with await pontive.auth()."
718
+ ]
719
+ };
720
+ }
721
+ function viteReact(project) {
722
+ const ts = project.typescript;
723
+ const base = project.srcDir ? "src/" : "";
724
+ const provider = `${ts ? 'import type { ReactNode } from "react";\n' : ""}import { Provider } from "@pontive/pontkit-react";
725
+
726
+ // ${HEADER}
727
+ // The browser reaches the auth server through the dev server's /__pontive
728
+ // proxy (vite.pontive.${ts ? "ts" : "js"}). Wrap the app: <PontiveProvider><App /></PontiveProvider>
729
+ export function PontiveProvider({ children }${ts ? ": { children: ReactNode }" : ""}) {
730
+ return (
731
+ <Provider domain="/__pontive" appId={import.meta.env.PONTIVE_CLIENT_ID}>
732
+ {children}
733
+ </Provider>
734
+ );
735
+ }
736
+ `;
737
+ const plugin = `import { loadEnv${ts ? ", type Plugin" : ""} } from "vite";
738
+ import { viteAuthProxy } from "@pontive/pontkit-loader/proxy";
739
+
740
+ // ${HEADER}
741
+ // Add it to vite.config: plugins: [react(), pontive()]. It proxies /__pontive
742
+ // to the instance's auth server and gives the browser the app's client id,
743
+ // and no other variable, from .env.local. In production, proxy /__pontive on
744
+ // your host instead (pontkit docs/auth-proxy.md).
745
+ export function pontive()${ts ? ": Plugin" : ""} {
746
+ return {
747
+ name: "pontive",
748
+ config(_config, { mode }) {
749
+ const env = loadEnv(mode, process.cwd(), "PONTIVE_");
750
+ return {
751
+ ...(env.PONTIVE_ISSUER ? { server: { proxy: viteAuthProxy({ authHost: env.PONTIVE_ISSUER }) } } : {}),
752
+ define: { "import.meta.env.PONTIVE_CLIENT_ID": JSON.stringify(env.PONTIVE_CLIENT_ID ?? "") },
753
+ };
754
+ },
755
+ };
756
+ }
757
+ `;
758
+ return {
759
+ packages: ["@pontive/pontkit-react", "@pontive/pontkit-loader"],
760
+ appType: "spa",
761
+ redirectUris: ["http://localhost/", "http://127.0.0.1/"],
762
+ files: [
763
+ { path: `${base}pontive.${ts ? "tsx" : "jsx"}`, contents: provider },
764
+ { path: `vite.pontive.${ts ? "ts" : "js"}`, contents: plugin }
765
+ ],
766
+ nextSteps: [
767
+ 'Add the plugin to vite.config: import { pontive } from "./vite.pontive"; plugins: [react(), pontive()].',
768
+ `Wrap the app in <PontiveProvider> from ./${base}pontive in your entry file.`
769
+ ]
770
+ };
771
+ }
772
+ function nodeModule(ts, esm) {
773
+ const t = (typed, plain = "") => ts ? typed : plain;
774
+ const exp = esm ? "export " : "";
775
+ const imports = esm ? `import { createServerAuth${t(", type Session")} } from "@pontive/pontkit-server";
776
+ ${t('import type { IncomingMessage, ServerResponse } from "node:http";\n')}` : `const { createServerAuth } = require("@pontive/pontkit-server");
777
+ `;
778
+ const body = `${imports}
779
+ // ${HEADER}
780
+ // Node 20.12 and later load .env.local here; earlier, start with
781
+ // node --env-file=.env.local.
782
+ try {
783
+ ${t("(process as unknown as { loadEnvFile?: (path: string) => void })", "process")}.loadEnvFile?.(".env.local");
784
+ } catch {
785
+ // No .env.local: the variables come from the environment.
786
+ }
787
+
788
+ ${exp}const pontive = createServerAuth({
789
+ issuer: process.env.PONTIVE_ISSUER${t("!")},
790
+ clientId: process.env.PONTIVE_CLIENT_ID${t("!")},
791
+ clientSecret: process.env.PONTIVE_CLIENT_SECRET,
792
+ sessionSecret: process.env.PONTIVE_SESSION_SECRET,
793
+ });
794
+ ${t("\ntype Next = (error?: unknown) => void;\n")}
795
+ function toRequest(req${t(": IncomingMessage")})${t(": Request")} {
796
+ const headers = new Headers();
797
+ for (const [name, value] of Object.entries(req.headers)) {
798
+ for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(name, v);
799
+ }
800
+ return new Request(new URL(req.url ?? "/", \`http://\${req.headers.host ?? "localhost"}\`), { method: req.method, headers });
801
+ }
802
+
803
+ async function send(res${t(": ServerResponse")}, response${t(": Response")})${t(": Promise<void>")} {
804
+ res.statusCode = response.status;
805
+ response.headers.forEach((value, name) => {
806
+ if (name !== "set-cookie") res.setHeader(name, value);
807
+ });
808
+ const cookies = response.headers.getSetCookie();
809
+ if (cookies.length > 0) res.setHeader("set-cookie", cookies);
810
+ res.end(Buffer.from(await response.arrayBuffer()));
811
+ }
812
+
813
+ /** Answers Pontive's sign-in routes: /api/auth/login, /api/auth/callback, /api/auth/logout. True when it did. */
814
+ ${exp}async function handlePontive(req${t(": IncomingMessage")}, res${t(": ServerResponse")})${t(": Promise<boolean>")} {
815
+ const response = await pontive.handle(toRequest(req));
816
+ if (!response) return false;
817
+ await send(res, response);
818
+ return true;
819
+ }
820
+
821
+ /** Express: app.use(pontiveRoutes) serves the sign-in routes. */
822
+ ${exp}function pontiveRoutes(req${t(": IncomingMessage")}, res${t(": ServerResponse")}, next${t(": Next")})${t(": void")} {
823
+ handlePontive(req, res).then((handled) => {
824
+ if (!handled) next();
825
+ }, next);
826
+ }
827
+
828
+ /** Express: app.use(pontiveSession) refreshes the session ahead of your routes and sets req.pontiveSession (null when signed out). */
829
+ ${exp}function pontiveSession(req${t(": IncomingMessage & { pontiveSession?: Session | null }")}, res${t(": ServerResponse")}, next${t(": Next")})${t(": void")} {
830
+ pontive.refresh(toRequest(req)).then((outcome) => {
831
+ for (const cookie of outcome.setCookies) res.appendHeader("set-cookie", cookie);
832
+ req.headers.cookie = outcome.cookieHeader;
833
+ req.pontiveSession = outcome.session;
834
+ next();
835
+ }, next);
836
+ }
837
+ ${esm ? "" : "\nmodule.exports = { pontive, handlePontive, pontiveRoutes, pontiveSession };\n"}`;
838
+ return body;
839
+ }
840
+ function node(project, express) {
841
+ const ts = project.typescript;
842
+ const esm = ts || project.esm;
843
+ const base = project.srcDir ? "src/" : "";
844
+ const path = `${base}pontive.${ts ? "ts" : "js"}`;
845
+ const importLine = esm ? `import { ${express ? "pontiveRoutes, pontiveSession" : "handlePontive, pontive"} } from "./pontive${ts ? "" : ".js"}"` : `const { ${express ? "pontiveRoutes, pontiveSession" : "handlePontive, pontive"} } = require("./pontive")`;
846
+ return {
847
+ packages: ["@pontive/pontkit-server"],
848
+ appType: "web",
849
+ files: [{ path, contents: nodeModule(ts, esm) }],
850
+ nextSteps: express ? [
851
+ `In your server: ${importLine}; then app.use(pontiveRoutes) and app.use(pontiveSession) before your routes.`,
852
+ "Sign in at /api/auth/login; req.pontiveSession is the signed-in session or null."
853
+ ] : [
854
+ `In your server: ${importLine}; start each request with if (await handlePontive(req, res)) return;`,
855
+ "Read the session with await pontive.getSession(req.headers.cookie). Sign in at /api/auth/login."
856
+ ]
857
+ };
858
+ }
859
+ function scaffoldPlan(project) {
860
+ switch (project.framework) {
861
+ case "nextjs":
862
+ return nextjs(project);
863
+ case "vite-react":
864
+ return viteReact(project);
865
+ case "express":
866
+ return node(project, true);
867
+ case "node":
868
+ return node(project, false);
869
+ }
870
+ }
871
+ function writeScaffold(cwd, files) {
872
+ const result = { written: [], skipped: [] };
873
+ for (const file of files) {
874
+ const target = join(cwd, file.path);
875
+ const blocker = [file.path, ...file.unlessExists ?? []].find((p) => existsSync(join(cwd, p)));
876
+ if (blocker) {
877
+ result.skipped.push({ path: file.path, reason: `${blocker} exists`, ...file.manual ? { manual: file.manual } : {} });
878
+ continue;
879
+ }
880
+ mkdirSync(dirname(target), { recursive: true });
881
+ writeFileSync(target, file.contents);
882
+ result.written.push(file.path);
883
+ }
884
+ return result;
885
+ }
886
+ function option(ctx, name) {
887
+ const value = ctx.values[name];
888
+ return typeof value === "string" && value !== "" ? value : void 0;
889
+ }
890
+ function frameworkOption(ctx) {
891
+ const value = option(ctx, "framework");
892
+ if (value === void 0) return void 0;
893
+ if (!FRAMEWORKS.includes(value)) {
894
+ throw new CliError("invalid_arguments", `--framework must be one of ${FRAMEWORKS.join(", ")}.`);
895
+ }
896
+ return value;
897
+ }
898
+ function tenancyOption(ctx) {
899
+ const value = option(ctx, "tenancy-mode");
900
+ if (value === void 0) return void 0;
901
+ if (value !== "b2b" && value !== "b2c") throw new CliError("invalid_arguments", "--tenancy-mode must be b2b or b2c.");
902
+ return value;
903
+ }
904
+ function regionOfKey(secretKey) {
905
+ return secretKey ? /^pontive_sk_[a-z]+_([a-z0-9]+)_/.exec(secretKey)?.[1] : void 0;
906
+ }
907
+ async function install(ctx, project, plan) {
908
+ const missing = plan.packages.filter((p) => !isInstalled(project, p));
909
+ if (missing.length === 0 || ctx.values["skip-install"] === true) return [];
910
+ const [command2, args] = installCommand(project.packageManager, missing);
911
+ ctx.out.info(`Installing ${missing.join(", ")} with ${project.packageManager}…`);
912
+ const code2 = await ctx.exec(command2, args, { cwd: ctx.cwd });
913
+ if (code2 !== 0) {
914
+ throw new CliError("install_failed", `${command2} ${args.join(" ")} failed (exit ${code2}). Install it yourself and run pontive init --skip-install.`);
915
+ }
916
+ return missing;
917
+ }
918
+ async function provision(ctx, project, plan) {
919
+ const key = await ephemeralKey();
920
+ const region = option(ctx, "region") ?? ctx.env.PONTIVE_REGION;
921
+ const tenancy = tenancyOption(ctx);
922
+ const body = {
923
+ name: option(ctx, "name") ?? projectName(project),
924
+ ...region ? { region } : {},
925
+ ...tenancy ? { tenancy_mode: tenancy } : {},
926
+ app: { type: plan.appType, ...plan.redirectUris ? { redirect_uris: plan.redirectUris } : {} },
927
+ encryption_key: key.publicJwk,
928
+ client: { name: "pontive-cli", version: ctx.version, ...ctx.agent ? { agent: ctx.agent } : {} }
929
+ };
930
+ ctx.out.info("Creating an unclaimed development instance…");
931
+ const response = await apiFor(ctx).provision(body, randomUUID());
932
+ let secrets;
933
+ if (response.encrypted_secrets) {
934
+ secrets = await decryptSecrets(response.encrypted_secrets, key);
935
+ } else if (response.secret_key && response.claim_token) {
936
+ secrets = { secret_key: response.secret_key, claim_token: response.claim_token, ...response.client_secret ? { client_secret: response.client_secret } : {} };
937
+ } else {
938
+ throw new CliError("invalid_response", "Pontive answered without the instance's secrets.");
939
+ }
940
+ if (plan.appType === "web" && !secrets.client_secret) {
941
+ throw new CliError("invalid_response", "Pontive answered a web app without its client secret.");
942
+ }
943
+ return { response, secrets };
944
+ }
945
+ const REPLACED_ON_RESET = /* @__PURE__ */ new Set(["PONTIVE_ISSUER", "PONTIVE_CLIENT_ID", "PONTIVE_CLIENT_SECRET", "PONTIVE_SECRET_KEY", "PONTIVE_INSTANCE_ID"]);
946
+ function envEntries(response, secrets) {
947
+ return [
948
+ ["PONTIVE_ISSUER", response.issuer],
949
+ ["PONTIVE_CLIENT_ID", response.app_id],
950
+ ...secrets.client_secret ? [["PONTIVE_CLIENT_SECRET", secrets.client_secret]] : [],
951
+ ...secrets.client_secret ? [["PONTIVE_SESSION_SECRET", sessionSecret()]] : [],
952
+ ["PONTIVE_SECRET_KEY", secrets.secret_key],
953
+ ["PONTIVE_INSTANCE_ID", response.instance_id]
954
+ ];
955
+ }
956
+ async function connectMcp(ctx, secretKey, region, nextSteps) {
957
+ if (ctx.values["no-mcp"] === true || !secretKey || !region) return null;
958
+ const requested = option(ctx, "mcp");
959
+ if (requested !== void 0 && !isMcpAgent(requested)) {
960
+ throw new CliError("invalid_arguments", `--mcp must be one of ${MCP_AGENTS.join(", ")}.`);
961
+ }
962
+ const agent = requested ?? (isMcpAgent(ctx.agent) ? ctx.agent : agentFromProject(ctx.cwd));
963
+ if (!agent) return null;
964
+ const url = mcpUrl(apiBaseUrl(ctx.env), region, ctx.env);
965
+ const file = mcpConfigFile(agent);
966
+ if (!file) {
967
+ nextSteps.push(mcpManualStep(agent, url));
968
+ return { agent, written: false, url, reason: "no project-level config for this agent" };
969
+ }
970
+ const consent = ctx.yes || !ctx.agentMode && requested !== void 0 || await confirm(ctx, `Connect ${agent} to Pontive's MCP server, writing the secret key to ${file} (gitignored)?`);
971
+ if (!consent) {
972
+ nextSteps.push(ctx.agentMode ? `Run pontive init --yes to write the Pontive MCP server to ${file}.` : mcpManualStep(agent, url));
973
+ return { agent, written: false, file, url, reason: ctx.agentMode ? "needs --yes" : "declined" };
974
+ }
975
+ const result = writeMcpConfig(ctx.cwd, agent, url, secretKey);
976
+ if (!result.written) {
977
+ nextSteps.push(result.manual);
978
+ return { agent, written: false, file: result.file, url, reason: result.reason };
979
+ }
980
+ nextSteps.push(`Restart ${agent} to load the Pontive MCP server from ${file}.`);
981
+ return { agent, written: true, file, url };
982
+ }
983
+ async function run$2(ctx) {
984
+ const reset = ctx.values.reset === true;
985
+ const project = detectProject(ctx.cwd, frameworkOption(ctx));
986
+ const plan = scaffoldPlan(project);
987
+ const nextSteps = [...plan.nextSteps];
988
+ if (reset && !await confirm(ctx, "Provision a new unclaimed instance and point .env.local at it? The current instance is left to expire.")) {
989
+ throw cancelled(ctx.agentMode ? "init --reset provisions a new instance; pass --yes to confirm." : "Cancelled.");
990
+ }
991
+ const existing = readKeyless(ctx.cwd);
992
+ if (!reset && existing?.claim_token && isExpired(existing, ctx.now())) {
993
+ throw new CliError(
994
+ "instance_expired",
995
+ `The unclaimed instance ${existing.instance_id} expired on ${humanDate(existing.expires_at)}, with its users. Run pontive init --reset for a new one.`,
996
+ ExitCode.ExpiredOrClaimedAway,
997
+ { instance_id: existing.instance_id }
998
+ );
999
+ }
1000
+ const installed = await install(ctx, project, plan);
1001
+ const files = writeScaffold(ctx.cwd, plan.files);
1002
+ for (const skipped of files.skipped) if (skipped.manual) nextSteps.push(skipped.manual);
1003
+ const gitignore = ensureGitignore(ctx.cwd, [ENV_FILE, `${PONTIVE_DIR}/`]);
1004
+ const envFile = readEnvFile(ctx.cwd);
1005
+ const configuredIssuer = envFile.get("PONTIVE_ISSUER") || ctx.env.PONTIVE_ISSUER;
1006
+ let instance;
1007
+ let env = { added: [], kept: [], replaced: [] };
1008
+ let secretKey = envFile.get("PONTIVE_SECRET_KEY") || ctx.env.PONTIVE_SECRET_KEY;
1009
+ if (!reset && existing) {
1010
+ instance = {
1011
+ status: "reused",
1012
+ instance_id: existing.instance_id,
1013
+ region: existing.region,
1014
+ issuer: existing.issuer,
1015
+ app_id: existing.app_id,
1016
+ ...existing.claim_token ? { expires_at: existing.expires_at } : { claimed: true }
1017
+ };
1018
+ } else if (!reset && configuredIssuer) {
1019
+ instance = { status: "configured", issuer: configuredIssuer, ...envFile.get("PONTIVE_INSTANCE_ID") ? { instance_id: envFile.get("PONTIVE_INSTANCE_ID") } : {}, region: regionOfKey(secretKey) };
1020
+ } else {
1021
+ const login = await loadLogin(ctx.env);
1022
+ if (login) throw new CliError("not_supported", "Signed-in init is not supported by this version of the CLI.");
1023
+ const provisioned = await withKeylessLock(ctx.cwd, { sleep: ctx.sleep, signal: ctx.signal }, async () => {
1024
+ const raced = reset ? null : readKeyless(ctx.cwd);
1025
+ if (raced) return { kind: "raced", keyless: raced };
1026
+ const { response, secrets } = await provision(ctx, project, plan);
1027
+ const keyless = {
1028
+ instance_id: response.instance_id,
1029
+ issuer: response.issuer,
1030
+ app_id: response.app_id,
1031
+ claim_token: secrets.claim_token,
1032
+ expires_at: response.expires_at,
1033
+ region: response.region
1034
+ };
1035
+ writeKeyless(ctx.cwd, keyless);
1036
+ const written = writeEnv(ctx.cwd, envEntries(response, secrets), reset ? REPLACED_ON_RESET : /* @__PURE__ */ new Set());
1037
+ return { kind: "new", keyless, env: written, secretKey: secrets.secret_key };
1038
+ });
1039
+ const k = provisioned.keyless;
1040
+ instance = {
1041
+ status: provisioned.kind === "new" ? "provisioned" : "reused",
1042
+ instance_id: k.instance_id,
1043
+ region: k.region,
1044
+ issuer: k.issuer,
1045
+ app_id: k.app_id,
1046
+ expires_at: k.expires_at
1047
+ };
1048
+ if (provisioned.kind === "new") {
1049
+ env = provisioned.env;
1050
+ secretKey = provisioned.secretKey;
1051
+ if (env.kept.length > 0) ctx.out.warn(`${ENV_FILE} already set ${env.kept.join(", ")}; those lines were left as they were.`);
1052
+ }
1053
+ }
1054
+ const mcp = await connectMcp(ctx, secretKey, instance.region, nextSteps);
1055
+ if (instance.expires_at) nextSteps.push(`Claim the instance before ${humanDate(instance.expires_at)} to keep it: npx pontive claim`);
1056
+ const human = [
1057
+ `Pontive is set up for ${project.framework} (${project.packageManager}).`,
1058
+ ...installed.length > 0 ? [`Installed ${installed.join(", ")}.`] : [],
1059
+ ...files.written.map((f) => `Wrote ${f}`),
1060
+ ...files.skipped.map((s) => `Skipped ${s.path}: ${s.reason}`),
1061
+ ...env.added.length + env.replaced.length > 0 ? [`Wrote ${[...env.added, ...env.replaced].join(", ")} to ${ENV_FILE}`] : [],
1062
+ ...instance.status === "provisioned" ? [`Wrote ${KEYLESS_FILE} (keep it private: it holds the claim token)`] : [],
1063
+ ...gitignore.length > 0 ? [`Added ${gitignore.join(", ")} to .gitignore`] : [],
1064
+ ...mcp?.written ? [`Wrote the Pontive MCP server to ${mcp.file}`] : [],
1065
+ "",
1066
+ instance.status === "configured" ? `Using the instance already configured in ${ENV_FILE} (${instance.issuer}).` : `Instance ${instance.instance_id} (${instance.region}), ${instance.issuer}${instance.status === "reused" ? ", reused from " + KEYLESS_FILE : ""}.`,
1067
+ ...instance.expires_at ? [
1068
+ "",
1069
+ ...box([
1070
+ `Unclaimed development instance. Pontive deletes it on ${humanDate(instance.expires_at)},`,
1071
+ "with its users. Run npx pontive claim to keep it."
1072
+ ])
1073
+ ] : [],
1074
+ "",
1075
+ "Next:",
1076
+ ...nextSteps.map((s) => ` - ${s}`)
1077
+ ];
1078
+ return {
1079
+ data: {
1080
+ framework: project.framework,
1081
+ package_manager: project.packageManager,
1082
+ installed,
1083
+ files,
1084
+ gitignore,
1085
+ instance,
1086
+ env: { added: env.added, kept: env.kept, replaced: env.replaced },
1087
+ mcp,
1088
+ next_steps: nextSteps
1089
+ },
1090
+ human
1091
+ };
1092
+ }
1093
+ const command$1 = {
1094
+ name: "init",
1095
+ summary: "Add Pontive sign-in to this app, creating an unclaimed development instance when you have no account",
1096
+ help: `Detects the framework (Next.js, Vite + React, Express, plain Node), installs the
1097
+ matching pontkit package, writes the auth route and middleware, and, signed out,
1098
+ creates an unclaimed development instance: its settings go to ${ENV_FILE}, its
1099
+ claim token to ${KEYLESS_FILE}, both gitignored. It lasts 7 days unless claimed
1100
+ (pontive claim). Existing files and ${ENV_FILE} lines are never overwritten.
1101
+
1102
+ Options:
1103
+ --reset Create a new unclaimed instance and point ${ENV_FILE} at it (asks first; --yes)
1104
+ --framework <name> ${FRAMEWORKS.join(" | ")} (default: detected)
1105
+ --region <region> us, eu or au (default: PONTIVE_REGION, else nearest)
1106
+ --name <name> The project's name (default: from package.json)
1107
+ --tenancy-mode <mode> b2c (default) or b2b
1108
+ --skip-install Do not install the pontkit package
1109
+ --mcp <agent> Connect this agent to Pontive's MCP server: ${MCP_AGENTS.join(", ")}
1110
+ --no-mcp Do not offer to connect an agent
1111
+
1112
+ Environment: PONTIVE_API_URL (default https://api.pontive.com), PONTIVE_REGION.`,
1113
+ options: {
1114
+ reset: { type: "boolean" },
1115
+ framework: { type: "string" },
1116
+ region: { type: "string" },
1117
+ name: { type: "string" },
1118
+ "tenancy-mode": { type: "string" },
1119
+ "skip-install": { type: "boolean" },
1120
+ mcp: { type: "string" },
1121
+ "no-mcp": { type: "boolean" }
1122
+ },
1123
+ run: run$2
1124
+ };
1125
+ const __vite_glob_0_1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1126
+ __proto__: null,
1127
+ command: command$1
1128
+ }, Symbol.toStringTag, { value: "Module" }));
1129
+ async function run$1(ctx) {
1130
+ const keyless = readKeyless(ctx.cwd);
1131
+ const envFile = readEnvFile(ctx.cwd);
1132
+ const set = CONTRACT_VARIABLES.filter((name) => Boolean(envFile.get(name) || ctx.env[name]));
1133
+ const missing = CONTRACT_VARIABLES.filter((name) => !set.includes(name));
1134
+ const variables = { set, missing };
1135
+ let state;
1136
+ let live;
1137
+ let checked = false;
1138
+ if (!keyless) {
1139
+ state = envFile.get("PONTIVE_ISSUER") || ctx.env.PONTIVE_ISSUER ? "configured" : "none";
1140
+ } else if (!keyless.claim_token) {
1141
+ state = "claimed";
1142
+ } else if (ctx.values.offline === true) {
1143
+ state = isExpired(keyless, ctx.now()) ? "expired" : "unclaimed";
1144
+ } else {
1145
+ try {
1146
+ live = await apiFor(ctx).getUnclaimed(keyless.instance_id, keyless.claim_token);
1147
+ checked = true;
1148
+ state = live.status === "claimed" ? "claimed" : "unclaimed";
1149
+ if (state === "claimed") await markClaimed(ctx);
1150
+ } catch (error) {
1151
+ if (error instanceof CliError && error.exitCode === ExitCode.ExpiredOrClaimedAway) {
1152
+ checked = true;
1153
+ state = "expired";
1154
+ } else if (error instanceof CliError && error.exitCode === ExitCode.RateLimited) {
1155
+ throw error;
1156
+ } else {
1157
+ ctx.out.warn(`Could not reach Pontive (${error instanceof Error ? error.message : String(error)}); showing what is on disk.`);
1158
+ state = isExpired(keyless, ctx.now()) ? "expired" : "unclaimed";
1159
+ }
1160
+ }
1161
+ }
1162
+ const issuer = keyless?.issuer ?? envFile.get("PONTIVE_ISSUER") ?? ctx.env.PONTIVE_ISSUER;
1163
+ const instanceId = keyless?.instance_id ?? envFile.get("PONTIVE_INSTANCE_ID") ?? ctx.env.PONTIVE_INSTANCE_ID;
1164
+ const expiresAt = state === "unclaimed" || state === "expired" ? live?.expires_at ?? keyless?.expires_at : void 0;
1165
+ const instance = state === "none" ? null : {
1166
+ instance_id: instanceId ?? null,
1167
+ region: live?.region ?? keyless?.region ?? null,
1168
+ issuer: issuer ?? null,
1169
+ app_id: keyless?.app_id ?? envFile.get("PONTIVE_CLIENT_ID") ?? null,
1170
+ status: state,
1171
+ ...expiresAt ? { expires_at: expiresAt } : {},
1172
+ ...live?.claimed_at ? { claimed_at: live.claimed_at } : {},
1173
+ checked_with_pontive: checked
1174
+ };
1175
+ const describe = {
1176
+ unclaimed: `unclaimed, deleted on ${expiresAt ? humanDate(expiresAt) : "?"} unless claimed (pontive claim)`,
1177
+ claimed: "claimed",
1178
+ expired: `expired${expiresAt ? ` on ${humanDate(expiresAt)}` : ""}; run pontive init --reset for a new one`,
1179
+ configured: `configured in ${ENV_FILE}`,
1180
+ none: "none; run pontive init"
1181
+ };
1182
+ const human = [
1183
+ `Instance: ${instance?.instance_id ?? "-"}`,
1184
+ `Region: ${instance?.region ?? "-"}`,
1185
+ `Issuer: ${instance?.issuer ?? "-"}`,
1186
+ `Status: ${describe[state]}`,
1187
+ `Set: ${set.length > 0 ? set.join(", ") : "-"}`,
1188
+ ...missing.length > 0 ? [`Not set: ${missing.join(", ")}`] : [],
1189
+ ...keyless ? [] : [`(no ${KEYLESS_FILE})`]
1190
+ ];
1191
+ return {
1192
+ exitCode: state === "expired" ? ExitCode.ExpiredOrClaimedAway : ExitCode.Success,
1193
+ data: { instance, variables },
1194
+ human
1195
+ };
1196
+ }
1197
+ const command = {
1198
+ name: "status",
1199
+ summary: "Show this app's Pontive instance and which PONTIVE_* variables are set",
1200
+ help: `Shows the instance, its region, when it is deleted unless claimed (or that it
1201
+ is claimed), and which PONTIVE_* variables ${ENV_FILE} or the environment set.
1202
+ Values are never printed. Exits 5 when the unclaimed instance has expired.
1203
+
1204
+ Options:
1205
+ --offline Do not ask Pontive; show what is on disk`,
1206
+ options: {
1207
+ offline: { type: "boolean" }
1208
+ },
1209
+ run: run$1
1210
+ };
1211
+ const __vite_glob_0_2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1212
+ __proto__: null,
1213
+ command
1214
+ }, Symbol.toStringTag, { value: "Module" }));
1215
+ const AGENT_VARIABLES = [
1216
+ ["CLAUDECODE", "claude-code"],
1217
+ ["CURSOR_AGENT", "cursor"],
1218
+ ["CODEX_SANDBOX", "codex"],
1219
+ ["GEMINI_CLI", "gemini-cli"]
1220
+ ];
1221
+ function isSet(value) {
1222
+ return value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
1223
+ }
1224
+ function detectAgent(env) {
1225
+ for (const [variable, agent] of AGENT_VARIABLES) {
1226
+ if (isSet(env[variable])) return agent;
1227
+ }
1228
+ return void 0;
1229
+ }
1230
+ function isAgentMode(env, json) {
1231
+ return json || detectAgent(env) !== void 0 || isSet(env.CI);
1232
+ }
1233
+ const modules = /* @__PURE__ */ Object.assign({ "./commands/claim.ts": __vite_glob_0_0, "./commands/init.ts": __vite_glob_0_1, "./commands/status.ts": __vite_glob_0_2 });
45
1234
  const commands = new Map(
46
1235
  Object.values(modules).map((m) => m.command).filter((c) => c !== void 0).sort((a, b) => a.name.localeCompare(b.name)).map((c) => [c.name, c])
47
1236
  );
@@ -94,14 +1283,14 @@ async function main(options) {
94
1283
  out.result(agentMode ? JSON.stringify({ ok: true, command: "version", version }) : version);
95
1284
  return ExitCode.Success;
96
1285
  }
97
- const command = commands.get(name);
98
- if (!command) return report(void 0, new CliError("unknown_command", `Unknown command "${name}". Run pontive --help.`));
1286
+ const command2 = commands.get(name);
1287
+ if (!command2) return report(void 0, new CliError("unknown_command", `Unknown command "${name}". Run pontive --help.`));
99
1288
  let parsed;
100
1289
  try {
101
1290
  parsed = parseArgs({
102
1291
  args: argv.slice(1),
103
- options: { ...GLOBAL_OPTIONS, ...command.options },
104
- allowPositionals: command.allowPositionals ?? false,
1292
+ options: { ...GLOBAL_OPTIONS, ...command2.options },
1293
+ allowPositionals: command2.allowPositionals ?? false,
105
1294
  strict: true
106
1295
  });
107
1296
  } catch (error) {
@@ -109,11 +1298,11 @@ async function main(options) {
109
1298
  }
110
1299
  const { values, positionals } = parsed;
111
1300
  if (values.help) {
112
- out.result(`Usage: pontive ${command.name} [options]
1301
+ out.result(`Usage: pontive ${command2.name} [options]
113
1302
 
114
- ${command.summary}
1303
+ ${command2.summary}
115
1304
 
116
- ${command.help}
1305
+ ${command2.help}
117
1306
 
118
1307
  ${GLOBAL_HELP}`);
119
1308
  return ExitCode.Success;
@@ -133,7 +1322,7 @@ ${GLOBAL_HELP}`);
133
1322
  };
134
1323
  let result;
135
1324
  try {
136
- result = await command.run(ctx);
1325
+ result = await command2.run(ctx);
137
1326
  } catch (error) {
138
1327
  return report(name, error);
139
1328
  }
@@ -155,9 +1344,9 @@ function streamOutput(stdout, stderr) {
155
1344
  `)
156
1345
  };
157
1346
  }
158
- function run(command, args, options) {
1347
+ function run(command2, args, options) {
159
1348
  return new Promise((resolve2) => {
160
- const child = spawn(command, args, {
1349
+ const child = spawn(command2, args, {
161
1350
  cwd: options.cwd,
162
1351
  // Agent mode keeps stdout for the one JSON object, so a child's output goes to stderr.
163
1352
  stdio: options.stdio === "inherit" ? "inherit" : ["ignore", process.stderr, process.stderr],
@@ -176,12 +1365,12 @@ function nodeRuntime(agentMode) {
176
1365
  return {
177
1366
  fetch: (...args) => fetch(...args),
178
1367
  interactive: Boolean(process.stdin.isTTY),
179
- exec: (command, args, options) => run(command, args, { cwd: options.cwd, stdio: agentMode ? "stderr" : "inherit" }),
1368
+ exec: (command2, args, options) => run(command2, args, { cwd: options.cwd, stdio: agentMode ? "stderr" : "inherit" }),
180
1369
  async openUrl(url) {
181
1370
  if (!hasDisplay(process.env)) return false;
182
- const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
1371
+ const [command2, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
183
1372
  return new Promise((resolve2) => {
184
- const child = spawn(command, args, { stdio: "ignore", detached: true });
1373
+ const child = spawn(command2, args, { stdio: "ignore", detached: true });
185
1374
  child.on("error", () => resolve2(false));
186
1375
  child.on("spawn", () => {
187
1376
  child.unref();
@@ -228,6 +1417,6 @@ const code = await main({
228
1417
  out: streamOutput(process.stdout, process.stderr),
229
1418
  runtime: nodeRuntime,
230
1419
  signal: controller.signal,
231
- version: "1.17.0"
1420
+ version: "1.18.0"
232
1421
  });
233
1422
  process.exitCode = code;