pontive 1.17.0 → 1.19.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 +260 -3
  2. package/dist/cli.js +3357 -46
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,33 +1,27 @@
1
1
  #!/usr/bin/env node
2
+ import { randomBytes, generateKeyPairSync, randomUUID, createHash } from "node:crypto";
3
+ import { existsSync, readFileSync, writeFileSync, openSync, closeSync, statSync, unlinkSync, mkdirSync, renameSync, createReadStream, createWriteStream } 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";
7
+ import { readFile, rm, writeFile, rename } from "node:fs/promises";
8
+ import { createInterface } from "node:readline";
9
+ import { gunzipSync } from "node:zlib";
10
+ import { createRequire } from "node:module";
11
+ import { pathToFileURL } from "node:url";
2
12
  import { parseArgs } from "node:util";
3
- import { resolve } from "node:path";
4
- import { spawn } from "node:child_process";
5
- 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
- }
13
+ import { createInterface as createInterface$1 } from "node:readline/promises";
24
14
  const ExitCode = {
25
15
  /** Done. */
26
16
  Success: 0,
27
17
  /** Anything else that went wrong. */
28
18
  Error: 1,
29
19
  /** The user, or a missing `--yes` in agent mode, declined. */
30
- Cancelled: 2
20
+ Cancelled: 2,
21
+ /** Pontive rate limited the call; the JSON carries `retry_after` in seconds. */
22
+ RateLimited: 3,
23
+ /** The unclaimed instance expired or was claimed by someone else. */
24
+ ExpiredOrClaimedAway: 5
31
25
  };
32
26
  class CliError extends Error {
33
27
  code;
@@ -41,7 +35,3324 @@ class CliError extends Error {
41
35
  this.extra = extra;
42
36
  }
43
37
  }
44
- const modules = /* @__PURE__ */ Object.assign({});
38
+ function cancelled(message, extra = {}) {
39
+ return new CliError("cancelled", message, ExitCode.Cancelled, extra);
40
+ }
41
+ const DEFAULT_API_URL = "https://api.pontive.com";
42
+ function apiBaseUrl$1(env) {
43
+ return (env.PONTIVE_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
44
+ }
45
+ function retryAfterSeconds(header, now) {
46
+ if (!header) return void 0;
47
+ const trimmed = header.trim();
48
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
49
+ const at = Date.parse(trimmed);
50
+ if (Number.isNaN(at)) return void 0;
51
+ return Math.max(0, Math.ceil((at - now.getTime()) / 1e3));
52
+ }
53
+ async function errorOf(response) {
54
+ try {
55
+ const body = await response.json();
56
+ return {
57
+ code: typeof body.error?.code === "string" ? body.error.code : void 0,
58
+ message: typeof body.error?.message === "string" ? body.error.message : void 0
59
+ };
60
+ } catch {
61
+ return {};
62
+ }
63
+ }
64
+ const MAX_RETRY_WAIT_SECONDS = 30;
65
+ let PontiveApi$1 = class PontiveApi {
66
+ constructor(options2) {
67
+ this.options = options2;
68
+ }
69
+ options;
70
+ /** Provisions an unclaimed development instance. Retried with the same idempotency key, so a retry never makes a second one. */
71
+ provision(body, idempotencyKey) {
72
+ return this.request("POST", "/v1/unclaimed-instances", {
73
+ body,
74
+ headers: { "x-idempotency-key": idempotencyKey }
75
+ });
76
+ }
77
+ getUnclaimed(instanceId, claimToken) {
78
+ return this.request("GET", `/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {
79
+ headers: { "x-pontive-claim-token": claimToken }
80
+ });
81
+ }
82
+ mintClaimLink(instanceId, claimToken) {
83
+ return this.request("POST", `/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {
84
+ headers: { "x-pontive-claim-token": claimToken }
85
+ });
86
+ }
87
+ async request(method, path, init) {
88
+ const { baseUrl, fetch: fetch2, sleep, now, signal, userAgent } = this.options;
89
+ const retries = this.options.retries ?? 3;
90
+ const url = `${baseUrl}${path}`;
91
+ for (let attempt = 0; ; attempt++) {
92
+ const backoff2 = 1e3 * 2 ** attempt;
93
+ let response;
94
+ try {
95
+ response = await fetch2(url, {
96
+ method,
97
+ headers: {
98
+ accept: "application/json",
99
+ "user-agent": userAgent,
100
+ ...init.body !== void 0 ? { "content-type": "application/json" } : {},
101
+ ...init.headers
102
+ },
103
+ body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
104
+ signal
105
+ });
106
+ } catch (error) {
107
+ if (signal?.aborted) throw error;
108
+ if (attempt < retries) {
109
+ await sleep(backoff2, signal);
110
+ continue;
111
+ }
112
+ throw new CliError("network_error", `Could not reach ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
113
+ }
114
+ if (response.ok) return await response.json();
115
+ const retryAfter = retryAfterSeconds(response.headers.get("retry-after"), now());
116
+ if (response.status >= 500 && attempt < retries) {
117
+ const wait = retryAfter !== void 0 && retryAfter <= MAX_RETRY_WAIT_SECONDS ? retryAfter * 1e3 : backoff2;
118
+ await response.body?.cancel();
119
+ await sleep(wait, signal);
120
+ continue;
121
+ }
122
+ throw await this.failure(response, retryAfter);
123
+ }
124
+ }
125
+ async failure(response, retryAfter) {
126
+ const { code: code2, message } = await errorOf(response);
127
+ const extra = retryAfter !== void 0 ? { retry_after: retryAfter } : {};
128
+ if (response.status === 429) {
129
+ return new CliError(
130
+ code2 ?? "rate_limited",
131
+ message ?? `Pontive rate limited the request${retryAfter !== void 0 ? `; retry in ${retryAfter}s` : ""}.`,
132
+ ExitCode.RateLimited,
133
+ { retry_after: retryAfter ?? 60 }
134
+ );
135
+ }
136
+ if (response.status === 401) {
137
+ return new CliError(
138
+ code2 ?? "unauthorized",
139
+ "Pontive refused the instance's credentials: the unclaimed instance expired or was claimed by someone else. Run pontive init --reset for a new one.",
140
+ ExitCode.ExpiredOrClaimedAway
141
+ );
142
+ }
143
+ if (response.status === 404 && (code2 === "unclaimed_instance_not_found" || code2 === void 0)) {
144
+ return new CliError(
145
+ "unclaimed_instance_not_found",
146
+ "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.",
147
+ ExitCode.ExpiredOrClaimedAway
148
+ );
149
+ }
150
+ return new CliError(
151
+ code2 ?? `http_${response.status}`,
152
+ message ?? `Pontive answered ${response.status} ${response.statusText}.`.replace(/ \./, "."),
153
+ ExitCode.Error,
154
+ extra
155
+ );
156
+ }
157
+ };
158
+ const ENV_FILE = ".env.local";
159
+ const PONTIVE_DIR = ".pontive";
160
+ const KEYLESS_FILE = join(PONTIVE_DIR, "keyless.json");
161
+ const LOCK_FILE = join(PONTIVE_DIR, "keyless.lock");
162
+ const CONTRACT_VARIABLES = [
163
+ "PONTIVE_ISSUER",
164
+ "PONTIVE_CLIENT_ID",
165
+ "PONTIVE_CLIENT_SECRET",
166
+ "PONTIVE_SESSION_SECRET",
167
+ "PONTIVE_SECRET_KEY",
168
+ "PONTIVE_INSTANCE_ID"
169
+ ];
170
+ function writeAtomic(path, contents) {
171
+ mkdirSync(dirname(path), { recursive: true });
172
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
173
+ writeFileSync(tmp, contents, { mode: 384 });
174
+ renameSync(tmp, path);
175
+ }
176
+ function ensurePontiveDir(cwd) {
177
+ const dir = join(cwd, PONTIVE_DIR);
178
+ mkdirSync(dir, { recursive: true, mode: 448 });
179
+ const ignore = join(dir, ".gitignore");
180
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
181
+ }
182
+ function readKeyless(cwd) {
183
+ const path = join(cwd, KEYLESS_FILE);
184
+ if (!existsSync(path)) return null;
185
+ let parsed;
186
+ try {
187
+ parsed = JSON.parse(readFileSync(path, "utf8"));
188
+ } catch {
189
+ throw new CliError("invalid_keyless_file", `${KEYLESS_FILE} is not valid JSON.`);
190
+ }
191
+ const k = parsed;
192
+ for (const field of ["instance_id", "issuer", "app_id", "expires_at", "region"]) {
193
+ if (typeof k?.[field] !== "string") throw new CliError("invalid_keyless_file", `${KEYLESS_FILE} has no ${field}.`);
194
+ }
195
+ return parsed;
196
+ }
197
+ function writeKeyless(cwd, keyless) {
198
+ ensurePontiveDir(cwd);
199
+ const ordered = {
200
+ instance_id: keyless.instance_id,
201
+ issuer: keyless.issuer,
202
+ app_id: keyless.app_id,
203
+ ...keyless.claim_token ? { claim_token: keyless.claim_token } : {},
204
+ expires_at: keyless.expires_at,
205
+ region: keyless.region
206
+ };
207
+ writeAtomic(join(cwd, KEYLESS_FILE), `${JSON.stringify(ordered, null, 2)}
208
+ `);
209
+ }
210
+ async function withKeylessLock(cwd, options2, fn) {
211
+ ensurePontiveDir(cwd);
212
+ const path = join(cwd, LOCK_FILE);
213
+ const waitMs = options2.waitMs ?? 3e4;
214
+ const staleMs = options2.staleMs ?? 12e4;
215
+ const step = 250;
216
+ for (let waited = 0; ; waited += step) {
217
+ try {
218
+ const fd = openSync(path, "wx", 384);
219
+ writeFileSync(fd, `${JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString(), by: "pontive-cli" })}
220
+ `);
221
+ closeSync(fd);
222
+ break;
223
+ } catch (error) {
224
+ if (error.code !== "EEXIST") throw error;
225
+ try {
226
+ if (Date.now() - statSync(path).mtimeMs > staleMs) {
227
+ unlinkSync(path);
228
+ continue;
229
+ }
230
+ } catch {
231
+ continue;
232
+ }
233
+ if (waited >= waitMs) {
234
+ throw new CliError(
235
+ "keyless_locked",
236
+ `${LOCK_FILE} is held by another process (a dev server provisioning?). Try again shortly, or remove the file if nothing is running.`
237
+ );
238
+ }
239
+ await options2.sleep(step, options2.signal);
240
+ }
241
+ }
242
+ try {
243
+ return await fn();
244
+ } finally {
245
+ try {
246
+ unlinkSync(path);
247
+ } catch {
248
+ }
249
+ }
250
+ }
251
+ const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
252
+ function unquote(raw) {
253
+ const value = raw.trim();
254
+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) return value.slice(1, -1);
255
+ return value.replace(/\s+#.*$/, "");
256
+ }
257
+ function readEnvFile(cwd) {
258
+ const path = join(cwd, ENV_FILE);
259
+ const vars = /* @__PURE__ */ new Map();
260
+ if (!existsSync(path)) return vars;
261
+ for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
262
+ const match = ENV_LINE.exec(line);
263
+ if (match && !vars.has(match[1])) vars.set(match[1], unquote(match[2]));
264
+ }
265
+ return vars;
266
+ }
267
+ function formatValue(value) {
268
+ return /^[A-Za-z0-9_\-.:/+=@]*$/.test(value) ? value : JSON.stringify(value);
269
+ }
270
+ function writeEnv(cwd, entries, replace = /* @__PURE__ */ new Set()) {
271
+ const path = join(cwd, ENV_FILE);
272
+ const original = existsSync(path) ? readFileSync(path, "utf8") : "";
273
+ const lines = original === "" ? [] : original.replace(/\r?\n$/, "").split(/\r?\n/);
274
+ const result = { added: [], kept: [], replaced: [] };
275
+ const wanted = new Map(entries);
276
+ for (let i = 0; i < lines.length; i++) {
277
+ const match = ENV_LINE.exec(lines[i]);
278
+ if (!match || !wanted.has(match[1])) continue;
279
+ const name = match[1];
280
+ if (replace.has(name) && !result.replaced.includes(name)) {
281
+ lines[i] = `${name}=${formatValue(wanted.get(name))}`;
282
+ result.replaced.push(name);
283
+ } else if (!result.kept.includes(name) && !result.replaced.includes(name)) {
284
+ result.kept.push(name);
285
+ }
286
+ }
287
+ const missing = entries.filter(([name]) => !result.kept.includes(name) && !result.replaced.includes(name));
288
+ if (missing.length > 0) {
289
+ if (lines.length > 0 && lines.at(-1).trim() !== "") lines.push("");
290
+ lines.push("# Pontive: written by pontive init. See https://docs.pontive.com/unclaimed-instances");
291
+ for (const [name, value] of missing) {
292
+ lines.push(`${name}=${formatValue(value)}`);
293
+ result.added.push(name);
294
+ }
295
+ }
296
+ if (result.added.length > 0 || result.replaced.length > 0) writeAtomic(path, `${lines.join("\n")}
297
+ `);
298
+ return result;
299
+ }
300
+ function sessionSecret() {
301
+ return randomBytes(32).toString("base64url");
302
+ }
303
+ function patternMatches(pattern, path, isDir2) {
304
+ let p = pattern.trim();
305
+ if (p === "" || p.startsWith("#") || p.startsWith("!")) return false;
306
+ if (p.endsWith("/")) {
307
+ if (!isDir2) return false;
308
+ p = p.slice(0, -1);
309
+ }
310
+ p = p.replace(/^\//, "").replace(/^\*\*\//, "");
311
+ if (p.includes("/")) return false;
312
+ const regex = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")}$`);
313
+ return regex.test(path);
314
+ }
315
+ function ensureGitignore(cwd, entries) {
316
+ const path = join(cwd, ".gitignore");
317
+ const original = existsSync(path) ? readFileSync(path, "utf8") : "";
318
+ const patterns = original.split(/\r?\n/);
319
+ const added = [];
320
+ for (const entry of entries) {
321
+ const isDir2 = entry.endsWith("/");
322
+ const name = entry.replace(/\/$/, "");
323
+ const exact = (p) => [name, `/${name}`, `${name}/`, `/${name}/`].includes(p.trim());
324
+ if (patterns.some((p) => exact(p) || patternMatches(p, name, isDir2))) continue;
325
+ added.push(entry);
326
+ }
327
+ if (added.length > 0) {
328
+ const prefix = original === "" || original.endsWith("\n") ? original : `${original}
329
+ `;
330
+ writeFileSync(path, `${prefix}${prefix === "" ? "" : "\n"}# Pontive: secrets for local development
331
+ ${added.join("\n")}
332
+ `);
333
+ }
334
+ return added;
335
+ }
336
+ function apiFor(ctx) {
337
+ return new PontiveApi$1({
338
+ baseUrl: apiBaseUrl$1(ctx.env),
339
+ fetch: ctx.fetch,
340
+ sleep: ctx.sleep,
341
+ now: ctx.now,
342
+ signal: ctx.signal,
343
+ userAgent: `pontive-cli/${ctx.version}`
344
+ });
345
+ }
346
+ function isExpired(keyless, now) {
347
+ const at = Date.parse(keyless.expires_at);
348
+ return !Number.isNaN(at) && at <= now.getTime();
349
+ }
350
+ async function markClaimed(ctx) {
351
+ await withKeylessLock(ctx.cwd, { sleep: ctx.sleep, signal: ctx.signal }, async () => {
352
+ const current = readKeyless(ctx.cwd);
353
+ if (!current?.claim_token) return;
354
+ const { claim_token: _dead, ...rest } = current;
355
+ writeKeyless(ctx.cwd, rest);
356
+ });
357
+ }
358
+ function humanDate(iso) {
359
+ const at = new Date(iso);
360
+ if (Number.isNaN(at.getTime())) return iso;
361
+ return at.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
362
+ }
363
+ function box(lines) {
364
+ const width = Math.max(...lines.map((l) => l.length));
365
+ return [`┌${"─".repeat(width + 2)}┐`, ...lines.map((l) => `│ ${l.padEnd(width)} │`), `└${"─".repeat(width + 2)}┘`];
366
+ }
367
+ const POLL_INTERVAL_MS = 5e3;
368
+ const DEFAULT_TIMEOUT_SECONDS = 300;
369
+ function claimed(instanceId) {
370
+ return {
371
+ data: { instance_id: instanceId, status: "claimed" },
372
+ human: [`Instance ${instanceId} is claimed. Your keys keep working; nothing in your app changes.`]
373
+ };
374
+ }
375
+ function timeoutSeconds(ctx) {
376
+ const raw = ctx.values.timeout;
377
+ if (raw === void 0) return DEFAULT_TIMEOUT_SECONDS;
378
+ const n = Number(raw);
379
+ if (!Number.isInteger(n) || n < 0) throw new CliError("invalid_arguments", "--timeout must be a whole number of seconds.");
380
+ return n;
381
+ }
382
+ async function run$3(ctx) {
383
+ const timeout = timeoutSeconds(ctx);
384
+ const keyless = readKeyless(ctx.cwd);
385
+ if (!keyless) {
386
+ throw new CliError("no_unclaimed_instance", `No ${KEYLESS_FILE} here, so no unclaimed instance to claim. Run pontive init first.`);
387
+ }
388
+ if (!keyless.claim_token) return claimed(keyless.instance_id);
389
+ if (isExpired(keyless, ctx.now())) {
390
+ throw new CliError(
391
+ "instance_expired",
392
+ `The unclaimed instance ${keyless.instance_id} expired on ${humanDate(keyless.expires_at)}. Run pontive init --reset for a new one.`,
393
+ ExitCode.ExpiredOrClaimedAway,
394
+ { instance_id: keyless.instance_id }
395
+ );
396
+ }
397
+ const api2 = apiFor(ctx);
398
+ let link;
399
+ try {
400
+ link = await api2.mintClaimLink(keyless.instance_id, keyless.claim_token);
401
+ } catch (error) {
402
+ if (error instanceof CliError && error.code === "instance_claimed") {
403
+ await markClaimed(ctx);
404
+ return claimed(keyless.instance_id);
405
+ }
406
+ throw error;
407
+ }
408
+ const opened = ctx.agentMode ? false : await ctx.openUrl(link.url);
409
+ ctx.out.info(
410
+ 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):
411
+ ${link.url}`
412
+ );
413
+ const pending = (waited) => ({
414
+ data: {
415
+ instance_id: keyless.instance_id,
416
+ status: "unclaimed",
417
+ claim_url: link.url,
418
+ claim_url_expires_at: link.expires_at,
419
+ expires_at: keyless.expires_at,
420
+ waited_seconds: waited
421
+ },
422
+ human: [
423
+ `Not claimed yet. The link works until ${link.expires_at}: ${link.url}`,
424
+ "The instance keeps working meanwhile; run pontive status to check, or pontive claim for a new link."
425
+ ]
426
+ });
427
+ if (ctx.values["no-wait"] === true || timeout === 0) return pending(0);
428
+ ctx.out.info("Waiting for the claim…");
429
+ const started = ctx.now().getTime();
430
+ for (; ; ) {
431
+ const elapsed = ctx.now().getTime() - started;
432
+ if (elapsed >= timeout * 1e3) return pending(Math.round(elapsed / 1e3));
433
+ await ctx.sleep(Math.min(POLL_INTERVAL_MS, timeout * 1e3 - elapsed), ctx.signal);
434
+ const status = await api2.getUnclaimed(keyless.instance_id, keyless.claim_token);
435
+ if (status.status === "claimed") {
436
+ await markClaimed(ctx);
437
+ return claimed(keyless.instance_id);
438
+ }
439
+ }
440
+ }
441
+ const command$2 = {
442
+ name: "claim",
443
+ summary: "Claim this app's unclaimed instance into your Pontive workspace",
444
+ help: `Mints a claim link (single use, valid for an hour), opens it in your browser
445
+ (prints it in agent mode or when there is no browser), and waits up to
446
+ 5 minutes for the claim. Once claimed, the claim token is removed from
447
+ ${KEYLESS_FILE}. The instance's keys keep working throughout.
448
+
449
+ Options:
450
+ --no-wait Print the link and return without waiting
451
+ --timeout <seconds> How long to wait for the claim (default ${DEFAULT_TIMEOUT_SECONDS})`,
452
+ options: {
453
+ "no-wait": { type: "boolean" },
454
+ timeout: { type: "string" }
455
+ },
456
+ run: run$3
457
+ };
458
+ const __vite_glob_0_0 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
459
+ __proto__: null,
460
+ command: command$2
461
+ }, Symbol.toStringTag, { value: "Module" }));
462
+ async function confirm(ctx, question) {
463
+ if (ctx.yes) return true;
464
+ if (ctx.agentMode || !ctx.interactive) return false;
465
+ return ctx.ask(question);
466
+ }
467
+ async function ephemeralKey() {
468
+ const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
469
+ const jwk = publicKey.export({ format: "jwk" });
470
+ const publicJwk = { kty: "EC", crv: "P-256", x: String(jwk.x), y: String(jwk.y) };
471
+ return { publicJwk, privateKey, thumbprint: await calculateJwkThumbprint(publicJwk, "sha256") };
472
+ }
473
+ function invalid$1(message) {
474
+ return new CliError("invalid_encrypted_secrets", message);
475
+ }
476
+ async function decryptSecrets(jwe, key) {
477
+ let header;
478
+ try {
479
+ header = decodeProtectedHeader(jwe);
480
+ } catch {
481
+ throw invalid$1("Pontive answered encrypted_secrets that is not a compact JWE.");
482
+ }
483
+ if (header.alg !== "ECDH-ES" || header.enc !== "A256GCM") {
484
+ throw invalid$1(`encrypted_secrets uses ${String(header.alg)}/${String(header.enc)}; expected ECDH-ES/A256GCM.`);
485
+ }
486
+ if (header.kid !== void 0 && header.kid !== key.thumbprint) {
487
+ throw invalid$1("encrypted_secrets was sealed to another key.");
488
+ }
489
+ let plaintext;
490
+ try {
491
+ ({ plaintext } = await compactDecrypt(jwe, key.privateKey, {
492
+ keyManagementAlgorithms: ["ECDH-ES"],
493
+ contentEncryptionAlgorithms: ["A256GCM"]
494
+ }));
495
+ } catch {
496
+ throw invalid$1("encrypted_secrets could not be decrypted.");
497
+ }
498
+ let secrets;
499
+ try {
500
+ secrets = JSON.parse(new TextDecoder().decode(plaintext));
501
+ } catch {
502
+ throw invalid$1("encrypted_secrets does not hold a JSON object.");
503
+ }
504
+ const s = secrets;
505
+ if (typeof s !== "object" || s === null || typeof s.secret_key !== "string" || typeof s.claim_token !== "string") {
506
+ throw invalid$1("encrypted_secrets is missing secret_key or claim_token.");
507
+ }
508
+ if (s.client_secret !== void 0 && s.client_secret !== null && typeof s.client_secret !== "string") {
509
+ throw invalid$1("encrypted_secrets carries a client_secret that is not a string.");
510
+ }
511
+ return {
512
+ secret_key: s.secret_key,
513
+ claim_token: s.claim_token,
514
+ ...typeof s.client_secret === "string" ? { client_secret: s.client_secret } : {}
515
+ };
516
+ }
517
+ async function loadLogin(_env) {
518
+ return null;
519
+ }
520
+ const FRAMEWORKS = ["nextjs", "vite-react", "express", "node"];
521
+ function readJson(path) {
522
+ try {
523
+ return JSON.parse(readFileSync(path, "utf8"));
524
+ } catch {
525
+ return void 0;
526
+ }
527
+ }
528
+ function isDir(path) {
529
+ try {
530
+ return statSync(path).isDirectory();
531
+ } catch {
532
+ return false;
533
+ }
534
+ }
535
+ function hasDependency(pkg, name) {
536
+ return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
537
+ }
538
+ const LOCKFILES = [
539
+ ["pnpm-lock.yaml", "pnpm"],
540
+ ["bun.lock", "bun"],
541
+ ["bun.lockb", "bun"],
542
+ ["yarn.lock", "yarn"],
543
+ ["package-lock.json", "npm"]
544
+ ];
545
+ function detectPackageManager(cwd, pkg) {
546
+ for (let dir = cwd; ; dir = dirname(dir)) {
547
+ for (const [file, pm] of LOCKFILES) {
548
+ if (existsSync(join(dir, file))) return pm;
549
+ }
550
+ if (dirname(dir) === dir) break;
551
+ }
552
+ const declared = pkg.packageManager?.split("@")[0];
553
+ if (declared === "pnpm" || declared === "yarn" || declared === "bun" || declared === "npm") return declared;
554
+ return "npm";
555
+ }
556
+ function detectFramework(pkg) {
557
+ if (hasDependency(pkg, "next")) return "nextjs";
558
+ if (hasDependency(pkg, "vite") && hasDependency(pkg, "react")) return "vite-react";
559
+ if (hasDependency(pkg, "express")) return "express";
560
+ return "node";
561
+ }
562
+ function nextMajor(cwd, pkg) {
563
+ const installed = readJson(join(cwd, "node_modules", "next", "package.json"))?.version;
564
+ const declared = pkg.dependencies?.next ?? pkg.devDependencies?.next;
565
+ const match = /(\d+)/.exec(installed ?? declared ?? "");
566
+ return match ? Number(match[1]) : void 0;
567
+ }
568
+ function detectProject(cwd, framework) {
569
+ const pkg = readJson(join(cwd, "package.json"));
570
+ if (!pkg) {
571
+ 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.`);
572
+ }
573
+ const fw = framework ?? detectFramework(pkg);
574
+ const srcDir = fw === "nextjs" ? isDir(join(cwd, "src", "app")) || isDir(join(cwd, "src")) && !isDir(join(cwd, "app")) : isDir(join(cwd, "src"));
575
+ return {
576
+ cwd,
577
+ framework: fw,
578
+ packageManager: detectPackageManager(cwd, pkg),
579
+ packageJson: pkg,
580
+ typescript: existsSync(join(cwd, "tsconfig.json")),
581
+ esm: pkg.type === "module",
582
+ srcDir,
583
+ ...fw === "nextjs" ? { nextMajor: nextMajor(cwd, pkg) } : {}
584
+ };
585
+ }
586
+ function installCommand(pm, packages) {
587
+ return pm === "npm" ? ["npm", ["install", ...packages]] : [pm, ["add", ...packages]];
588
+ }
589
+ function isInstalled(project, name) {
590
+ return hasDependency(project.packageJson, name);
591
+ }
592
+ function projectName(project) {
593
+ const raw = (project.packageJson.name ?? basename(project.cwd)).replace(/^@[^/]+\//, "");
594
+ const words = raw.split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1));
595
+ const name = words.join(" ").slice(0, 100).trim();
596
+ return name === "" ? "Untitled app" : name;
597
+ }
598
+ const MCP_AGENTS = ["claude-code", "cursor", "gemini-cli", "codex"];
599
+ const TARGETS = {
600
+ "claude-code": {
601
+ file: ".mcp.json",
602
+ entry: (url, key) => ({ type: "http", url, headers: { Authorization: `Bearer ${key}` } })
603
+ },
604
+ cursor: {
605
+ file: join(".cursor", "mcp.json"),
606
+ entry: (url, key) => ({ url, headers: { Authorization: `Bearer ${key}` } })
607
+ },
608
+ "gemini-cli": {
609
+ file: join(".gemini", "settings.json"),
610
+ entry: (url, key) => ({ httpUrl: url, headers: { Authorization: `Bearer ${key}` } })
611
+ }
612
+ };
613
+ function mcpUrl(apiUrl, region, env) {
614
+ if (env.PONTIVE_MCP_URL) return env.PONTIVE_MCP_URL;
615
+ let base = "pontive.com";
616
+ try {
617
+ const host = new URL(apiUrl).hostname;
618
+ if (host.startsWith("api.")) base = host.slice("api.".length);
619
+ } catch {
620
+ }
621
+ return `https://mcp.${region}.${base}/mcp`;
622
+ }
623
+ function agentFromProject(cwd) {
624
+ if (existsSync(join(cwd, ".mcp.json")) || existsSync(join(cwd, ".claude")) || existsSync(join(cwd, "CLAUDE.md"))) return "claude-code";
625
+ if (existsSync(join(cwd, ".cursor"))) return "cursor";
626
+ if (existsSync(join(cwd, ".gemini")) || existsSync(join(cwd, "GEMINI.md"))) return "gemini-cli";
627
+ return void 0;
628
+ }
629
+ function isMcpAgent(agent) {
630
+ return MCP_AGENTS.includes(agent ?? "");
631
+ }
632
+ function mcpConfigFile(agent) {
633
+ return TARGETS[agent]?.file;
634
+ }
635
+ function mcpManualStep(agent, url) {
636
+ if (agent === "codex") {
637
+ 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.`;
638
+ }
639
+ return `Connect the Pontive MCP server at ${url} with the header Authorization: Bearer <PONTIVE_SECRET_KEY from .env.local>.`;
640
+ }
641
+ function tracked(cwd, file) {
642
+ const result = spawnSync("git", ["ls-files", "--error-unmatch", file], { cwd, stdio: "ignore" });
643
+ return result.status === 0;
644
+ }
645
+ function writeMcpConfig(cwd, agent, url, secretKey2) {
646
+ const target = TARGETS[agent];
647
+ const manual = mcpManualStep(agent, url);
648
+ if (!target) return { written: false, agent, url, reason: "no project-level config for this agent", manual };
649
+ const path = join(cwd, target.file);
650
+ if (tracked(cwd, target.file)) {
651
+ return { written: false, agent, file: target.file, url, reason: `${target.file} is tracked by git, and a secret key must not be committed`, manual };
652
+ }
653
+ let config = {};
654
+ if (existsSync(path)) {
655
+ try {
656
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
657
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error();
658
+ config = parsed;
659
+ } catch {
660
+ return { written: false, agent, file: target.file, url, reason: `${target.file} is not a JSON object`, manual };
661
+ }
662
+ }
663
+ const servers = typeof config.mcpServers === "object" && config.mcpServers !== null ? config.mcpServers : {};
664
+ config.mcpServers = { ...servers, pontive: target.entry(url, secretKey2) };
665
+ mkdirSync(dirname(path), { recursive: true });
666
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}
667
+ `, { mode: 384 });
668
+ return { written: true, agent, file: target.file, url, gitignore: ensureGitignore(cwd, [target.file.split("\\").join("/")]) };
669
+ }
670
+ const HEADER = "Written by `pontive init`. The values come from .env.local, the PONTIVE_* variables.";
671
+ function nextjs(project) {
672
+ const ts = project.typescript;
673
+ const ext = ts ? "ts" : "js";
674
+ const base = project.srcDir ? "src/" : "";
675
+ const bang = ts ? "!" : "";
676
+ const proxyFile = (project.nextMajor ?? 0) >= 16;
677
+ const middlewareName = proxyFile ? "proxy" : "middleware";
678
+ const middlewarePath = `${base}${middlewareName}.${ext}`;
679
+ const lib = `import { pontiveAuth } from "@pontive/pontkit-nextjs/server";
680
+
681
+ // ${HEADER}
682
+ export const pontive = pontiveAuth({
683
+ issuer: process.env.PONTIVE_ISSUER${bang},
684
+ clientId: process.env.PONTIVE_CLIENT_ID${bang},
685
+ clientSecret: process.env.PONTIVE_CLIENT_SECRET,
686
+ sessionSecret: process.env.PONTIVE_SESSION_SECRET,
687
+ });
688
+ `;
689
+ const route = `// Pontive's sign-in routes: /api/auth/login, /api/auth/callback, /api/auth/logout.
690
+ import { pontive } from "../../../../lib/pontive";
691
+
692
+ export const { GET, POST } = pontive.handlers;
693
+ `;
694
+ const middleware = `${ts ? 'import type { NextRequest } from "next/server";\n' : ""}import { pontive } from "./lib/pontive";
695
+
696
+ // Keeps the Pontive session current before anything renders. Read it anywhere
697
+ // on the server with \`await pontive.auth()\`.
698
+ export function ${middlewareName}(req${ts ? ": NextRequest" : ""}) {
699
+ return pontive.middleware(req);
700
+ }
701
+
702
+ export const config = {
703
+ matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
704
+ };
705
+ `;
706
+ const otherMiddleware = ["middleware", "proxy"].flatMap((n) => [`${base}${n}.ts`, `${base}${n}.js`]);
707
+ return {
708
+ packages: ["@pontive/pontkit-nextjs"],
709
+ appType: "web",
710
+ files: [
711
+ { path: `${base}lib/pontive.${ext}`, contents: lib },
712
+ { path: `${base}app/api/auth/[...pontive]/route.${ext}`, contents: route },
713
+ {
714
+ path: middlewarePath,
715
+ contents: middleware,
716
+ unlessExists: otherMiddleware,
717
+ manual: `Your ${middlewareName} file already exists: return pontive.middleware(req) from it (import { pontive } from "./lib/pontive").`
718
+ }
719
+ ],
720
+ nextSteps: [
721
+ "Sign in at /api/auth/login and out at /api/auth/logout.",
722
+ "Read the session on the server with await pontive.auth()."
723
+ ]
724
+ };
725
+ }
726
+ function viteReact(project) {
727
+ const ts = project.typescript;
728
+ const base = project.srcDir ? "src/" : "";
729
+ const provider = `${ts ? 'import type { ReactNode } from "react";\n' : ""}import { Provider } from "@pontive/pontkit-react";
730
+
731
+ // ${HEADER}
732
+ // The browser reaches the auth server through the dev server's /__pontive
733
+ // proxy (vite.pontive.${ts ? "ts" : "js"}). Wrap the app: <PontiveProvider><App /></PontiveProvider>
734
+ export function PontiveProvider({ children }${ts ? ": { children: ReactNode }" : ""}) {
735
+ return (
736
+ <Provider domain="/__pontive" appId={import.meta.env.PONTIVE_CLIENT_ID}>
737
+ {children}
738
+ </Provider>
739
+ );
740
+ }
741
+ `;
742
+ const plugin = `import { loadEnv${ts ? ", type Plugin" : ""} } from "vite";
743
+ import { viteAuthProxy } from "@pontive/pontkit-loader/proxy";
744
+
745
+ // ${HEADER}
746
+ // Add it to vite.config: plugins: [react(), pontive()]. It proxies /__pontive
747
+ // to the instance's auth server and gives the browser the app's client id,
748
+ // and no other variable, from .env.local. In production, proxy /__pontive on
749
+ // your host instead (pontkit docs/auth-proxy.md).
750
+ export function pontive()${ts ? ": Plugin" : ""} {
751
+ return {
752
+ name: "pontive",
753
+ config(_config, { mode }) {
754
+ const env = loadEnv(mode, process.cwd(), "PONTIVE_");
755
+ return {
756
+ ...(env.PONTIVE_ISSUER ? { server: { proxy: viteAuthProxy({ authHost: env.PONTIVE_ISSUER }) } } : {}),
757
+ define: { "import.meta.env.PONTIVE_CLIENT_ID": JSON.stringify(env.PONTIVE_CLIENT_ID ?? "") },
758
+ };
759
+ },
760
+ };
761
+ }
762
+ `;
763
+ return {
764
+ packages: ["@pontive/pontkit-react", "@pontive/pontkit-loader"],
765
+ appType: "spa",
766
+ redirectUris: ["http://localhost/", "http://127.0.0.1/"],
767
+ files: [
768
+ { path: `${base}pontive.${ts ? "tsx" : "jsx"}`, contents: provider },
769
+ { path: `vite.pontive.${ts ? "ts" : "js"}`, contents: plugin }
770
+ ],
771
+ nextSteps: [
772
+ 'Add the plugin to vite.config: import { pontive } from "./vite.pontive"; plugins: [react(), pontive()].',
773
+ `Wrap the app in <PontiveProvider> from ./${base}pontive in your entry file.`
774
+ ]
775
+ };
776
+ }
777
+ function nodeModule(ts, esm) {
778
+ const t = (typed, plain = "") => ts ? typed : plain;
779
+ const exp = esm ? "export " : "";
780
+ const imports = esm ? `import { createServerAuth${t(", type Session")} } from "@pontive/pontkit-server";
781
+ ${t('import type { IncomingMessage, ServerResponse } from "node:http";\n')}` : `const { createServerAuth } = require("@pontive/pontkit-server");
782
+ `;
783
+ const body = `${imports}
784
+ // ${HEADER}
785
+ // Node 20.12 and later load .env.local here; earlier, start with
786
+ // node --env-file=.env.local.
787
+ try {
788
+ ${t("(process as unknown as { loadEnvFile?: (path: string) => void })", "process")}.loadEnvFile?.(".env.local");
789
+ } catch {
790
+ // No .env.local: the variables come from the environment.
791
+ }
792
+
793
+ ${exp}const pontive = createServerAuth({
794
+ issuer: process.env.PONTIVE_ISSUER${t("!")},
795
+ clientId: process.env.PONTIVE_CLIENT_ID${t("!")},
796
+ clientSecret: process.env.PONTIVE_CLIENT_SECRET,
797
+ sessionSecret: process.env.PONTIVE_SESSION_SECRET,
798
+ });
799
+ ${t("\ntype Next = (error?: unknown) => void;\n")}
800
+ function toRequest(req${t(": IncomingMessage")})${t(": Request")} {
801
+ const headers = new Headers();
802
+ for (const [name, value] of Object.entries(req.headers)) {
803
+ for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(name, v);
804
+ }
805
+ return new Request(new URL(req.url ?? "/", \`http://\${req.headers.host ?? "localhost"}\`), { method: req.method, headers });
806
+ }
807
+
808
+ async function send(res${t(": ServerResponse")}, response${t(": Response")})${t(": Promise<void>")} {
809
+ res.statusCode = response.status;
810
+ response.headers.forEach((value, name) => {
811
+ if (name !== "set-cookie") res.setHeader(name, value);
812
+ });
813
+ const cookies = response.headers.getSetCookie();
814
+ if (cookies.length > 0) res.setHeader("set-cookie", cookies);
815
+ res.end(Buffer.from(await response.arrayBuffer()));
816
+ }
817
+
818
+ /** Answers Pontive's sign-in routes: /api/auth/login, /api/auth/callback, /api/auth/logout. True when it did. */
819
+ ${exp}async function handlePontive(req${t(": IncomingMessage")}, res${t(": ServerResponse")})${t(": Promise<boolean>")} {
820
+ const response = await pontive.handle(toRequest(req));
821
+ if (!response) return false;
822
+ await send(res, response);
823
+ return true;
824
+ }
825
+
826
+ /** Express: app.use(pontiveRoutes) serves the sign-in routes. */
827
+ ${exp}function pontiveRoutes(req${t(": IncomingMessage")}, res${t(": ServerResponse")}, next${t(": Next")})${t(": void")} {
828
+ handlePontive(req, res).then((handled) => {
829
+ if (!handled) next();
830
+ }, next);
831
+ }
832
+
833
+ /** Express: app.use(pontiveSession) refreshes the session ahead of your routes and sets req.pontiveSession (null when signed out). */
834
+ ${exp}function pontiveSession(req${t(": IncomingMessage & { pontiveSession?: Session | null }")}, res${t(": ServerResponse")}, next${t(": Next")})${t(": void")} {
835
+ pontive.refresh(toRequest(req)).then((outcome) => {
836
+ for (const cookie of outcome.setCookies) res.appendHeader("set-cookie", cookie);
837
+ req.headers.cookie = outcome.cookieHeader;
838
+ req.pontiveSession = outcome.session;
839
+ next();
840
+ }, next);
841
+ }
842
+ ${esm ? "" : "\nmodule.exports = { pontive, handlePontive, pontiveRoutes, pontiveSession };\n"}`;
843
+ return body;
844
+ }
845
+ function node(project, express) {
846
+ const ts = project.typescript;
847
+ const esm = ts || project.esm;
848
+ const base = project.srcDir ? "src/" : "";
849
+ const path = `${base}pontive.${ts ? "ts" : "js"}`;
850
+ const importLine = esm ? `import { ${express ? "pontiveRoutes, pontiveSession" : "handlePontive, pontive"} } from "./pontive${ts ? "" : ".js"}"` : `const { ${express ? "pontiveRoutes, pontiveSession" : "handlePontive, pontive"} } = require("./pontive")`;
851
+ return {
852
+ packages: ["@pontive/pontkit-server"],
853
+ appType: "web",
854
+ files: [{ path, contents: nodeModule(ts, esm) }],
855
+ nextSteps: express ? [
856
+ `In your server: ${importLine}; then app.use(pontiveRoutes) and app.use(pontiveSession) before your routes.`,
857
+ "Sign in at /api/auth/login; req.pontiveSession is the signed-in session or null."
858
+ ] : [
859
+ `In your server: ${importLine}; start each request with if (await handlePontive(req, res)) return;`,
860
+ "Read the session with await pontive.getSession(req.headers.cookie). Sign in at /api/auth/login."
861
+ ]
862
+ };
863
+ }
864
+ function scaffoldPlan(project) {
865
+ switch (project.framework) {
866
+ case "nextjs":
867
+ return nextjs(project);
868
+ case "vite-react":
869
+ return viteReact(project);
870
+ case "express":
871
+ return node(project, true);
872
+ case "node":
873
+ return node(project, false);
874
+ }
875
+ }
876
+ function writeScaffold(cwd, files) {
877
+ const result = { written: [], skipped: [] };
878
+ for (const file of files) {
879
+ const target = join(cwd, file.path);
880
+ const blocker = [file.path, ...file.unlessExists ?? []].find((p) => existsSync(join(cwd, p)));
881
+ if (blocker) {
882
+ result.skipped.push({ path: file.path, reason: `${blocker} exists`, ...file.manual ? { manual: file.manual } : {} });
883
+ continue;
884
+ }
885
+ mkdirSync(dirname(target), { recursive: true });
886
+ writeFileSync(target, file.contents);
887
+ result.written.push(file.path);
888
+ }
889
+ return result;
890
+ }
891
+ function option(ctx, name) {
892
+ const value = ctx.values[name];
893
+ return typeof value === "string" && value !== "" ? value : void 0;
894
+ }
895
+ function frameworkOption(ctx) {
896
+ const value = option(ctx, "framework");
897
+ if (value === void 0) return void 0;
898
+ if (!FRAMEWORKS.includes(value)) {
899
+ throw new CliError("invalid_arguments", `--framework must be one of ${FRAMEWORKS.join(", ")}.`);
900
+ }
901
+ return value;
902
+ }
903
+ function tenancyOption(ctx) {
904
+ const value = option(ctx, "tenancy-mode");
905
+ if (value === void 0) return void 0;
906
+ if (value !== "b2b" && value !== "b2c") throw new CliError("invalid_arguments", "--tenancy-mode must be b2b or b2c.");
907
+ return value;
908
+ }
909
+ function regionOfKey(secretKey2) {
910
+ return secretKey2 ? /^pontive_sk_[a-z]+_([a-z0-9]+)_/.exec(secretKey2)?.[1] : void 0;
911
+ }
912
+ async function install(ctx, project, plan) {
913
+ const missing = plan.packages.filter((p) => !isInstalled(project, p));
914
+ if (missing.length === 0 || ctx.values["skip-install"] === true) return [];
915
+ const [command2, args] = installCommand(project.packageManager, missing);
916
+ ctx.out.info(`Installing ${missing.join(", ")} with ${project.packageManager}…`);
917
+ const code2 = await ctx.exec(command2, args, { cwd: ctx.cwd });
918
+ if (code2 !== 0) {
919
+ throw new CliError("install_failed", `${command2} ${args.join(" ")} failed (exit ${code2}). Install it yourself and run pontive init --skip-install.`);
920
+ }
921
+ return missing;
922
+ }
923
+ async function provision(ctx, project, plan) {
924
+ const key = await ephemeralKey();
925
+ const region = option(ctx, "region") ?? ctx.env.PONTIVE_REGION;
926
+ const tenancy = tenancyOption(ctx);
927
+ const body = {
928
+ name: option(ctx, "name") ?? projectName(project),
929
+ ...region ? { region } : {},
930
+ ...tenancy ? { tenancy_mode: tenancy } : {},
931
+ app: { type: plan.appType, ...plan.redirectUris ? { redirect_uris: plan.redirectUris } : {} },
932
+ encryption_key: key.publicJwk,
933
+ client: { name: "pontive-cli", version: ctx.version, ...ctx.agent ? { agent: ctx.agent } : {} }
934
+ };
935
+ ctx.out.info("Creating an unclaimed development instance…");
936
+ const response = await apiFor(ctx).provision(body, randomUUID());
937
+ let secrets;
938
+ if (response.encrypted_secrets) {
939
+ secrets = await decryptSecrets(response.encrypted_secrets, key);
940
+ } else if (response.secret_key && response.claim_token) {
941
+ secrets = { secret_key: response.secret_key, claim_token: response.claim_token, ...response.client_secret ? { client_secret: response.client_secret } : {} };
942
+ } else {
943
+ throw new CliError("invalid_response", "Pontive answered without the instance's secrets.");
944
+ }
945
+ if (plan.appType === "web" && !secrets.client_secret) {
946
+ throw new CliError("invalid_response", "Pontive answered a web app without its client secret.");
947
+ }
948
+ return { response, secrets };
949
+ }
950
+ const REPLACED_ON_RESET = /* @__PURE__ */ new Set(["PONTIVE_ISSUER", "PONTIVE_CLIENT_ID", "PONTIVE_CLIENT_SECRET", "PONTIVE_SECRET_KEY", "PONTIVE_INSTANCE_ID"]);
951
+ function envEntries(response, secrets) {
952
+ return [
953
+ ["PONTIVE_ISSUER", response.issuer],
954
+ ["PONTIVE_CLIENT_ID", response.app_id],
955
+ ...secrets.client_secret ? [["PONTIVE_CLIENT_SECRET", secrets.client_secret]] : [],
956
+ ...secrets.client_secret ? [["PONTIVE_SESSION_SECRET", sessionSecret()]] : [],
957
+ ["PONTIVE_SECRET_KEY", secrets.secret_key],
958
+ ["PONTIVE_INSTANCE_ID", response.instance_id]
959
+ ];
960
+ }
961
+ async function connectMcp(ctx, secretKey2, region, nextSteps2) {
962
+ if (ctx.values["no-mcp"] === true || !secretKey2 || !region) return null;
963
+ const requested = option(ctx, "mcp");
964
+ if (requested !== void 0 && !isMcpAgent(requested)) {
965
+ throw new CliError("invalid_arguments", `--mcp must be one of ${MCP_AGENTS.join(", ")}.`);
966
+ }
967
+ const agent = requested ?? (isMcpAgent(ctx.agent) ? ctx.agent : agentFromProject(ctx.cwd));
968
+ if (!agent) return null;
969
+ const url = mcpUrl(apiBaseUrl$1(ctx.env), region, ctx.env);
970
+ const file = mcpConfigFile(agent);
971
+ if (!file) {
972
+ nextSteps2.push(mcpManualStep(agent, url));
973
+ return { agent, written: false, url, reason: "no project-level config for this agent" };
974
+ }
975
+ 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)?`);
976
+ if (!consent) {
977
+ nextSteps2.push(ctx.agentMode ? `Run pontive init --yes to write the Pontive MCP server to ${file}.` : mcpManualStep(agent, url));
978
+ return { agent, written: false, file, url, reason: ctx.agentMode ? "needs --yes" : "declined" };
979
+ }
980
+ const result = writeMcpConfig(ctx.cwd, agent, url, secretKey2);
981
+ if (!result.written) {
982
+ nextSteps2.push(result.manual);
983
+ return { agent, written: false, file: result.file, url, reason: result.reason };
984
+ }
985
+ nextSteps2.push(`Restart ${agent} to load the Pontive MCP server from ${file}.`);
986
+ return { agent, written: true, file, url };
987
+ }
988
+ async function run$2(ctx) {
989
+ const reset = ctx.values.reset === true;
990
+ const project = detectProject(ctx.cwd, frameworkOption(ctx));
991
+ const plan = scaffoldPlan(project);
992
+ const nextSteps2 = [...plan.nextSteps];
993
+ if (reset && !await confirm(ctx, "Provision a new unclaimed instance and point .env.local at it? The current instance is left to expire.")) {
994
+ throw cancelled(ctx.agentMode ? "init --reset provisions a new instance; pass --yes to confirm." : "Cancelled.");
995
+ }
996
+ const existing = readKeyless(ctx.cwd);
997
+ if (!reset && existing?.claim_token && isExpired(existing, ctx.now())) {
998
+ throw new CliError(
999
+ "instance_expired",
1000
+ `The unclaimed instance ${existing.instance_id} expired on ${humanDate(existing.expires_at)}, with its users. Run pontive init --reset for a new one.`,
1001
+ ExitCode.ExpiredOrClaimedAway,
1002
+ { instance_id: existing.instance_id }
1003
+ );
1004
+ }
1005
+ const installed = await install(ctx, project, plan);
1006
+ const files = writeScaffold(ctx.cwd, plan.files);
1007
+ for (const skipped of files.skipped) if (skipped.manual) nextSteps2.push(skipped.manual);
1008
+ const gitignore = ensureGitignore(ctx.cwd, [ENV_FILE, `${PONTIVE_DIR}/`]);
1009
+ const envFile = readEnvFile(ctx.cwd);
1010
+ const configuredIssuer = envFile.get("PONTIVE_ISSUER") || ctx.env.PONTIVE_ISSUER;
1011
+ let instance;
1012
+ let env = { added: [], kept: [], replaced: [] };
1013
+ let secretKey2 = envFile.get("PONTIVE_SECRET_KEY") || ctx.env.PONTIVE_SECRET_KEY;
1014
+ if (!reset && existing) {
1015
+ instance = {
1016
+ status: "reused",
1017
+ instance_id: existing.instance_id,
1018
+ region: existing.region,
1019
+ issuer: existing.issuer,
1020
+ app_id: existing.app_id,
1021
+ ...existing.claim_token ? { expires_at: existing.expires_at } : { claimed: true }
1022
+ };
1023
+ } else if (!reset && configuredIssuer) {
1024
+ instance = { status: "configured", issuer: configuredIssuer, ...envFile.get("PONTIVE_INSTANCE_ID") ? { instance_id: envFile.get("PONTIVE_INSTANCE_ID") } : {}, region: regionOfKey(secretKey2) };
1025
+ } else {
1026
+ const login = await loadLogin(ctx.env);
1027
+ if (login) throw new CliError("not_supported", "Signed-in init is not supported by this version of the CLI.");
1028
+ const provisioned = await withKeylessLock(ctx.cwd, { sleep: ctx.sleep, signal: ctx.signal }, async () => {
1029
+ const raced = reset ? null : readKeyless(ctx.cwd);
1030
+ if (raced) return { kind: "raced", keyless: raced };
1031
+ const { response, secrets } = await provision(ctx, project, plan);
1032
+ const keyless = {
1033
+ instance_id: response.instance_id,
1034
+ issuer: response.issuer,
1035
+ app_id: response.app_id,
1036
+ claim_token: secrets.claim_token,
1037
+ expires_at: response.expires_at,
1038
+ region: response.region
1039
+ };
1040
+ writeKeyless(ctx.cwd, keyless);
1041
+ const written = writeEnv(ctx.cwd, envEntries(response, secrets), reset ? REPLACED_ON_RESET : /* @__PURE__ */ new Set());
1042
+ return { kind: "new", keyless, env: written, secretKey: secrets.secret_key };
1043
+ });
1044
+ const k = provisioned.keyless;
1045
+ instance = {
1046
+ status: provisioned.kind === "new" ? "provisioned" : "reused",
1047
+ instance_id: k.instance_id,
1048
+ region: k.region,
1049
+ issuer: k.issuer,
1050
+ app_id: k.app_id,
1051
+ expires_at: k.expires_at
1052
+ };
1053
+ if (provisioned.kind === "new") {
1054
+ env = provisioned.env;
1055
+ secretKey2 = provisioned.secretKey;
1056
+ if (env.kept.length > 0) ctx.out.warn(`${ENV_FILE} already set ${env.kept.join(", ")}; those lines were left as they were.`);
1057
+ }
1058
+ }
1059
+ const mcp = await connectMcp(ctx, secretKey2, instance.region, nextSteps2);
1060
+ if (instance.expires_at) nextSteps2.push(`Claim the instance before ${humanDate(instance.expires_at)} to keep it: npx pontive claim`);
1061
+ const human = [
1062
+ `Pontive is set up for ${project.framework} (${project.packageManager}).`,
1063
+ ...installed.length > 0 ? [`Installed ${installed.join(", ")}.`] : [],
1064
+ ...files.written.map((f) => `Wrote ${f}`),
1065
+ ...files.skipped.map((s) => `Skipped ${s.path}: ${s.reason}`),
1066
+ ...env.added.length + env.replaced.length > 0 ? [`Wrote ${[...env.added, ...env.replaced].join(", ")} to ${ENV_FILE}`] : [],
1067
+ ...instance.status === "provisioned" ? [`Wrote ${KEYLESS_FILE} (keep it private: it holds the claim token)`] : [],
1068
+ ...gitignore.length > 0 ? [`Added ${gitignore.join(", ")} to .gitignore`] : [],
1069
+ ...mcp?.written ? [`Wrote the Pontive MCP server to ${mcp.file}`] : [],
1070
+ "",
1071
+ 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 : ""}.`,
1072
+ ...instance.expires_at ? [
1073
+ "",
1074
+ ...box([
1075
+ `Unclaimed development instance. Pontive deletes it on ${humanDate(instance.expires_at)},`,
1076
+ "with its users. Run npx pontive claim to keep it."
1077
+ ])
1078
+ ] : [],
1079
+ "",
1080
+ "Next:",
1081
+ ...nextSteps2.map((s) => ` - ${s}`)
1082
+ ];
1083
+ return {
1084
+ data: {
1085
+ framework: project.framework,
1086
+ package_manager: project.packageManager,
1087
+ installed,
1088
+ files,
1089
+ gitignore,
1090
+ instance,
1091
+ env: { added: env.added, kept: env.kept, replaced: env.replaced },
1092
+ mcp,
1093
+ next_steps: nextSteps2
1094
+ },
1095
+ human
1096
+ };
1097
+ }
1098
+ const command$1 = {
1099
+ name: "init",
1100
+ summary: "Add Pontive sign-in to this app, creating an unclaimed development instance when you have no account",
1101
+ help: `Detects the framework (Next.js, Vite + React, Express, plain Node), installs the
1102
+ matching pontkit package, writes the auth route and middleware, and, signed out,
1103
+ creates an unclaimed development instance: its settings go to ${ENV_FILE}, its
1104
+ claim token to ${KEYLESS_FILE}, both gitignored. It lasts 7 days unless claimed
1105
+ (pontive claim). Existing files and ${ENV_FILE} lines are never overwritten.
1106
+
1107
+ Options:
1108
+ --reset Create a new unclaimed instance and point ${ENV_FILE} at it (asks first; --yes)
1109
+ --framework <name> ${FRAMEWORKS.join(" | ")} (default: detected)
1110
+ --region <region> us, eu or au (default: PONTIVE_REGION, else nearest)
1111
+ --name <name> The project's name (default: from package.json)
1112
+ --tenancy-mode <mode> b2c (default) or b2b
1113
+ --skip-install Do not install the pontkit package
1114
+ --mcp <agent> Connect this agent to Pontive's MCP server: ${MCP_AGENTS.join(", ")}
1115
+ --no-mcp Do not offer to connect an agent
1116
+
1117
+ Environment: PONTIVE_API_URL (default https://api.pontive.com), PONTIVE_REGION.`,
1118
+ options: {
1119
+ reset: { type: "boolean" },
1120
+ framework: { type: "string" },
1121
+ region: { type: "string" },
1122
+ name: { type: "string" },
1123
+ "tenancy-mode": { type: "string" },
1124
+ "skip-install": { type: "boolean" },
1125
+ mcp: { type: "string" },
1126
+ "no-mcp": { type: "boolean" }
1127
+ },
1128
+ run: run$2
1129
+ };
1130
+ const __vite_glob_0_1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1131
+ __proto__: null,
1132
+ command: command$1
1133
+ }, Symbol.toStringTag, { value: "Module" }));
1134
+ const KEY_PATTERN = /^pontive_sk_(live|test)_([a-z0-9-]+)_/;
1135
+ function apiBaseUrl(env, key) {
1136
+ const override = env.PONTIVE_MGMT_URL?.trim();
1137
+ if (override) return override.replace(/\/+$/, "").replace(/\/v1$/, "");
1138
+ const match = KEY_PATTERN.exec(key);
1139
+ if (!match) {
1140
+ throw new CliError(
1141
+ "secret_key_invalid",
1142
+ "PONTIVE_SECRET_KEY is not a Pontive secret key (pontive_sk_live_… or pontive_sk_test_…). Set PONTIVE_MGMT_URL to call another API."
1143
+ );
1144
+ }
1145
+ return `https://api.${match[2]}.pontive.com`;
1146
+ }
1147
+ function secretKey(env) {
1148
+ const key = env.PONTIVE_SECRET_KEY?.trim();
1149
+ if (!key) {
1150
+ throw new CliError(
1151
+ "secret_key_required",
1152
+ "Set PONTIVE_SECRET_KEY to the instance's secret key (dashboard, API keys). It is read from the environment only, never from a flag."
1153
+ );
1154
+ }
1155
+ return key;
1156
+ }
1157
+ class PontiveApi2 {
1158
+ constructor(baseUrl, key, options2) {
1159
+ this.baseUrl = baseUrl;
1160
+ this.key = key;
1161
+ this.options = options2;
1162
+ }
1163
+ baseUrl;
1164
+ key;
1165
+ options;
1166
+ static fromEnv(env, options2) {
1167
+ const key = secretKey(env);
1168
+ return new PontiveApi2(apiBaseUrl(env, key), key, options2);
1169
+ }
1170
+ async request(method, path, body) {
1171
+ const retries = this.options.retries ?? 5;
1172
+ for (let attempt = 0; ; attempt++) {
1173
+ let response;
1174
+ try {
1175
+ response = await this.options.fetch(`${this.baseUrl}${path}`, {
1176
+ method,
1177
+ headers: {
1178
+ authorization: `Bearer ${this.key}`,
1179
+ accept: "application/json",
1180
+ ...body === void 0 ? {} : { "content-type": "application/json" }
1181
+ },
1182
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1183
+ signal: this.options.signal
1184
+ });
1185
+ } catch (error) {
1186
+ if (this.options.signal?.aborted) throw error;
1187
+ if (attempt < retries) {
1188
+ this.options.onRetry?.(`Network error calling ${method} ${path}; retrying.`);
1189
+ await this.options.sleep(backoff(attempt), this.options.signal);
1190
+ continue;
1191
+ }
1192
+ throw new CliError("network_error", `Could not reach ${this.baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
1193
+ }
1194
+ if (response.ok) {
1195
+ if (response.status === 204) return void 0;
1196
+ return await response.json();
1197
+ }
1198
+ const retryable = response.status === 429 || response.status === 502 || response.status === 503 || response.status === 504;
1199
+ const retryAfter = Number(response.headers.get("retry-after"));
1200
+ if (retryable && attempt < retries) {
1201
+ const wait = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1e3 : backoff(attempt);
1202
+ this.options.onRetry?.(`${method} ${path} answered ${response.status}; retrying in ${Math.ceil(wait / 1e3)}s.`);
1203
+ await this.options.sleep(wait, this.options.signal);
1204
+ continue;
1205
+ }
1206
+ throw await apiError(response, method, path, Number.isFinite(retryAfter) ? retryAfter : void 0);
1207
+ }
1208
+ }
1209
+ createRun(input) {
1210
+ return this.request("POST", "/v1/user-imports", input);
1211
+ }
1212
+ getRun(id) {
1213
+ return this.request("GET", `/v1/user-imports/${encodeURIComponent(id)}`);
1214
+ }
1215
+ listRuns(page = 1, limit = 20) {
1216
+ return this.request("GET", `/v1/user-imports?page=${page}&limit=${limit}`);
1217
+ }
1218
+ listRecords(id, query) {
1219
+ const params = new URLSearchParams({ page: String(query.page), limit: String(query.limit) });
1220
+ if (query.outcome) params.set("outcome", query.outcome);
1221
+ if (query.kind) params.set("kind", query.kind);
1222
+ return this.request("GET", `/v1/user-imports/${encodeURIComponent(id)}/records?${params}`);
1223
+ }
1224
+ importUsers(runId, users2, dryRun) {
1225
+ return this.request("POST", "/v1/users/import", { user_import_id: runId, dry_run: dryRun, users: users2 });
1226
+ }
1227
+ importOrganizations(runId, organizations, dryRun) {
1228
+ return this.request("POST", "/v1/organizations/import", { user_import_id: runId, dry_run: dryRun, organizations });
1229
+ }
1230
+ revert(id, dryRun) {
1231
+ return this.request("POST", `/v1/user-imports/${encodeURIComponent(id)}/revert`, { dry_run: dryRun });
1232
+ }
1233
+ listSources(page = 1, limit = 100) {
1234
+ return this.request("GET", `/v1/authn/migration-sources?page=${page}&limit=${limit}`);
1235
+ }
1236
+ getSource(id) {
1237
+ return this.request("GET", `/v1/authn/migration-sources/${encodeURIComponent(id)}`);
1238
+ }
1239
+ createSource(input) {
1240
+ return this.request("POST", "/v1/authn/migration-sources", input);
1241
+ }
1242
+ updateSource(id, input) {
1243
+ return this.request("PATCH", `/v1/authn/migration-sources/${encodeURIComponent(id)}`, input);
1244
+ }
1245
+ deleteSource(id) {
1246
+ return this.request("DELETE", `/v1/authn/migration-sources/${encodeURIComponent(id)}`);
1247
+ }
1248
+ validateSource(id, input) {
1249
+ return this.request("POST", `/v1/authn/migration-sources/${encodeURIComponent(id)}/validate`, input);
1250
+ }
1251
+ }
1252
+ function backoff(attempt) {
1253
+ return Math.min(3e4, 1e3 * 2 ** attempt);
1254
+ }
1255
+ async function apiError(response, method, path, retryAfter) {
1256
+ let envelope = {};
1257
+ try {
1258
+ envelope = await response.json();
1259
+ } catch {
1260
+ }
1261
+ const code2 = envelope.error?.code ?? `http_${response.status}`;
1262
+ const message = envelope.error?.message ?? response.statusText ?? "Request failed";
1263
+ const extra = { status: response.status };
1264
+ if (envelope.error?.param) extra.param = envelope.error.param;
1265
+ if (envelope.error?.details?.length) extra.details = envelope.error.details;
1266
+ if (response.status === 429) {
1267
+ return new CliError(code2, `${message} (${method} ${path}, 429)`, ExitCode.RateLimited, { ...extra, retry_after: retryAfter ?? null });
1268
+ }
1269
+ return new CliError(code2, `${message} (${method} ${path}, ${response.status})`, ExitCode.Error, extra);
1270
+ }
1271
+ const FORMAT = "pontive-users/v1";
1272
+ function parseLine(text, lineNumber) {
1273
+ const trimmed = text.trim();
1274
+ if (trimmed === "") return void 0;
1275
+ let value;
1276
+ try {
1277
+ value = JSON.parse(trimmed);
1278
+ } catch {
1279
+ throw invalid(lineNumber, "is not valid JSON");
1280
+ }
1281
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalid(lineNumber, "is not a JSON object");
1282
+ const { kind, ...rest } = value;
1283
+ if (kind === void 0 && "format" in rest) {
1284
+ if (lineNumber !== 1) throw invalid(lineNumber, "is a header, which may only be the first line");
1285
+ if (rest.format !== FORMAT) throw invalid(lineNumber, `names format ${JSON.stringify(rest.format)}; this CLI reads ${FORMAT}`);
1286
+ return { kind: "header", header: rest };
1287
+ }
1288
+ switch (kind) {
1289
+ case "user":
1290
+ return { kind: "user", user: rest };
1291
+ case "organization":
1292
+ if (typeof rest.external_id !== "string" || rest.external_id === "") throw invalid(lineNumber, "is an organization without external_id");
1293
+ if (!Array.isArray(rest.members)) rest.members = [];
1294
+ return { kind: "organization", organization: rest };
1295
+ case "summary":
1296
+ return { kind: "summary", summary: rest };
1297
+ default:
1298
+ throw invalid(lineNumber, `has kind ${JSON.stringify(kind)}; expected "user", "organization" or "summary"`);
1299
+ }
1300
+ }
1301
+ function invalid(lineNumber, what) {
1302
+ return new CliError("invalid_file", `Line ${lineNumber} ${what}.`);
1303
+ }
1304
+ function formatLine(line) {
1305
+ switch (line.kind) {
1306
+ case "header":
1307
+ return JSON.stringify(line.header);
1308
+ case "user":
1309
+ return JSON.stringify({ kind: "user", ...line.user });
1310
+ case "organization":
1311
+ return JSON.stringify({ kind: "organization", ...line.organization });
1312
+ case "summary":
1313
+ return JSON.stringify({ kind: "summary", ...line.summary });
1314
+ }
1315
+ }
1316
+ async function* readLines(path) {
1317
+ const stream = createReadStream(path, { encoding: "utf8" });
1318
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
1319
+ let n = 0;
1320
+ try {
1321
+ for await (const text of rl) {
1322
+ n++;
1323
+ const line = parseLine(text, n);
1324
+ if (line) yield line;
1325
+ }
1326
+ } finally {
1327
+ rl.close();
1328
+ stream.destroy();
1329
+ }
1330
+ }
1331
+ async function fingerprint(path) {
1332
+ const hash = createHash("sha256");
1333
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
1334
+ return hash.digest("hex");
1335
+ }
1336
+ class FileWriter {
1337
+ stream;
1338
+ failure;
1339
+ constructor(path, overwrite) {
1340
+ this.stream = createWriteStream(path, { flags: overwrite ? "w" : "wx", mode: 384, encoding: "utf8" });
1341
+ this.stream.on("error", (error) => {
1342
+ this.failure = error;
1343
+ });
1344
+ }
1345
+ async write(line) {
1346
+ if (this.failure) throw this.failure;
1347
+ if (!this.stream.write(`${formatLine(line)}
1348
+ `)) {
1349
+ await new Promise((resolve2, reject) => {
1350
+ this.stream.once("drain", resolve2);
1351
+ this.stream.once("error", reject);
1352
+ });
1353
+ }
1354
+ }
1355
+ async close() {
1356
+ await new Promise((resolve2, reject) => {
1357
+ this.stream.end((error) => error ? reject(error) : resolve2());
1358
+ });
1359
+ if (this.failure) throw this.failure;
1360
+ }
1361
+ }
1362
+ const KEYS_PER_REASON = 100;
1363
+ class ExportStats {
1364
+ users = 0;
1365
+ organizations = 0;
1366
+ members = 0;
1367
+ passwordUsersWithoutHash = 0;
1368
+ /** Users left out of the file, by reason (`email_required`, …). */
1369
+ skippedUsers = /* @__PURE__ */ new Map();
1370
+ /** Identities left out of the file, by `reason:provider`. */
1371
+ skippedIdentities = /* @__PURE__ */ new Map();
1372
+ /** Users whose source had a TOTP factor that could not be exported: they enroll again. */
1373
+ totpNotExported = 0;
1374
+ notes = [];
1375
+ skipUser(reason, key) {
1376
+ const entry = this.skippedUsers.get(reason) ?? { count: 0, keys: [] };
1377
+ entry.count++;
1378
+ if (entry.keys.length < KEYS_PER_REASON) entry.keys.push(key);
1379
+ this.skippedUsers.set(reason, entry);
1380
+ }
1381
+ skipIdentity(reason, provider) {
1382
+ const id = `${reason}:${provider}`;
1383
+ this.skippedIdentities.set(id, (this.skippedIdentities.get(id) ?? 0) + 1);
1384
+ }
1385
+ summary() {
1386
+ return { users: this.users, organizations: this.organizations, password_users_without_hash: this.passwordUsersWithoutHash };
1387
+ }
1388
+ toJSON() {
1389
+ return {
1390
+ users: this.users,
1391
+ organizations: this.organizations,
1392
+ members: this.members,
1393
+ password_users_without_hash: this.passwordUsersWithoutHash,
1394
+ totp_not_exported: this.totpNotExported,
1395
+ skipped_users: Object.fromEntries(this.skippedUsers),
1396
+ skipped_identities: Object.fromEntries(this.skippedIdentities),
1397
+ notes: this.notes
1398
+ };
1399
+ }
1400
+ }
1401
+ function identity(stats, provider, type, providerUserId, email) {
1402
+ if (type === void 0) {
1403
+ stats.skipIdentity("unsupported", provider);
1404
+ return void 0;
1405
+ }
1406
+ if (type === "not_portable" || type === "microsoft" || type === "entra") {
1407
+ stats.skipIdentity("not_portable", provider);
1408
+ return void 0;
1409
+ }
1410
+ if (providerUserId === void 0 || providerUserId === null || providerUserId === "") return void 0;
1411
+ return {
1412
+ connection_type: type,
1413
+ // GitHub's id is a number in some sources' JSON.
1414
+ provider_user_id: String(providerUserId),
1415
+ ...typeof email === "string" && email !== "" ? { email } : {}
1416
+ };
1417
+ }
1418
+ function externalIdMode(flags) {
1419
+ const value = flags["external-id"];
1420
+ if (value === void 0 || value === "legacy") return "legacy";
1421
+ if (value === "none") return "none";
1422
+ throw new CliError("invalid_arguments", `--external-id is legacy or none; got "${String(value)}".`);
1423
+ }
1424
+ function compact(value) {
1425
+ const out = {};
1426
+ for (const [k, v] of Object.entries(value)) {
1427
+ if (v === void 0 || v === null || v === "") continue;
1428
+ if (Array.isArray(v) && v.length === 0) continue;
1429
+ if (typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0) continue;
1430
+ out[k] = v;
1431
+ }
1432
+ return out;
1433
+ }
1434
+ function isoDate(value) {
1435
+ if (value === void 0 || value === null || value === "") return void 0;
1436
+ const date = value instanceof Date ? value : new Date(value);
1437
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
1438
+ }
1439
+ function object(value) {
1440
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1441
+ }
1442
+ function str(value) {
1443
+ return typeof value === "string" && value !== "" ? value : void 0;
1444
+ }
1445
+ function requireEmail(stats, user, key) {
1446
+ if (user.email) return true;
1447
+ stats.skipUser("email_required", key);
1448
+ return false;
1449
+ }
1450
+ async function loadOptional(cwd, specifier, install2) {
1451
+ try {
1452
+ return await import(
1453
+ /* @vite-ignore */
1454
+ specifier
1455
+ );
1456
+ } catch (error) {
1457
+ if (!isNotFound(error)) throw error;
1458
+ }
1459
+ try {
1460
+ const resolved = createRequire(join(cwd, "package.json")).resolve(specifier);
1461
+ return await import(
1462
+ /* @vite-ignore */
1463
+ pathToFileURL(resolved).href
1464
+ );
1465
+ } catch (error) {
1466
+ if (!isNotFound(error)) throw error;
1467
+ }
1468
+ throw new CliError(
1469
+ "dependency_missing",
1470
+ `This exporter needs ${install2}, which pontive does not install by default. Run it with npx -p pontive -p ${install2} pontive migrate …, or npm install --no-save ${install2} in this directory.`,
1471
+ void 0,
1472
+ { install: `npm install --no-save ${install2}` }
1473
+ );
1474
+ }
1475
+ function isNotFound(error) {
1476
+ const code2 = error?.code;
1477
+ return code2 === "ERR_MODULE_NOT_FOUND" || code2 === "MODULE_NOT_FOUND";
1478
+ }
1479
+ function pick(mod, name) {
1480
+ const direct = mod[name];
1481
+ if (direct !== void 0) return direct;
1482
+ const fallback = object(mod.default)?.[name];
1483
+ if (fallback === void 0) throw new CliError("dependency_invalid", `The installed module does not export ${name}.`);
1484
+ return fallback;
1485
+ }
1486
+ function requireEnv(ctx, names, provider) {
1487
+ const missing = names.filter((n) => !ctx.env[n]?.trim());
1488
+ if (missing.length > 0) {
1489
+ throw new CliError("provider_credentials_required", `The ${provider} exporter reads ${names.join(", ")} from the environment; ${missing.join(", ")} not set.`);
1490
+ }
1491
+ return names.map((n) => ctx.env[n].trim());
1492
+ }
1493
+ async function fetchJson(ctx, url, init, what) {
1494
+ for (let attempt = 0; ; attempt++) {
1495
+ const response = await ctx.fetch(url, { ...init, signal: ctx.signal });
1496
+ if (response.ok) return await response.json();
1497
+ const retryable = response.status === 429 || response.status >= 500;
1498
+ if (retryable && attempt < 6) {
1499
+ const after = Number(response.headers.get("retry-after"));
1500
+ const wait = Number.isFinite(after) && after > 0 ? after * 1e3 : Math.min(3e4, 1e3 * 2 ** attempt);
1501
+ ctx.info(`${what} answered ${response.status}; retrying in ${Math.ceil(wait / 1e3)}s.`);
1502
+ await ctx.sleep(wait, ctx.signal);
1503
+ continue;
1504
+ }
1505
+ let detail = "";
1506
+ try {
1507
+ const body = await response.json();
1508
+ const message = body.message ?? body.error_description ?? object(body.errors)?.message ?? (Array.isArray(body.errors) ? object(body.errors[0])?.message : void 0) ?? body.error;
1509
+ if (typeof message === "string") detail = `: ${message}`;
1510
+ } catch {
1511
+ }
1512
+ throw new CliError("provider_error", `${what} answered ${response.status}${detail}`, void 0, { status: response.status });
1513
+ }
1514
+ }
1515
+ function flagString(flags, name) {
1516
+ const value = flags[name];
1517
+ return typeof value === "string" && value !== "" ? value : void 0;
1518
+ }
1519
+ function flagStrings(flags, name) {
1520
+ const value = flags[name];
1521
+ if (value === void 0) return [];
1522
+ return (Array.isArray(value) ? value : [value]).filter((v) => typeof v === "string");
1523
+ }
1524
+ const FIELDS = [
1525
+ "user_id",
1526
+ "email",
1527
+ "email_verified",
1528
+ "phone_number",
1529
+ "phone_verified",
1530
+ "username",
1531
+ "name",
1532
+ "given_name",
1533
+ "family_name",
1534
+ "picture",
1535
+ "locale",
1536
+ "created_at",
1537
+ "blocked",
1538
+ "identities",
1539
+ "user_metadata",
1540
+ "app_metadata",
1541
+ "multifactor"
1542
+ ];
1543
+ const PROVIDERS$4 = {
1544
+ "google-oauth2": "google",
1545
+ github: "github",
1546
+ apple: "apple",
1547
+ oidc: "oidc",
1548
+ windowslive: "not_portable",
1549
+ waad: "not_portable"
1550
+ };
1551
+ const OWN$2 = /* @__PURE__ */ new Set(["auth0", "email", "sms"]);
1552
+ function mapAuth0User(user, hashes, stats, externalId) {
1553
+ const identities = user.identities ?? [];
1554
+ const isPasswordUser = identities.some((i) => i.provider === "auth0");
1555
+ const hash = hashes.get(user.user_id);
1556
+ const external = identities.filter((i) => !OWN$2.has(i.provider ?? "")).map((i) => identity(stats, i.provider ?? "unknown", PROVIDERS$4[i.provider ?? ""], i.user_id, i.profileData?.email)).filter((i) => i !== void 0);
1557
+ if (isPasswordUser && !hash) stats.passwordUsersWithoutHash++;
1558
+ if (user.multifactor?.includes("guardian") || user.multifactor?.includes("google-authenticator")) stats.totpNotExported++;
1559
+ const name = user.name && user.name !== user.email ? user.name : void 0;
1560
+ const row = compact({
1561
+ legacy_subject: user.user_id,
1562
+ external_id: externalId === "legacy" ? user.user_id : void 0,
1563
+ email: user.email,
1564
+ email_verified: user.email_verified,
1565
+ phone: user.phone_number,
1566
+ phone_verified: user.phone_number ? user.phone_verified : void 0,
1567
+ username: user.username,
1568
+ name,
1569
+ given_name: user.given_name,
1570
+ family_name: user.family_name,
1571
+ picture: user.picture,
1572
+ locale: user.locale,
1573
+ metadata: user.user_metadata,
1574
+ private_metadata: user.app_metadata,
1575
+ status: user.blocked ? "deactivated" : void 0,
1576
+ created_at: isoDate(user.created_at),
1577
+ password_hash: hash ? { hasher: "bcrypt", value: hash } : void 0,
1578
+ external_identities: external
1579
+ });
1580
+ return requireEmail(stats, row, user.user_id) ? row : void 0;
1581
+ }
1582
+ async function readAuth0Hashes(path) {
1583
+ const hashes = /* @__PURE__ */ new Map();
1584
+ const rl = createInterface({ input: createReadStream(path, { encoding: "utf8" }), crlfDelay: Infinity });
1585
+ let n = 0;
1586
+ for await (const text of rl) {
1587
+ n++;
1588
+ if (text.trim() === "") continue;
1589
+ let row;
1590
+ try {
1591
+ row = JSON.parse(text);
1592
+ } catch {
1593
+ throw new CliError("invalid_file", `--hashes line ${n} is not JSON. Decrypt the export (gpg --decrypt) before passing it.`);
1594
+ }
1595
+ const rawId = row._id;
1596
+ const id = typeof rawId === "string" ? rawId : str(object(rawId)?.$oid);
1597
+ const hash = str(row.passwordHash);
1598
+ if (!id || !hash || !/^\$2[aby]\$/.test(hash)) continue;
1599
+ hashes.set(id.includes("|") ? id : `auth0|${id}`, hash);
1600
+ }
1601
+ return hashes;
1602
+ }
1603
+ async function token(ctx, domain, clientId, clientSecret) {
1604
+ const answer = await fetchJson(
1605
+ ctx,
1606
+ `https://${domain}/oauth/token`,
1607
+ {
1608
+ method: "POST",
1609
+ headers: { "content-type": "application/json" },
1610
+ body: JSON.stringify({ grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret, audience: `https://${domain}/api/v2/` })
1611
+ },
1612
+ "Auth0 token"
1613
+ );
1614
+ return answer.access_token;
1615
+ }
1616
+ async function exportUsers(ctx, base, auth) {
1617
+ const connection = flagString(ctx.flags, "connection");
1618
+ const job = await fetchJson(
1619
+ ctx,
1620
+ `${base}/jobs/users-exports`,
1621
+ {
1622
+ method: "POST",
1623
+ headers: { ...auth, "content-type": "application/json" },
1624
+ body: JSON.stringify({ format: "json", fields: FIELDS.map((name) => ({ name })), ...connection ? { connection_id: connection } : {} })
1625
+ },
1626
+ "Auth0 users export"
1627
+ );
1628
+ ctx.info(`Auth0 export job ${job.id} started.`);
1629
+ let location;
1630
+ for (let attempt = 0; ; attempt++) {
1631
+ const status = await fetchJson(ctx, `${base}/jobs/${job.id}`, { headers: auth }, "Auth0 export job");
1632
+ if (status.status === "completed" && status.location) {
1633
+ location = status.location;
1634
+ break;
1635
+ }
1636
+ if (status.status === "failed") throw new CliError("provider_error", `Auth0 export job ${job.id} failed.`);
1637
+ if (attempt % 5 === 0) ctx.info(`Auth0 export job ${status.status}${status.percentage_done !== void 0 ? `, ${status.percentage_done}%` : ""}.`);
1638
+ await ctx.sleep(Math.min(1e4, 2e3 + attempt * 500), ctx.signal);
1639
+ }
1640
+ const response = await ctx.fetch(location, { signal: ctx.signal });
1641
+ if (!response.ok) throw new CliError("provider_error", `Downloading the Auth0 export answered ${response.status}.`);
1642
+ let bytes = Buffer.from(await response.arrayBuffer());
1643
+ if (bytes[0] === 31 && bytes[1] === 139) bytes = gunzipSync(bytes);
1644
+ const lines = bytes.toString("utf8").split("\n");
1645
+ return (async function* () {
1646
+ for (const line of lines) if (line.trim() !== "") yield JSON.parse(line);
1647
+ })();
1648
+ }
1649
+ async function* checkpoint(ctx, url, key, auth, what) {
1650
+ let from;
1651
+ do {
1652
+ const sep = url.includes("?") ? "&" : "?";
1653
+ const page = await fetchJson(ctx, `${url}${sep}take=100${from ? `&from=${encodeURIComponent(from)}` : ""}`, { headers: auth }, what);
1654
+ yield* page[key] ?? [];
1655
+ from = page.next;
1656
+ } while (from);
1657
+ }
1658
+ const auth0 = {
1659
+ provider: "auth0",
1660
+ sourceType: "auth0",
1661
+ summary: "Auth0 Management API (AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET); --hashes <file> merges support's password hash export",
1662
+ async run(ctx, emit, stats) {
1663
+ const [domain, clientId, clientSecret] = requireEnv(ctx, ["AUTH0_DOMAIN", "AUTH0_CLIENT_ID", "AUTH0_CLIENT_SECRET"], "auth0");
1664
+ const host = domain.replace(/^https?:\/\//, "").replace(/\/+$/, "");
1665
+ const base = `https://${host}/api/v2`;
1666
+ const mode = externalIdMode(ctx.flags);
1667
+ const hashesFile = flagString(ctx.flags, "hashes");
1668
+ const hashes = hashesFile ? await readAuth0Hashes(resolve(ctx.cwd, hashesFile)) : /* @__PURE__ */ new Map();
1669
+ if (hashesFile) ctx.info(`Read ${hashes.size} password hashes.`);
1670
+ else stats.notes.push("No --hashes file: Auth0 password users are exported without their hash and reset by email. Auth0 support provides the hash export on paid plans.");
1671
+ const auth = { authorization: `Bearer ${await token(ctx, host, clientId, clientSecret)}` };
1672
+ for await (const user of await exportUsers(ctx, base, auth)) {
1673
+ const row = mapAuth0User(user, hashes, stats, mode);
1674
+ if (!row) continue;
1675
+ stats.users++;
1676
+ await emit({ kind: "user", user: row });
1677
+ }
1678
+ if (ctx.flags["skip-organizations"]) return;
1679
+ for await (const org of checkpoint(
1680
+ ctx,
1681
+ `${base}/organizations`,
1682
+ "organizations",
1683
+ auth,
1684
+ "Auth0 organizations"
1685
+ )) {
1686
+ const members = [];
1687
+ for await (const member of checkpoint(
1688
+ ctx,
1689
+ `${base}/organizations/${encodeURIComponent(org.id)}/members?fields=user_id,roles&include_fields=true`,
1690
+ "members",
1691
+ auth,
1692
+ "Auth0 organization members"
1693
+ )) {
1694
+ members.push({ legacy_subject: member.user_id, roles: (member.roles ?? []).map((r) => r.name) });
1695
+ }
1696
+ stats.organizations++;
1697
+ stats.members += members.length;
1698
+ await emit({
1699
+ kind: "organization",
1700
+ organization: compact({ external_id: org.id, name: org.display_name ?? org.name, slug: org.name, metadata: org.metadata, members })
1701
+ });
1702
+ }
1703
+ }
1704
+ };
1705
+ function parseCsv(text) {
1706
+ const rows = [];
1707
+ let row = [];
1708
+ let field = "";
1709
+ let quoted = false;
1710
+ for (let i = 0; i < text.length; i++) {
1711
+ const c = text[i];
1712
+ if (quoted) {
1713
+ if (c === '"') {
1714
+ if (text[i + 1] === '"') {
1715
+ field += '"';
1716
+ i++;
1717
+ } else {
1718
+ quoted = false;
1719
+ }
1720
+ } else {
1721
+ field += c;
1722
+ }
1723
+ continue;
1724
+ }
1725
+ if (c === '"') quoted = true;
1726
+ else if (c === ",") {
1727
+ row.push(field);
1728
+ field = "";
1729
+ } else if (c === "\n" || c === "\r") {
1730
+ if (c === "\r" && text[i + 1] === "\n") i++;
1731
+ row.push(field);
1732
+ rows.push(row);
1733
+ row = [];
1734
+ field = "";
1735
+ } else {
1736
+ field += c;
1737
+ }
1738
+ }
1739
+ if (field !== "" || row.length > 0) {
1740
+ row.push(field);
1741
+ rows.push(row);
1742
+ }
1743
+ const [header, ...body] = rows.filter((r) => !(r.length === 1 && r[0] === ""));
1744
+ if (!header) return [];
1745
+ const keys = header.map((h) => h.trim().replace(/^/, ""));
1746
+ return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, r[i] ?? ""])));
1747
+ }
1748
+ const BASE = "https://api.clerk.com/v1";
1749
+ const PAGE$1 = 500;
1750
+ const PROVIDERS$3 = {
1751
+ google: "google",
1752
+ github: "github",
1753
+ apple: "apple",
1754
+ microsoft: "not_portable"
1755
+ };
1756
+ const HASHERS = {
1757
+ bcrypt: "bcrypt",
1758
+ argon2i: "argon2",
1759
+ argon2id: "argon2",
1760
+ bcrypt_sha256_django: "django",
1761
+ pbkdf2_sha256_django: "django",
1762
+ scrypt_werkzeug: "werkzeug",
1763
+ phpass: "wordpress",
1764
+ ldap_ssha: "ldap"
1765
+ };
1766
+ function mapClerkUser(user, csv, stats, externalId) {
1767
+ const email = user.email_addresses?.find((e) => e.id === user.primary_email_address_id) ?? user.email_addresses?.[0];
1768
+ const phone = user.phone_numbers?.find((p) => p.id === user.primary_phone_number_id);
1769
+ const secrets = csv.get(user.id);
1770
+ let passwordHash2;
1771
+ if (user.password_enabled) {
1772
+ const hasher = HASHERS[secrets?.password_hasher ?? ""];
1773
+ if (secrets?.password_digest && hasher) passwordHash2 = { hasher, value: secrets.password_digest };
1774
+ else stats.passwordUsersWithoutHash++;
1775
+ }
1776
+ let totp;
1777
+ if (user.totp_enabled) {
1778
+ if (secrets?.totp_secret) totp = { secret: secrets.totp_secret };
1779
+ else stats.totpNotExported++;
1780
+ }
1781
+ const external = (user.external_accounts ?? []).map((a) => {
1782
+ const provider = (a.provider ?? "").replace(/^oauth_/, "");
1783
+ const type = provider.startsWith("custom_") ? "oidc" : PROVIDERS$3[provider];
1784
+ return identity(stats, provider || "unknown", type, a.provider_user_id, a.email_address);
1785
+ }).filter((i) => i !== void 0);
1786
+ const name = [user.first_name, user.last_name].filter(Boolean).join(" ");
1787
+ const row = compact({
1788
+ legacy_subject: user.id,
1789
+ external_id: user.external_id ?? (externalId === "legacy" ? user.id : void 0),
1790
+ email: email?.email_address,
1791
+ email_verified: email ? email.verification?.status === "verified" : void 0,
1792
+ phone: phone?.phone_number,
1793
+ phone_verified: phone ? phone.verification?.status === "verified" : void 0,
1794
+ username: user.username ?? void 0,
1795
+ name: name || void 0,
1796
+ given_name: user.first_name ?? void 0,
1797
+ family_name: user.last_name ?? void 0,
1798
+ // Clerk answers a generated avatar for users without one.
1799
+ picture: user.has_image ? user.image_url ?? void 0 : void 0,
1800
+ metadata: user.public_metadata ?? void 0,
1801
+ private_metadata: user.private_metadata ?? void 0,
1802
+ status: user.banned ? "deactivated" : void 0,
1803
+ created_at: isoDate(user.created_at),
1804
+ password_hash: passwordHash2,
1805
+ totp,
1806
+ external_identities: external
1807
+ });
1808
+ return requireEmail(stats, row, user.id) ? row : void 0;
1809
+ }
1810
+ function readClerkCsv(text) {
1811
+ const rows = /* @__PURE__ */ new Map();
1812
+ for (const row of parseCsv(text)) {
1813
+ if (!row.id) continue;
1814
+ rows.set(row.id, { password_digest: row.password_digest || void 0, password_hasher: row.password_hasher || void 0, totp_secret: row.totp_secret || void 0 });
1815
+ }
1816
+ return rows;
1817
+ }
1818
+ async function* users(ctx, auth) {
1819
+ let after;
1820
+ for (; ; ) {
1821
+ const params = new URLSearchParams({ limit: String(PAGE$1), order_by: "+created_at" });
1822
+ if (after) params.set("starting_after", after);
1823
+ const page = await fetchJson(ctx, `${BASE}/users?${params}`, { headers: auth }, "Clerk users");
1824
+ yield* page;
1825
+ if (page.length < PAGE$1) return;
1826
+ after = page[page.length - 1].id;
1827
+ }
1828
+ }
1829
+ async function* offsetPages(ctx, url, auth, what) {
1830
+ for (let offset = 0; ; offset += PAGE$1) {
1831
+ const sep = url.includes("?") ? "&" : "?";
1832
+ const page = await fetchJson(ctx, `${url}${sep}limit=${PAGE$1}&offset=${offset}`, { headers: auth }, what);
1833
+ yield* page.data;
1834
+ if (page.data.length < PAGE$1 || offset + page.data.length >= page.total_count) return;
1835
+ }
1836
+ }
1837
+ const clerk = {
1838
+ provider: "clerk",
1839
+ sourceType: "clerk",
1840
+ summary: "Clerk Backend API (CLERK_SECRET_KEY); --csv <file> adds the dashboard export's password digests and TOTP secrets",
1841
+ async run(ctx, emit, stats) {
1842
+ const [secret] = requireEnv(ctx, ["CLERK_SECRET_KEY"], "clerk");
1843
+ const auth = { authorization: `Bearer ${secret}` };
1844
+ const mode = externalIdMode(ctx.flags);
1845
+ const csvFile = flagString(ctx.flags, "csv");
1846
+ const csv = csvFile ? readClerkCsv(await readFile(resolve(ctx.cwd, csvFile), "utf8")) : /* @__PURE__ */ new Map();
1847
+ if (!csvFile) {
1848
+ stats.notes.push(
1849
+ "No --csv: Clerk's Backend API returns no password digests or TOTP secrets. Export users from the Clerk dashboard and pass the CSV to keep passwords and TOTP."
1850
+ );
1851
+ }
1852
+ stats.notes.push("unsafe_metadata is not exported: users could write it, so it is not carried into Pontive.");
1853
+ for await (const user of users(ctx, auth)) {
1854
+ const row = mapClerkUser(user, csv, stats, mode);
1855
+ if (!row) continue;
1856
+ stats.users++;
1857
+ await emit({ kind: "user", user: row });
1858
+ }
1859
+ if (ctx.flags["skip-organizations"]) return;
1860
+ for await (const org of offsetPages(
1861
+ ctx,
1862
+ `${BASE}/organizations`,
1863
+ auth,
1864
+ "Clerk organizations"
1865
+ )) {
1866
+ const members = [];
1867
+ for await (const m of offsetPages(
1868
+ ctx,
1869
+ `${BASE}/organizations/${encodeURIComponent(org.id)}/memberships`,
1870
+ auth,
1871
+ "Clerk organization memberships"
1872
+ )) {
1873
+ const userId = object(m.public_user_data)?.user_id;
1874
+ if (typeof userId === "string") members.push({ legacy_subject: userId, roles: [m.role] });
1875
+ }
1876
+ stats.organizations++;
1877
+ stats.members += members.length;
1878
+ await emit({
1879
+ kind: "organization",
1880
+ organization: compact({ external_id: org.id, name: org.name, slug: org.slug, metadata: org.public_metadata ?? void 0, members })
1881
+ });
1882
+ }
1883
+ }
1884
+ };
1885
+ const PROVIDERS$2 = {
1886
+ Google: "google",
1887
+ SignInWithApple: "apple",
1888
+ OIDC: "oidc"
1889
+ };
1890
+ function mapCognitoUser(user, groups, stats, externalId) {
1891
+ const attrs = new Map((user.Attributes ?? []).map((a) => [a.Name ?? "", a.Value ?? ""]));
1892
+ const sub = attrs.get("sub") ?? user.Username ?? "";
1893
+ const email = attrs.get("email") || void 0;
1894
+ let identities = [];
1895
+ const raw = attrs.get("identities");
1896
+ if (raw) {
1897
+ try {
1898
+ const parsed = JSON.parse(raw);
1899
+ if (Array.isArray(parsed)) identities = parsed;
1900
+ } catch {
1901
+ }
1902
+ }
1903
+ const external = identities.filter((i) => !(email && i.userId?.toLowerCase() === email.toLowerCase())).map((i) => identity(stats, i.providerName ?? i.providerType ?? "unknown", PROVIDERS$2[i.providerType ?? ""], i.userId)).filter((i) => i !== void 0);
1904
+ if (user.UserStatus !== "EXTERNAL_PROVIDER") stats.passwordUsersWithoutHash++;
1905
+ const custom = {};
1906
+ for (const [name, value] of attrs) if (name.startsWith("custom:")) custom[name.slice("custom:".length)] = value;
1907
+ const phone = attrs.get("phone_number") || void 0;
1908
+ const row = compact({
1909
+ legacy_subject: sub,
1910
+ external_id: externalId === "legacy" ? sub : void 0,
1911
+ email,
1912
+ email_verified: email ? attrs.get("email_verified") === "true" : void 0,
1913
+ phone,
1914
+ phone_verified: phone ? attrs.get("phone_number_verified") === "true" : void 0,
1915
+ username: attrs.get("preferred_username") || void 0,
1916
+ name: attrs.get("name") || void 0,
1917
+ given_name: attrs.get("given_name") || void 0,
1918
+ family_name: attrs.get("family_name") || void 0,
1919
+ picture: attrs.get("picture") || void 0,
1920
+ locale: attrs.get("locale") || void 0,
1921
+ metadata: groups.length > 0 ? { cognito_groups: groups } : void 0,
1922
+ private_metadata: custom,
1923
+ status: user.Enabled === false ? "deactivated" : void 0,
1924
+ created_at: isoDate(user.UserCreateDate),
1925
+ external_identities: external
1926
+ });
1927
+ return requireEmail(stats, row, sub) ? row : void 0;
1928
+ }
1929
+ const cognito = {
1930
+ provider: "cognito",
1931
+ sourceType: "cognito",
1932
+ summary: "Cognito ListUsers and groups (--user-pool-id, AWS credentials from the environment); needs @aws-sdk/client-cognito-identity-provider",
1933
+ async run(ctx, emit, stats) {
1934
+ const pool = flagString(ctx.flags, "user-pool-id");
1935
+ if (!pool) throw new CliError("invalid_arguments", "The cognito exporter needs --user-pool-id (as us-east-1_AbC123).");
1936
+ const region = ctx.env.AWS_REGION?.trim() || ctx.env.AWS_DEFAULT_REGION?.trim() || pool.split("_")[0];
1937
+ const mode = externalIdMode(ctx.flags);
1938
+ const sdk = await ctx.load("@aws-sdk/client-cognito-identity-provider", "@aws-sdk/client-cognito-identity-provider");
1939
+ const Client = pick(sdk, "CognitoIdentityProviderClient");
1940
+ const ListUsers = pick(sdk, "ListUsersCommand");
1941
+ const ListGroups = pick(sdk, "ListGroupsCommand");
1942
+ const ListUsersInGroup = pick(sdk, "ListUsersInGroupCommand");
1943
+ const client = new Client({ region });
1944
+ const send = (command2) => client.send(command2);
1945
+ const groupsByUser = /* @__PURE__ */ new Map();
1946
+ let groupToken;
1947
+ do {
1948
+ const page = await send(new ListGroups({ UserPoolId: pool, Limit: 60, NextToken: groupToken }));
1949
+ for (const group of page.Groups ?? []) {
1950
+ const name = group.GroupName;
1951
+ if (!name || name.startsWith(`${pool}_`)) continue;
1952
+ let memberToken;
1953
+ do {
1954
+ const members = await send(new ListUsersInGroup({ UserPoolId: pool, GroupName: name, Limit: 60, NextToken: memberToken }));
1955
+ for (const u of members.Users ?? []) {
1956
+ if (u.Username) groupsByUser.set(u.Username, [...groupsByUser.get(u.Username) ?? [], name]);
1957
+ }
1958
+ memberToken = members.NextToken;
1959
+ } while (memberToken);
1960
+ }
1961
+ groupToken = page.NextToken;
1962
+ } while (groupToken);
1963
+ let token2;
1964
+ do {
1965
+ const page = await send(new ListUsers({ UserPoolId: pool, Limit: 60, PaginationToken: token2 }));
1966
+ for (const user of page.Users ?? []) {
1967
+ const row = mapCognitoUser(user, groupsByUser.get(user.Username ?? "") ?? [], stats, mode);
1968
+ if (!row) continue;
1969
+ stats.users++;
1970
+ await emit({ kind: "user", user: row });
1971
+ }
1972
+ token2 = page.PaginationToken;
1973
+ if (stats.users % 1200 < 60) ctx.info(`Cognito: ${stats.users} users read.`);
1974
+ } while (token2);
1975
+ stats.notes.push(
1976
+ "Cognito exports no password hashes and no TOTP secrets: password users set a new password by email at their first Pontive sign-in, and TOTP users enroll again."
1977
+ );
1978
+ stats.notes.push("Cognito groups are exported as metadata.cognito_groups, not as organizations.");
1979
+ }
1980
+ };
1981
+ const PROVIDERS$1 = {
1982
+ "google.com": "google",
1983
+ "github.com": "github",
1984
+ "apple.com": "apple",
1985
+ "microsoft.com": "not_portable"
1986
+ };
1987
+ const OWN$1 = /* @__PURE__ */ new Set(["password", "phone", "emailLink"]);
1988
+ const REDACTED = /* @__PURE__ */ new Set(["REDACTED", "UkVEQUNURUQ=", "UkVEQUNURUQ"]);
1989
+ function standardBase64(value) {
1990
+ const s = value.replace(/-/g, "+").replace(/_/g, "/");
1991
+ return s + "=".repeat((4 - s.length % 4) % 4);
1992
+ }
1993
+ function mapFirebaseUser(user, stats, externalId) {
1994
+ const providers = user.providerData ?? [];
1995
+ const isPasswordUser = providers.some((p) => p.providerId === "password");
1996
+ let passwordHash2;
1997
+ if (user.passwordHash && !REDACTED.has(user.passwordHash) && user.passwordSalt) {
1998
+ passwordHash2 = { hasher: "firebase_scrypt", value: standardBase64(user.passwordHash), salt: standardBase64(user.passwordSalt) };
1999
+ } else if (isPasswordUser) {
2000
+ stats.passwordUsersWithoutHash++;
2001
+ }
2002
+ if (user.multiFactor?.enrolledFactors?.some((f) => f.factorId === "totp")) stats.totpNotExported++;
2003
+ const external = providers.filter((p) => !OWN$1.has(p.providerId)).map((p) => identity(stats, p.providerId, p.providerId.startsWith("oidc.") ? "oidc" : PROVIDERS$1[p.providerId], p.uid, p.email)).filter((i) => i !== void 0);
2004
+ const row = compact({
2005
+ legacy_subject: user.uid,
2006
+ external_id: externalId === "legacy" ? user.uid : void 0,
2007
+ email: user.email,
2008
+ email_verified: user.email ? Boolean(user.emailVerified) : void 0,
2009
+ phone: user.phoneNumber,
2010
+ // Firebase holds a phone number only once it signed in with it.
2011
+ phone_verified: user.phoneNumber ? true : void 0,
2012
+ name: user.displayName,
2013
+ picture: user.photoURL,
2014
+ private_metadata: user.customClaims,
2015
+ status: user.disabled ? "deactivated" : void 0,
2016
+ created_at: isoDate(user.metadata?.creationTime),
2017
+ password_hash: passwordHash2,
2018
+ external_identities: external
2019
+ });
2020
+ return requireEmail(stats, row, user.uid) ? row : void 0;
2021
+ }
2022
+ const firebase = {
2023
+ provider: "firebase",
2024
+ sourceType: "firebase",
2025
+ summary: "Firebase Admin SDK listUsers (GOOGLE_APPLICATION_CREDENTIALS); needs the firebase-admin package; hash parameters go on the source",
2026
+ async run(ctx, emit, stats) {
2027
+ if (!ctx.env.GOOGLE_APPLICATION_CREDENTIALS && !ctx.env.GOOGLE_CLOUD_PROJECT) {
2028
+ throw new CliError(
2029
+ "provider_credentials_required",
2030
+ "The firebase exporter uses a service account: set GOOGLE_APPLICATION_CREDENTIALS to its JSON key file (or GOOGLE_CLOUD_PROJECT with application default credentials)."
2031
+ );
2032
+ }
2033
+ const mode = externalIdMode(ctx.flags);
2034
+ const app = await ctx.load("firebase-admin/app", "firebase-admin");
2035
+ const authModule = await ctx.load("firebase-admin/auth", "firebase-admin");
2036
+ const initializeApp = pick(app, "initializeApp");
2037
+ const applicationDefault = pick(app, "applicationDefault");
2038
+ const getAuth = pick(authModule, "getAuth");
2039
+ const instance = initializeApp(
2040
+ { credential: applicationDefault(), ...ctx.env.GOOGLE_CLOUD_PROJECT ? { projectId: ctx.env.GOOGLE_CLOUD_PROJECT } : {} },
2041
+ "pontive-migrate"
2042
+ );
2043
+ const auth = getAuth(instance);
2044
+ let token2;
2045
+ let withHash = 0;
2046
+ do {
2047
+ const page = await auth.listUsers(1e3, token2);
2048
+ for (const user of page.users) {
2049
+ const row = mapFirebaseUser(user, stats, mode);
2050
+ if (!row) continue;
2051
+ if (row.password_hash) withHash++;
2052
+ stats.users++;
2053
+ await emit({ kind: "user", user: row });
2054
+ }
2055
+ token2 = page.pageToken;
2056
+ ctx.info(`Firebase: ${stats.users} users read.`);
2057
+ } while (token2);
2058
+ if (withHash === 0 && stats.passwordUsersWithoutHash > 0) {
2059
+ stats.notes.push(
2060
+ "No password hashes came back: the service account needs firebaseauth.configs.getHashConfig (a custom IAM role) for listUsers to answer them."
2061
+ );
2062
+ }
2063
+ if (withHash > 0) {
2064
+ stats.notes.push("Firebase hashes need the project's hash parameters on the migration source: pontive migrate source create --type firebase --hash-config <file>.");
2065
+ }
2066
+ stats.notes.push("Firebase has no organizations; Identity Platform tenants are not exported.");
2067
+ }
2068
+ };
2069
+ const PAGE = 1e3;
2070
+ const PROVIDERS = {
2071
+ google: "google",
2072
+ github: "github",
2073
+ apple: "apple",
2074
+ azure: "not_portable"
2075
+ };
2076
+ const OWN = /* @__PURE__ */ new Set(["email", "phone", "anonymous"]);
2077
+ function passwordHash(value, stats) {
2078
+ if (!value) return void 0;
2079
+ if (/^\$2[aby]\$/.test(value)) return { hasher: "bcrypt", value };
2080
+ if (/^\$argon2(id|i)\$/.test(value)) return { hasher: "argon2", value };
2081
+ stats.passwordUsersWithoutHash++;
2082
+ return void 0;
2083
+ }
2084
+ function mapSupabaseUser(user, identities, factors, stats, externalId, now) {
2085
+ const meta = user.raw_user_meta_data ?? {};
2086
+ const { provider: _p, providers: _ps, ...appMeta } = user.raw_app_meta_data ?? {};
2087
+ const external = identities.filter((i) => !OWN.has(i.provider) && !i.provider.startsWith("sso:")).map((i) => {
2088
+ const subject = i.provider_id ?? str(object(i.identity_data)?.sub);
2089
+ return identity(stats, i.provider, PROVIDERS[i.provider], subject, str(object(i.identity_data)?.email));
2090
+ }).filter((i) => i !== void 0);
2091
+ const secret = factors.map((f) => f.secret).find((s) => typeof s === "string" && s !== "");
2092
+ let totp;
2093
+ if (secret && !secret.trimStart().startsWith("{")) totp = { secret };
2094
+ else if (factors.length > 0) stats.totpNotExported++;
2095
+ const banned = user.banned_until ? new Date(user.banned_until) > now : false;
2096
+ const phone = user.phone ? user.phone.startsWith("+") ? user.phone : `+${user.phone}` : void 0;
2097
+ const row = compact({
2098
+ legacy_subject: user.id,
2099
+ external_id: externalId === "legacy" ? user.id : void 0,
2100
+ email: user.email ?? void 0,
2101
+ email_verified: user.email ? user.email_confirmed_at !== null : void 0,
2102
+ phone,
2103
+ phone_verified: phone ? user.phone_confirmed_at !== null : void 0,
2104
+ name: str(meta.full_name) ?? str(meta.name),
2105
+ picture: str(meta.avatar_url) ?? str(meta.picture),
2106
+ metadata: meta,
2107
+ private_metadata: appMeta,
2108
+ status: banned ? "deactivated" : void 0,
2109
+ created_at: isoDate(user.created_at),
2110
+ password_hash: passwordHash(user.encrypted_password, stats),
2111
+ totp,
2112
+ external_identities: external
2113
+ });
2114
+ return requireEmail(stats, row, user.id) ? row : void 0;
2115
+ }
2116
+ const supabase = {
2117
+ provider: "supabase",
2118
+ sourceType: "supabase",
2119
+ summary: "Supabase auth schema over Postgres (SUPABASE_DB_URL, or --db-url); needs the pg package",
2120
+ async run(ctx, emit, stats) {
2121
+ const flagUrl = flagString(ctx.flags, "db-url");
2122
+ if (flagUrl) ctx.warn("--db-url puts the database password in your shell history; prefer SUPABASE_DB_URL.");
2123
+ const url = ctx.env.SUPABASE_DB_URL?.trim() || flagUrl;
2124
+ if (!url) throw new CliError("provider_credentials_required", "The supabase exporter reads the connection string from SUPABASE_DB_URL (or --db-url).");
2125
+ const mode = externalIdMode(ctx.flags);
2126
+ const pg = await ctx.load("pg", "pg");
2127
+ const Client = pick(pg, "Client");
2128
+ const client = new Client({ connectionString: url });
2129
+ await client.connect();
2130
+ try {
2131
+ let after = "00000000-0000-0000-0000-000000000000";
2132
+ for (; ; ) {
2133
+ const { rows } = await client.query(
2134
+ `select id, email, encrypted_password, email_confirmed_at, phone, phone_confirmed_at,
2135
+ raw_user_meta_data, raw_app_meta_data, created_at, banned_until
2136
+ from auth.users
2137
+ where id > $1 and deleted_at is null and not coalesce(is_anonymous, false)
2138
+ order by id
2139
+ limit ${PAGE}`,
2140
+ [after]
2141
+ );
2142
+ if (rows.length === 0) break;
2143
+ const ids = rows.map((r) => r.id);
2144
+ const identities = await client.query(
2145
+ "select user_id, provider, provider_id, identity_data from auth.identities where user_id = any($1::uuid[])",
2146
+ [ids]
2147
+ );
2148
+ const factors = await client.query(
2149
+ "select user_id, secret from auth.mfa_factors where factor_type = 'totp' and status = 'verified' and user_id = any($1::uuid[])",
2150
+ [ids]
2151
+ );
2152
+ const byUser = (list) => {
2153
+ const map = /* @__PURE__ */ new Map();
2154
+ for (const r of list) map.set(r.user_id, [...map.get(r.user_id) ?? [], r]);
2155
+ return map;
2156
+ };
2157
+ const identitiesByUser = byUser(identities.rows);
2158
+ const factorsByUser = byUser(factors.rows);
2159
+ for (const user of rows) {
2160
+ const row = mapSupabaseUser(user, identitiesByUser.get(user.id) ?? [], factorsByUser.get(user.id) ?? [], stats, mode, ctx.now());
2161
+ if (!row) continue;
2162
+ stats.users++;
2163
+ await emit({ kind: "user", user: row });
2164
+ }
2165
+ after = rows[rows.length - 1].id;
2166
+ ctx.info(`Supabase: ${stats.users} users read.`);
2167
+ if (rows.length < PAGE) break;
2168
+ }
2169
+ } finally {
2170
+ await client.end();
2171
+ }
2172
+ stats.notes.push("Supabase has no organizations of its own; the app's tables are not read.");
2173
+ }
2174
+ };
2175
+ const EXPORTERS = new Map([auth0, clerk, supabase, firebase, cognito].map((e) => [e.provider, e]));
2176
+ function exporter(name) {
2177
+ const found = name ? EXPORTERS.get(name) : void 0;
2178
+ if (!found) {
2179
+ throw new CliError(
2180
+ "unknown_provider",
2181
+ `${name ? `Unknown provider "${name}"` : "Name a provider"}: ${[...EXPORTERS.keys()].join(", ")}. For any other source, write the pontive-users/v1 file yourself and run pontive migrate import.`
2182
+ );
2183
+ }
2184
+ return found;
2185
+ }
2186
+ async function runExport(e, ctx, emit) {
2187
+ const stats = new ExportStats();
2188
+ await emit({ kind: "header", header: { format: FORMAT, source_type: e.sourceType, exported_at: ctx.now().toISOString() } });
2189
+ let sawOrganization = false;
2190
+ await e.run(
2191
+ ctx,
2192
+ async (line) => {
2193
+ if (line.kind === "organization") sawOrganization = true;
2194
+ else if (line.kind === "user" && sawOrganization) throw new Error(`The ${e.provider} exporter wrote a user after an organization.`);
2195
+ await emit(line);
2196
+ },
2197
+ stats
2198
+ );
2199
+ await emit({ kind: "summary", summary: stats.summary() });
2200
+ return stats;
2201
+ }
2202
+ const ALIASES = {
2203
+ base64_signer_key: "signer_key",
2204
+ signer_key: "signer_key",
2205
+ signerkey: "signer_key",
2206
+ base64_salt_separator: "salt_separator",
2207
+ salt_separator: "salt_separator",
2208
+ saltseparator: "salt_separator",
2209
+ rounds: "rounds",
2210
+ mem_cost: "mem_cost",
2211
+ memorycost: "mem_cost",
2212
+ memcost: "mem_cost"
2213
+ };
2214
+ function parseHashConfig(text) {
2215
+ const out = {};
2216
+ const set = (rawKey, rawValue) => {
2217
+ const key = ALIASES[rawKey.toLowerCase()];
2218
+ if (!key) return;
2219
+ if (key === "rounds" || key === "mem_cost") out[key] = Number(rawValue);
2220
+ else out[key] = String(rawValue).trim();
2221
+ };
2222
+ const trimmed = text.trim();
2223
+ if (trimmed.startsWith("{")) {
2224
+ let json;
2225
+ try {
2226
+ json = JSON.parse(trimmed);
2227
+ } catch {
2228
+ throw new CliError("invalid_file", "The hash config file is not valid JSON.");
2229
+ }
2230
+ const inner = json.firebase_scrypt ?? json.hashConfig ?? json.hash_config ?? json;
2231
+ for (const [k, v] of Object.entries(inner)) set(k, v);
2232
+ return out;
2233
+ }
2234
+ for (const match of trimmed.matchAll(/([A-Za-z0-9_]+)\s*:\s*([^,\n}]+)/g)) set(match[1], match[2]);
2235
+ return out;
2236
+ }
2237
+ async function readHashConfig(input, complete) {
2238
+ const fromFile = input.file ? parseHashConfig(await readFile(input.file, "utf8")) : {};
2239
+ const config = { ...fromFile };
2240
+ if (input.saltSeparator !== void 0) config.salt_separator = input.saltSeparator;
2241
+ if (input.rounds !== void 0) config.rounds = Number(input.rounds);
2242
+ if (input.memCost !== void 0) config.mem_cost = Number(input.memCost);
2243
+ const envKey = input.env.FIREBASE_SIGNER_KEY?.trim();
2244
+ if (envKey) config.signer_key = envKey;
2245
+ const given = Object.values(config).some((v) => v !== void 0);
2246
+ if (!given) return void 0;
2247
+ for (const key of ["rounds", "mem_cost"]) {
2248
+ const v = config[key];
2249
+ if (v !== void 0 && (!Number.isInteger(v) || v < 1 || v > 16)) {
2250
+ throw new CliError("invalid_arguments", `Firebase ${key} must be an integer from 1 to 16.`);
2251
+ }
2252
+ }
2253
+ const missing = ["salt_separator", "rounds", "mem_cost"].filter((k) => config[k] === void 0);
2254
+ if (complete && !config.signer_key) missing.unshift("signer_key");
2255
+ if (missing.length > 0) {
2256
+ throw new CliError(
2257
+ "invalid_arguments",
2258
+ `Firebase hash parameters missing: ${missing.join(", ")}. Pass --hash-config <file> (the console's Password hash parameters), or --salt-separator, --rounds, --mem-cost with the signer key in FIREBASE_SIGNER_KEY.`
2259
+ );
2260
+ }
2261
+ return config;
2262
+ }
2263
+ const MAX_USERS = 100;
2264
+ const MAX_ORGANIZATIONS = 100;
2265
+ const MAX_MEMBERS = 1e3;
2266
+ const MAX_BODY_BYTES = 9e5;
2267
+ function size(value) {
2268
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
2269
+ }
2270
+ async function* userBatches(users2, max = MAX_USERS) {
2271
+ let batch = [];
2272
+ let bytes = 0;
2273
+ for await (const user of users2) {
2274
+ const n = size(user) + 1;
2275
+ if (batch.length > 0 && (batch.length >= max || bytes + n > MAX_BODY_BYTES)) {
2276
+ yield batch;
2277
+ batch = [];
2278
+ bytes = 0;
2279
+ }
2280
+ batch.push(user);
2281
+ bytes += n;
2282
+ }
2283
+ if (batch.length > 0) yield batch;
2284
+ }
2285
+ const isOwner = (m) => m.roles.includes("owner");
2286
+ async function* organizationBatches(organizations, limits = { organizations: MAX_ORGANIZATIONS, members: MAX_MEMBERS }) {
2287
+ let batch = [];
2288
+ let members = 0;
2289
+ let bytes = 0;
2290
+ const flush = function* () {
2291
+ if (batch.length > 0) yield batch;
2292
+ batch = [];
2293
+ members = 0;
2294
+ bytes = 0;
2295
+ };
2296
+ for await (const organization of organizations) {
2297
+ const ordered = [...organization.members.filter(isOwner), ...organization.members.filter((m) => !isOwner(m))];
2298
+ const { members: _all, ...fields } = organization;
2299
+ const fieldBytes = size(fields) + 16;
2300
+ let next = 0;
2301
+ let placed = false;
2302
+ do {
2303
+ const room = limits.members - members;
2304
+ if (batch.length >= limits.organizations || room <= 0 && ordered.length > next || batch.length > 0 && bytes + fieldBytes > MAX_BODY_BYTES) {
2305
+ yield* flush();
2306
+ continue;
2307
+ }
2308
+ const chunk = [];
2309
+ let chunkBytes = 0;
2310
+ while (next < ordered.length && chunk.length < limits.members - members) {
2311
+ const n = size(ordered[next]) + 1;
2312
+ if (bytes + fieldBytes + chunkBytes + n > MAX_BODY_BYTES && (chunk.length > 0 || batch.length > 0)) break;
2313
+ chunk.push(ordered[next]);
2314
+ chunkBytes += n;
2315
+ next++;
2316
+ }
2317
+ if (chunk.length === 0 && next < ordered.length) {
2318
+ yield* flush();
2319
+ continue;
2320
+ }
2321
+ batch.push({ ...fields, members: chunk });
2322
+ members += chunk.length;
2323
+ bytes += fieldBytes + chunkBytes;
2324
+ placed = true;
2325
+ } while (next < ordered.length || !placed);
2326
+ }
2327
+ yield* flush();
2328
+ }
2329
+ function parseRoleMap(values) {
2330
+ if (values.length === 0) return void 0;
2331
+ const map = /* @__PURE__ */ new Map();
2332
+ for (const value of values) {
2333
+ for (const pair of value.split(",")) {
2334
+ const trimmed = pair.trim();
2335
+ if (trimmed === "") continue;
2336
+ const at = trimmed.lastIndexOf("=");
2337
+ if (at <= 0 || at === trimmed.length - 1) {
2338
+ throw new CliError("invalid_arguments", `--role-map takes source_role=pontive_role pairs; got "${trimmed}".`);
2339
+ }
2340
+ map.set(trimmed.slice(0, at).trim(), trimmed.slice(at + 1).trim());
2341
+ }
2342
+ }
2343
+ return map;
2344
+ }
2345
+ function parseIdentityConnections(values) {
2346
+ return values.map((value) => {
2347
+ const match = /^([a-z_]+)=(app_[^:\s]+):([^:\s]+)$/.exec(value.trim());
2348
+ if (!match) {
2349
+ throw new CliError(
2350
+ "invalid_arguments",
2351
+ `--identity-connection takes connection_type=app_id:connection_slug, as google=app_01J…:google; got "${value}".`
2352
+ );
2353
+ }
2354
+ return { connection_type: match[1], app_id: match[2], connection_slug: match[3] };
2355
+ });
2356
+ }
2357
+ function memberReference(member) {
2358
+ return member.legacy_subject ?? member.user_external_id ?? member.user_id ?? "(no reference)";
2359
+ }
2360
+ function mapRoles(organization, map) {
2361
+ if (!map) return { organization, failures: [] };
2362
+ const failures = [];
2363
+ const members = [];
2364
+ for (const member of organization.members) {
2365
+ const unmapped = member.roles.find((role) => !map.has(role));
2366
+ if (unmapped !== void 0) {
2367
+ failures.push({ organization: organization.external_id, member: memberReference(member), code: "role_not_mapped", role: unmapped });
2368
+ continue;
2369
+ }
2370
+ members.push({ ...member, roles: [...new Set(member.roles.map((role) => map.get(role)))] });
2371
+ }
2372
+ return { organization: { ...organization, members }, failures };
2373
+ }
2374
+ function filterIdentities(user, mapped, skipped) {
2375
+ if (!user.external_identities?.length) return user;
2376
+ const kept = user.external_identities.filter((identity2) => {
2377
+ if (mapped.has(identity2.connection_type)) return true;
2378
+ skipped.set(identity2.connection_type, (skipped.get(identity2.connection_type) ?? 0) + 1);
2379
+ return false;
2380
+ });
2381
+ if (kept.length === user.external_identities.length) return user;
2382
+ const { external_identities: _dropped, ...rest } = user;
2383
+ return kept.length > 0 ? { ...rest, external_identities: kept } : rest;
2384
+ }
2385
+ function filterTotp(user, hasTotpApps, counter) {
2386
+ if (!user.totp || hasTotpApps) return user;
2387
+ counter.totpNotImported++;
2388
+ const { totp: _dropped, ...rest } = user;
2389
+ return rest;
2390
+ }
2391
+ const KEYS_PER_CODE = 100;
2392
+ const zero = () => ({ created: 0, updated: 0, skipped: 0, failed: 0 });
2393
+ class ReportBuilder {
2394
+ constructor(dryRun, runId) {
2395
+ this.dryRun = dryRun;
2396
+ this.runId = runId;
2397
+ }
2398
+ dryRun;
2399
+ runId;
2400
+ users = zero();
2401
+ organizations = { ...zero(), pending_users: 0 };
2402
+ failures = /* @__PURE__ */ new Map();
2403
+ warnings = /* @__PURE__ */ new Map();
2404
+ batches = 0;
2405
+ /** Dry run: the keys of users the import would create or match, to recognize organizations waiting on them. */
2406
+ importedUsers = /* @__PURE__ */ new Set();
2407
+ summary;
2408
+ identitiesNotImported = /* @__PURE__ */ new Map();
2409
+ /** Users whose TOTP secret was not sent because the run names no TOTP app. */
2410
+ totpNotImported = 0;
2411
+ /** Records a user batch's answer. `sent` is the batch as sent, for the rows' keys. */
2412
+ addUsers(answer, sent) {
2413
+ this.batches++;
2414
+ for (const record of answer.records) {
2415
+ const row = sent[record.index];
2416
+ const key = record.key ?? row?.legacy_subject ?? row?.external_id ?? row?.email ?? `#${record.index}`;
2417
+ this.users[record.outcome]++;
2418
+ if (record.outcome !== "failed" && row) {
2419
+ for (const k of [row.legacy_subject, row.external_id]) if (k) this.importedUsers.add(k);
2420
+ }
2421
+ for (const error of record.errors ?? []) add(this.failures, error.code, "user", key);
2422
+ for (const warning of record.warnings ?? []) add(this.warnings, warning.code, "user", key);
2423
+ }
2424
+ }
2425
+ addOrganizations(answer, sent) {
2426
+ this.batches++;
2427
+ for (const record of answer.records) {
2428
+ const row = sent[record.index];
2429
+ const key = record.key ?? row?.external_id ?? `#${record.index}`;
2430
+ if (this.dryRun && record.outcome === "failed" && row && this.waitsOnImportedUsers(record.errors ?? [], row)) {
2431
+ this.organizations.pending_users++;
2432
+ continue;
2433
+ }
2434
+ this.organizations[record.outcome]++;
2435
+ for (const error of record.errors ?? []) add(this.failures, error.code, "organization", key);
2436
+ for (const warning of record.warnings ?? []) add(this.warnings, warning.code, "organization", key);
2437
+ }
2438
+ }
2439
+ addLocalFailures(failures) {
2440
+ for (const f of failures) add(this.failures, f.code, "member", `${f.organization}/${f.member} (${f.role})`);
2441
+ }
2442
+ waitsOnImportedUsers(errors, row) {
2443
+ if (errors.length === 0) return false;
2444
+ if (!errors.every((e) => e.code === "user_not_found" || e.code === "owners_required")) return false;
2445
+ return row.members.every((m) => {
2446
+ const ref = m.legacy_subject ?? m.user_external_id;
2447
+ return ref !== void 0 && this.importedUsers.has(ref);
2448
+ });
2449
+ }
2450
+ build() {
2451
+ const failures = [...this.failures.values()].sort((a, b) => b.count - a.count);
2452
+ const warnings = [...this.warnings.values()].sort((a, b) => b.count - a.count);
2453
+ const data = {
2454
+ dry_run: this.dryRun,
2455
+ run_id: this.runId,
2456
+ users: { ...this.users },
2457
+ organizations: { ...this.organizations },
2458
+ batches: this.batches,
2459
+ failures,
2460
+ warnings,
2461
+ password_users_without_hash: this.summary?.password_users_without_hash ?? null,
2462
+ identities_not_imported: Object.fromEntries(this.identitiesNotImported),
2463
+ totp_not_imported: this.totpNotImported,
2464
+ next_steps: []
2465
+ };
2466
+ data.next_steps = nextSteps(data);
2467
+ return data;
2468
+ }
2469
+ }
2470
+ function add(groups, code2, kind, key) {
2471
+ const id = `${kind}:${code2}`;
2472
+ let group = groups.get(id);
2473
+ if (!group) {
2474
+ group = { code: code2, kind, count: 0, keys: [] };
2475
+ groups.set(id, group);
2476
+ }
2477
+ group.count++;
2478
+ if (group.keys.length < KEYS_PER_CODE) group.keys.push(key);
2479
+ }
2480
+ function has(data, code2) {
2481
+ return data.failures.some((f) => f.code === code2);
2482
+ }
2483
+ function nextSteps(data) {
2484
+ const steps = [];
2485
+ const run2 = data.run_id;
2486
+ if (has(data, "identifier_conflict")) {
2487
+ steps.push(
2488
+ "identifier_conflict: another Pontive user already has these rows' email, phone or username. Email never matches an import to an existing user; resolve each one (merge, delete or change the row) and import again."
2489
+ );
2490
+ }
2491
+ if (has(data, "migration_source_required")) {
2492
+ steps.push("migration_source_required: create a source (pontive migrate source create --name … --type …) and import into a run with --source msrc_….");
2493
+ }
2494
+ if (has(data, "owners_required")) {
2495
+ steps.push("owners_required: a new organization needs a member with the owner role. Map one with --role-map <source_role>=owner.");
2496
+ }
2497
+ if (has(data, "role_not_mapped")) {
2498
+ steps.push("role_not_mapped: these members hold a role --role-map does not name; add it to the map and import again.");
2499
+ }
2500
+ if (has(data, "role_not_found")) {
2501
+ steps.push("role_not_found: these roles are not organization roles in this instance; map them with --role-map or create them first.");
2502
+ }
2503
+ if (has(data, "password_hash_invalid") || has(data, "hasher_unsupported")) {
2504
+ steps.push("password_hash_invalid / hasher_unsupported: these users are not imported with their password; fix or remove password_hash in their rows to import them, and they reset by email.");
2505
+ }
2506
+ const identityTypes = Object.keys(data.identities_not_imported);
2507
+ if (identityTypes.length > 0) {
2508
+ steps.push(
2509
+ `External identities not imported for ${identityTypes.join(", ")}: the run maps no connection of that type. Those users re-link by email at their first sign-in; to import them, pass --identity-connection <type>=app_…:<connection_slug> on a new run.`
2510
+ );
2511
+ }
2512
+ if (data.totp_not_imported > 0) {
2513
+ steps.push(
2514
+ `${data.totp_not_imported} users' TOTP secrets were not imported: the run names no app to store them under. They enroll again; to import them, pass --totp-app app_… on a new run.`
2515
+ );
2516
+ }
2517
+ if (has(data, "owner_requires_transfer")) {
2518
+ steps.push("owner_requires_transfer: owners are set only when the import creates the organization; grant owner on an existing one by transferring ownership.");
2519
+ }
2520
+ if (data.password_users_without_hash) {
2521
+ steps.push(`${data.password_users_without_hash} password users were exported without a hash: they set a new password by email at their first Pontive sign-in.`);
2522
+ }
2523
+ if (data.dry_run) {
2524
+ if (data.organizations.pending_users > 0) {
2525
+ steps.push(
2526
+ `${data.organizations.pending_users} organizations wait on users this import creates; a dry run creates none, so they show as pending and resolve when applied.`
2527
+ );
2528
+ }
2529
+ steps.push("Nothing was written. Re-run with --apply to import.");
2530
+ } else {
2531
+ const failed = data.users.failed + data.organizations.failed;
2532
+ if (failed > 0) steps.push(`List every failed row: pontive migrate records ${run2} --outcome failed`);
2533
+ steps.push(`Check the run: pontive migrate status ${run2}`);
2534
+ steps.push(`Undo it: pontive migrate revert ${run2} (a dry run), then with --apply`);
2535
+ }
2536
+ return steps;
2537
+ }
2538
+ function renderReport(data) {
2539
+ const lines = [];
2540
+ const title = data.dry_run ? `Dry run of ${data.run_id}: nothing was written.` : `Imported into ${data.run_id}.`;
2541
+ lines.push(title, "");
2542
+ const counts = (c) => `${c.created} created, ${c.updated} updated, ${c.skipped} skipped, ${c.failed} failed`;
2543
+ const verb = data.dry_run ? "would be" : "";
2544
+ lines.push(`Users${verb ? ` (${verb})` : ""}: ${counts(data.users)}`);
2545
+ const pending = data.dry_run && data.organizations.pending_users > 0 ? `, ${data.organizations.pending_users} pending users` : "";
2546
+ lines.push(`Organizations${verb ? ` (${verb})` : ""}: ${counts(data.organizations)}${pending}`);
2547
+ if (data.failures.length > 0) {
2548
+ lines.push("", "Failures:");
2549
+ for (const f of data.failures) {
2550
+ const shown = f.keys.slice(0, 10);
2551
+ const more = f.count > shown.length ? `, … ${f.count - shown.length} more` : "";
2552
+ lines.push(` ${f.code} (${f.kind}, ${f.count}): ${shown.join(", ")}${more}`);
2553
+ }
2554
+ }
2555
+ if (data.warnings.length > 0) {
2556
+ lines.push("", "Warnings:");
2557
+ for (const w of data.warnings) lines.push(` ${w.code} (${w.kind}, ${w.count}): ${w.keys.slice(0, 5).join(", ")}${w.count > 5 ? ", …" : ""}`);
2558
+ }
2559
+ if (data.password_users_without_hash !== null) {
2560
+ lines.push("", `Password users without a hash: ${data.password_users_without_hash}`);
2561
+ }
2562
+ if (data.next_steps.length > 0) {
2563
+ lines.push("", "Next:");
2564
+ for (const step of data.next_steps) lines.push(` - ${step}`);
2565
+ }
2566
+ return lines;
2567
+ }
2568
+ const STATE_FILE = ".pontive-import-state.json";
2569
+ function statePath(file) {
2570
+ return join(dirname(file), STATE_FILE);
2571
+ }
2572
+ async function loadState(file, sha256) {
2573
+ let text;
2574
+ try {
2575
+ text = await readFile(statePath(file), "utf8");
2576
+ } catch (error) {
2577
+ if (error.code === "ENOENT") return void 0;
2578
+ throw error;
2579
+ }
2580
+ let state;
2581
+ try {
2582
+ state = JSON.parse(text);
2583
+ } catch {
2584
+ throw new CliError("state_invalid", `${statePath(file)} is not valid JSON. Delete it to start over.`);
2585
+ }
2586
+ if (state.version !== 1 || state.file !== basename(file)) return void 0;
2587
+ if (state.sha256 !== sha256) {
2588
+ throw new CliError(
2589
+ "state_mismatch",
2590
+ `${statePath(file)} belongs to an earlier version of ${basename(file)} (run ${state.run_id}). Delete it to import the changed file into a new run, or pass --run ${state.run_id} to continue that run with it.`,
2591
+ void 0,
2592
+ { run_id: state.run_id }
2593
+ );
2594
+ }
2595
+ return state;
2596
+ }
2597
+ async function saveState(file, state) {
2598
+ const path = statePath(file);
2599
+ const tmp = `${path}.tmp`;
2600
+ await writeFile(tmp, `${JSON.stringify(state, null, 2)}
2601
+ `, { mode: 384 });
2602
+ await rename(tmp, path);
2603
+ }
2604
+ async function removeState(file) {
2605
+ await rm(statePath(file), { force: true });
2606
+ }
2607
+ function fileSource(path) {
2608
+ let summary;
2609
+ return {
2610
+ async *users() {
2611
+ for await (const line of readLines(path)) {
2612
+ if (line.kind === "user") yield line.user;
2613
+ else if (line.kind === "summary") summary = line.summary;
2614
+ }
2615
+ },
2616
+ async *organizations() {
2617
+ for await (const line of readLines(path)) if (line.kind === "organization") yield line.organization;
2618
+ },
2619
+ summary: () => summary
2620
+ };
2621
+ }
2622
+ function memorySource(users2, organizations, summary) {
2623
+ return {
2624
+ async *users() {
2625
+ yield* users2;
2626
+ },
2627
+ async *organizations() {
2628
+ yield* organizations;
2629
+ },
2630
+ summary: () => summary
2631
+ };
2632
+ }
2633
+ function runFingerprint(settings2) {
2634
+ return createHash("sha256").update(JSON.stringify({ source: settings2.sourceId ?? null, options: settings2.options })).digest("hex").slice(0, 16);
2635
+ }
2636
+ async function resolveRun(api2, settings2, io) {
2637
+ const fp = runFingerprint(settings2);
2638
+ let state;
2639
+ if (settings2.file) {
2640
+ try {
2641
+ state = await loadState(settings2.file.path, settings2.file.sha256);
2642
+ } catch (error) {
2643
+ if (!(settings2.runId && error instanceof CliError && error.code === "state_mismatch")) throw error;
2644
+ }
2645
+ }
2646
+ if (settings2.runId) {
2647
+ const run22 = await api2.getRun(settings2.runId);
2648
+ if (settings2.optionsFromFlags) io.warn(`Importing into existing run ${run22.id}: its own options apply, not the option flags.`);
2649
+ if (state && state.run_id !== run22.id) state = void 0;
2650
+ return { run: assertOpen(run22), state };
2651
+ }
2652
+ if (state) {
2653
+ const applied = state.users_batches_applied + state.organizations_batches_applied;
2654
+ if (state.run_fingerprint === fp || applied > 0) {
2655
+ if (state.run_fingerprint !== fp) {
2656
+ throw new CliError(
2657
+ "run_options_fixed",
2658
+ `${basename(settings2.file.path)} is part way into run ${state.run_id}, whose source and options differ from these flags. Re-run with the flags it was started with, or delete ${".pontive-import-state.json"} to start a new run.`,
2659
+ void 0,
2660
+ { run_id: state.run_id }
2661
+ );
2662
+ }
2663
+ try {
2664
+ const run22 = await api2.getRun(state.run_id);
2665
+ io.info(`Continuing run ${run22.id} from ${".pontive-import-state.json"}.`);
2666
+ return { run: assertOpen(run22), state };
2667
+ } catch (error) {
2668
+ if (!(error instanceof CliError && error.code === "user_import_not_found") || applied > 0) throw error;
2669
+ }
2670
+ }
2671
+ }
2672
+ const run2 = await api2.createRun({
2673
+ name: settings2.name,
2674
+ ...settings2.sourceId ? { migration_source_id: settings2.sourceId } : {},
2675
+ options: settings2.options
2676
+ });
2677
+ io.info(`Created run ${run2.id}.`);
2678
+ if (settings2.file) {
2679
+ state = {
2680
+ version: 1,
2681
+ file: basename(settings2.file.path),
2682
+ sha256: settings2.file.sha256,
2683
+ run_id: run2.id,
2684
+ run_fingerprint: fp,
2685
+ phase: "users",
2686
+ users_batches_applied: 0,
2687
+ organizations_batches_applied: 0,
2688
+ updated_at: io.now().toISOString()
2689
+ };
2690
+ await saveState(settings2.file.path, state);
2691
+ }
2692
+ return { run: run2, state };
2693
+ }
2694
+ function assertOpen(run2) {
2695
+ if (run2.status !== "open") {
2696
+ throw new CliError("user_import_reverted", `Run ${run2.id} is ${run2.status} and takes no more batches. Import into a new run.`, void 0, { run_id: run2.id });
2697
+ }
2698
+ return run2;
2699
+ }
2700
+ async function pass(api2, run2, source, settings2, io, dryRun, state) {
2701
+ const report = new ReportBuilder(dryRun, run2.id);
2702
+ const mapped = new Set(run2.options?.identity_connections?.map((c) => c.connection_type) ?? []);
2703
+ const hasTotpApps = (run2.options?.totp_app_ids?.length ?? 0) > 0;
2704
+ const label = dryRun ? "Dry run" : "Applying";
2705
+ const prepared = async function* () {
2706
+ for await (const user of source.users()) {
2707
+ if (user.legacy_subject && !run2.migration_source_id) {
2708
+ throw new CliError(
2709
+ "migration_source_required",
2710
+ "The rows carry legacy_subject, which needs a migration source on the run. Create one with pontive migrate source create, then pass --source msrc_…."
2711
+ );
2712
+ }
2713
+ yield filterTotp(filterIdentities(user, mapped, report.identitiesNotImported), hasTotpApps, report);
2714
+ }
2715
+ };
2716
+ let n = 0;
2717
+ let rows = 0;
2718
+ for await (const batch of userBatches(prepared())) {
2719
+ n++;
2720
+ rows += batch.length;
2721
+ if (!dryRun && state && n <= state.users_batches_applied) continue;
2722
+ const answer = await api2.importUsers(run2.id, batch, dryRun);
2723
+ report.addUsers(answer, batch);
2724
+ io.info(`${label}: users batch ${n} (${rows} rows) ${answer.counts.created} created, ${answer.counts.updated} updated, ${answer.counts.skipped} skipped, ${answer.counts.failed} failed`);
2725
+ if (!dryRun && state) {
2726
+ state.users_batches_applied = n;
2727
+ state.updated_at = io.now().toISOString();
2728
+ await saveState(settings2.file.path, state);
2729
+ }
2730
+ }
2731
+ report.summary = source.summary();
2732
+ if (!dryRun && state && state.phase === "users") {
2733
+ state.phase = "organizations";
2734
+ await saveState(settings2.file.path, state);
2735
+ }
2736
+ const local = [];
2737
+ const mappedOrgs = async function* () {
2738
+ for await (const organization of source.organizations()) {
2739
+ const { organization: out, failures } = mapRoles(organization, settings2.roleMap);
2740
+ local.push(...failures);
2741
+ yield out;
2742
+ }
2743
+ };
2744
+ n = 0;
2745
+ rows = 0;
2746
+ for await (const batch of organizationBatches(mappedOrgs())) {
2747
+ n++;
2748
+ rows += batch.length;
2749
+ if (!dryRun && state && n <= state.organizations_batches_applied) continue;
2750
+ const answer = await api2.importOrganizations(run2.id, batch, dryRun);
2751
+ report.addOrganizations(answer, batch);
2752
+ io.info(`${label}: organizations batch ${n} (${rows} rows) ${answer.counts.created} created, ${answer.counts.updated} updated, ${answer.counts.failed} failed`);
2753
+ if (!dryRun && state) {
2754
+ state.organizations_batches_applied = n;
2755
+ state.updated_at = io.now().toISOString();
2756
+ await saveState(settings2.file.path, state);
2757
+ }
2758
+ }
2759
+ report.addLocalFailures(local);
2760
+ if (!dryRun && state) {
2761
+ state.phase = "done";
2762
+ await saveState(settings2.file.path, state);
2763
+ }
2764
+ return report.build();
2765
+ }
2766
+ async function runImport(api2, source, settings2, io) {
2767
+ const { run: run2, state } = await resolveRun(api2, settings2, io);
2768
+ const dry = await pass(api2, run2, source, settings2, io, true, void 0);
2769
+ if (!settings2.apply) return { run: run2, dry_run: dry };
2770
+ for (const line of renderReport(dry)) io.info(line);
2771
+ const rows = dry.users.created + dry.users.updated + dry.organizations.created + dry.organizations.updated + dry.organizations.pending_users;
2772
+ const failing = dry.users.failed + dry.organizations.failed;
2773
+ const question = `Apply to run ${run2.id}: ${rows} rows written${failing > 0 ? `, ${failing} failing` : ""}?`;
2774
+ if (!await io.confirm(question)) {
2775
+ throw cancelled("Not applied. The dry run above is what --apply would do; pass --yes to apply without asking.", { run_id: run2.id, dry_run: dry });
2776
+ }
2777
+ const applied = await pass(api2, run2, source, settings2, io, false, state);
2778
+ const after = await api2.getRun(run2.id);
2779
+ return { run: after, dry_run: dry, applied, run_counts: after.counts };
2780
+ }
2781
+ const SOURCE_TYPES = [
2782
+ "auth0",
2783
+ "clerk",
2784
+ "supabase",
2785
+ "lovable_cloud",
2786
+ "firebase",
2787
+ "cognito",
2788
+ "nextauth",
2789
+ "better_auth",
2790
+ "replit_auth",
2791
+ "other"
2792
+ ];
2793
+ const options = {
2794
+ // export
2795
+ out: { type: "string", short: "o" },
2796
+ force: { type: "boolean" },
2797
+ // provider flags
2798
+ connection: { type: "string" },
2799
+ hashes: { type: "string" },
2800
+ csv: { type: "string" },
2801
+ "db-url": { type: "string" },
2802
+ "user-pool-id": { type: "string" },
2803
+ "external-id": { type: "string" },
2804
+ "skip-organizations": { type: "boolean" },
2805
+ // import and run
2806
+ run: { type: "string" },
2807
+ source: { type: "string" },
2808
+ name: { type: "string" },
2809
+ apply: { type: "boolean" },
2810
+ "on-existing": { type: "string" },
2811
+ "allow-weak-passwords": { type: "boolean" },
2812
+ "identity-connection": { type: "string", multiple: true },
2813
+ "totp-app": { type: "string", multiple: true },
2814
+ "no-events": { type: "boolean" },
2815
+ "role-map": { type: "string", multiple: true },
2816
+ "delete-after": { type: "boolean" },
2817
+ // records
2818
+ outcome: { type: "string" },
2819
+ kind: { type: "string" },
2820
+ // source
2821
+ type: { type: "string" },
2822
+ "hash-config": { type: "string" },
2823
+ "salt-separator": { type: "string" },
2824
+ rounds: { type: "string" },
2825
+ "mem-cost": { type: "string" },
2826
+ file: { type: "string" },
2827
+ email: { type: "string" }
2828
+ };
2829
+ const help = `Subcommands:
2830
+ export <provider> [--out pontive-users.ndjson] [provider flags]
2831
+ Writes the provider's users and organizations as pontive-users/v1 NDJSON
2832
+ (mode 0600: the file holds password hashes and TOTP secrets).
2833
+ import <file> [--run uimp_…] [--source msrc_…] [--apply] [--yes]
2834
+ Dry-runs the file against the instance; with --apply, applies it after
2835
+ the dry run and a confirmation. Resumable: progress is kept in
2836
+ .pontive-import-state.json beside the file.
2837
+ run <provider> [--source msrc_…] [--apply] [--yes]
2838
+ export and import in one go, with nothing written to disk.
2839
+ status [uimp_…] A run, or the latest runs.
2840
+ records <uimp_…> [--outcome failed] [--kind user|organization]
2841
+ revert <uimp_…> [--apply] [--yes] Dry run, or deletes what the run created.
2842
+ source create --name <name> --type <source_type> [--hash-config <file>]
2843
+ source get|validate|delete <msrc_…>
2844
+ source update <msrc_…> [--name <name>] [--hash-config <file>]
2845
+ source list
2846
+
2847
+ Providers: ${[...EXPORTERS.values()].map((e) => `
2848
+ ${e.provider.padEnd(9)} ${e.summary}`).join("")}
2849
+
2850
+ Provider flags:
2851
+ --external-id legacy|none external_id = the source's user id (default), or unset
2852
+ --skip-organizations auth0, clerk: users only
2853
+ --connection con_… auth0: one database connection
2854
+ --hashes <file> auth0: support's password hash export, decrypted
2855
+ --csv <file> clerk: the dashboard's user export
2856
+ --db-url <url> supabase: prefer SUPABASE_DB_URL
2857
+ --user-pool-id <id> cognito
2858
+
2859
+ Import options (fixed on a run once its first batch is applied):
2860
+ --name <name> The run's name
2861
+ --on-existing skip|update A row matching an existing user (default skip)
2862
+ --allow-weak-passwords Imported passwords that break the policy are not forced to change
2863
+ --identity-connection <type>=app_…:<slug> Import external identities of that type (repeatable)
2864
+ --totp-app app_… Store TOTP secrets under this app's issuer (repeatable)
2865
+ --no-events No pontive.user.created per imported user
2866
+ --role-map a=b,c=d Organization roles; an unmapped role fails its member
2867
+ --delete-after Delete the file and its state once applied
2868
+
2869
+ Source options:
2870
+ --type ${SOURCE_TYPES.join("|")}
2871
+ --hash-config <file> firebase: the console's Password hash parameters
2872
+ --salt-separator, --rounds, --mem-cost firebase, with the signer key in FIREBASE_SIGNER_KEY
2873
+ validate: --file <export> --email <user> checks the parameters against that
2874
+ user's hash, with their password in PONTIVE_SAMPLE_PASSWORD
2875
+
2876
+ Environment:
2877
+ PONTIVE_SECRET_KEY The instance's secret key (required; never a flag)
2878
+ PONTIVE_MGMT_URL Another management API (development), e.g. https://api.us.pontive-dev.com
2879
+ Each provider's own credentials, as listed above.`;
2880
+ function api(ctx) {
2881
+ return PontiveApi2.fromEnv(ctx.env, {
2882
+ fetch: ctx.fetch,
2883
+ sleep: ctx.sleep,
2884
+ signal: ctx.signal,
2885
+ onRetry: (message) => ctx.out.info(message)
2886
+ });
2887
+ }
2888
+ function exportContext(ctx) {
2889
+ return {
2890
+ env: ctx.env,
2891
+ flags: ctx.values,
2892
+ cwd: ctx.cwd,
2893
+ fetch: ctx.fetch,
2894
+ sleep: ctx.sleep,
2895
+ signal: ctx.signal,
2896
+ info: (m) => ctx.out.info(m),
2897
+ warn: (m) => ctx.out.warn(m),
2898
+ now: ctx.now,
2899
+ load: (specifier, install2) => loadOptional(ctx.cwd, specifier, install2)
2900
+ };
2901
+ }
2902
+ function requireConsentAvailable(ctx, what) {
2903
+ if (ctx.yes || !ctx.agentMode && ctx.interactive) return;
2904
+ const why = ctx.agentMode ? "Agent mode never prompts" : "There is no terminal to ask on";
2905
+ throw cancelled(`${what} writes to the instance. ${why}: pass --yes to consent, after reading the dry run (run it without --apply).`, {
2906
+ hint: "Re-run without --apply to see the dry run, then with --apply --yes."
2907
+ });
2908
+ }
2909
+ function runOptions(ctx) {
2910
+ const v = ctx.values;
2911
+ const onExisting = flagString(v, "on-existing") ?? "skip";
2912
+ if (onExisting !== "skip" && onExisting !== "update") throw new CliError("invalid_arguments", `--on-existing is skip or update; got "${onExisting}".`);
2913
+ const totpApps = flagStrings(v, "totp-app");
2914
+ for (const app of totpApps) if (!app.startsWith("app_")) throw new CliError("invalid_arguments", `--totp-app takes an app id (app_…); got "${app}".`);
2915
+ const connections = parseIdentityConnections(flagStrings(v, "identity-connection"));
2916
+ return {
2917
+ options: {
2918
+ on_existing: onExisting,
2919
+ password_policy_violation: v["allow-weak-passwords"] ? "allow" : "require_change",
2920
+ identity_connections: connections,
2921
+ totp_app_ids: totpApps,
2922
+ emit_events: !v["no-events"]
2923
+ },
2924
+ fromFlags: v["on-existing"] !== void 0 || Boolean(v["allow-weak-passwords"]) || connections.length > 0 || totpApps.length > 0 || Boolean(v["no-events"])
2925
+ };
2926
+ }
2927
+ function settings(ctx, sourceType, file) {
2928
+ const { options: opts, fromFlags } = runOptions(ctx);
2929
+ const runId = flagString(ctx.values, "run");
2930
+ const sourceId = flagString(ctx.values, "source");
2931
+ if (runId && !runId.startsWith("uimp_")) throw new CliError("invalid_arguments", `--run takes a run id (uimp_…); got "${runId}".`);
2932
+ if (sourceId && !sourceId.startsWith("msrc_")) throw new CliError("invalid_arguments", `--source takes a migration source id (msrc_…); got "${sourceId}".`);
2933
+ if (runId && sourceId) ctx.out.warn("--source is ignored with --run: the run already names its source.");
2934
+ const date = ctx.now().toISOString().slice(0, 10);
2935
+ return {
2936
+ runId,
2937
+ sourceId,
2938
+ name: flagString(ctx.values, "name") ?? `${sourceType ?? "pontive-users"} import ${date}`,
2939
+ options: opts,
2940
+ optionsFromFlags: fromFlags,
2941
+ roleMap: parseRoleMap(flagStrings(ctx.values, "role-map")),
2942
+ apply: ctx.values.apply === true,
2943
+ file
2944
+ };
2945
+ }
2946
+ function importResult(result, extra = {}) {
2947
+ const final = result.applied ?? result.dry_run;
2948
+ const human = renderReport(final);
2949
+ if (result.run_counts) {
2950
+ const c = result.run_counts;
2951
+ human.push("", `Run ${result.run.id} totals: ${Object.entries(c).map(([k, n]) => `${k} ${n}`).join(", ")}`);
2952
+ }
2953
+ return {
2954
+ data: {
2955
+ run_id: result.run.id,
2956
+ applied: result.applied !== void 0,
2957
+ report: final,
2958
+ ...result.applied ? { dry_run_report: result.dry_run, run_counts: result.run_counts } : {},
2959
+ ...extra
2960
+ },
2961
+ human
2962
+ };
2963
+ }
2964
+ const CREDENTIAL_WARNING = "This file holds password hashes and TOTP secrets: keep it private, never commit it, and delete it once imported (import --delete-after does).";
2965
+ async function exportCommand(ctx) {
2966
+ const e = exporter(ctx.positionals[1]);
2967
+ const out = resolve(ctx.cwd, flagString(ctx.values, "out") ?? "pontive-users.ndjson");
2968
+ const force = ctx.values.force === true;
2969
+ if (existsSync(out) && !force) throw new CliError("file_exists", `${out} exists. Pass --force to replace it, or --out another file.`);
2970
+ const writer = new FileWriter(out, force);
2971
+ let stats;
2972
+ try {
2973
+ stats = await runExport(e, exportContext(ctx), (line) => writer.write(line));
2974
+ } finally {
2975
+ await writer.close().catch(() => void 0);
2976
+ }
2977
+ ctx.out.warn(CREDENTIAL_WARNING);
2978
+ return {
2979
+ data: { provider: e.provider, file: out, export: stats.toJSON(), warning: CREDENTIAL_WARNING },
2980
+ human: [`Exported to ${out}.`, ...exportLines(stats), "", `Next: pontive migrate import ${basename(out)} (a dry run), then with --apply.`]
2981
+ };
2982
+ }
2983
+ function exportLines(stats) {
2984
+ const s = stats.toJSON();
2985
+ const lines = [
2986
+ ` users: ${s.users}`,
2987
+ ` organizations: ${s.organizations} (${s.members} memberships)`,
2988
+ ` password users without a hash (they reset by email): ${s.password_users_without_hash}`
2989
+ ];
2990
+ if (s.totp_not_exported > 0) lines.push(` users with TOTP that could not be exported (they enroll again): ${s.totp_not_exported}`);
2991
+ for (const [reason, { count, keys }] of Object.entries(s.skipped_users)) {
2992
+ lines.push(` users left out, ${reason}: ${count} (${keys.slice(0, 10).join(", ")}${count > 10 ? ", …" : ""})`);
2993
+ }
2994
+ for (const [key, count] of Object.entries(s.skipped_identities)) {
2995
+ const [reason, provider] = key.split(/:(.*)/s);
2996
+ lines.push(
2997
+ reason === "not_portable" ? ` ${provider} identities left out (not portable; they re-link by email): ${count}` : ` ${provider} identities left out (no Pontive connection type): ${count}`
2998
+ );
2999
+ }
3000
+ for (const note of s.notes) lines.push(` note: ${note}`);
3001
+ return lines;
3002
+ }
3003
+ async function importCommand(ctx) {
3004
+ const name = ctx.positionals[1];
3005
+ if (!name) throw new CliError("invalid_arguments", "Name the file: pontive migrate import <file>.");
3006
+ const path = resolve(ctx.cwd, name);
3007
+ if (!existsSync(path)) throw new CliError("file_not_found", `${path} does not exist.`);
3008
+ if (ctx.values.apply) requireConsentAvailable(ctx, "import --apply");
3009
+ if (ctx.values["delete-after"] && !ctx.values.apply) throw new CliError("invalid_arguments", "--delete-after needs --apply.");
3010
+ let sourceType;
3011
+ for await (const line of readLines(path)) {
3012
+ if (line.kind === "header") sourceType = line.header.source_type;
3013
+ break;
3014
+ }
3015
+ const sha256 = await fingerprint(path);
3016
+ const result = await runImport(api(ctx), fileSource(path), settings(ctx, sourceType, { path, sha256 }), importIo(ctx));
3017
+ if (result.applied && ctx.values["delete-after"]) {
3018
+ await rm(path, { force: true });
3019
+ await removeState(path);
3020
+ ctx.out.info(`Deleted ${path} and its state.`);
3021
+ }
3022
+ return importResult(result);
3023
+ }
3024
+ function importIo(ctx) {
3025
+ return {
3026
+ info: (m) => ctx.out.info(m),
3027
+ warn: (m) => ctx.out.warn(m),
3028
+ confirm: (q) => confirm(ctx, q),
3029
+ now: ctx.now
3030
+ };
3031
+ }
3032
+ async function runCommand(ctx) {
3033
+ const e = exporter(ctx.positionals[1]);
3034
+ if (ctx.values.apply) requireConsentAvailable(ctx, "run --apply");
3035
+ if (!flagString(ctx.values, "source") && !flagString(ctx.values, "run")) {
3036
+ throw new CliError(
3037
+ "migration_source_required",
3038
+ `Exported rows carry each user's ${e.provider} id as legacy_subject, which needs a migration source: pontive migrate source create --name "${e.provider}" --type ${e.sourceType}, then pass --source msrc_….`
3039
+ );
3040
+ }
3041
+ const s = settings(ctx, e.sourceType);
3042
+ const users2 = [];
3043
+ const organizations = [];
3044
+ const stats = await runExport(e, exportContext(ctx), async (line) => {
3045
+ if (line.kind === "user") users2.push(line.user);
3046
+ else if (line.kind === "organization") organizations.push(line.organization);
3047
+ });
3048
+ ctx.out.info(`Exported ${stats.users} users and ${stats.organizations} organizations from ${e.provider}.`);
3049
+ const source = memorySource(users2, organizations, stats.summary());
3050
+ const result = await runImport(api(ctx), source, s, importIo(ctx));
3051
+ const out = importResult(result, { provider: e.provider, export: stats.toJSON() });
3052
+ out.human = [`Exported from ${e.provider}:`, ...exportLines(stats), "", ...out.human];
3053
+ return out;
3054
+ }
3055
+ function runLines(run2) {
3056
+ const counts = Object.entries(run2.counts ?? {}).map(([k, n]) => `${k} ${n}`).join(", ");
3057
+ return [`${run2.id} ${run2.status} ${run2.name} (created ${run2.created_at}${run2.migration_source_id ? `, source ${run2.migration_source_id}` : ""})`, ...counts ? [` ${counts}`] : []];
3058
+ }
3059
+ async function statusCommand(ctx) {
3060
+ const id = ctx.positionals[1];
3061
+ const client = api(ctx);
3062
+ if (id) {
3063
+ const run2 = await client.getRun(id);
3064
+ return { data: { run: run2 }, human: [...runLines(run2), ` options: ${JSON.stringify(run2.options)}`] };
3065
+ }
3066
+ const page = await client.listRuns(1, 20);
3067
+ return {
3068
+ data: { runs: page.data, pagination: page.pagination },
3069
+ human: page.data.length === 0 ? ["No import runs."] : page.data.flatMap(runLines)
3070
+ };
3071
+ }
3072
+ async function recordsCommand(ctx) {
3073
+ const id = ctx.positionals[1];
3074
+ if (!id) throw new CliError("invalid_arguments", "Name the run: pontive migrate records <uimp_…>.");
3075
+ const outcome = flagString(ctx.values, "outcome");
3076
+ const kind = flagString(ctx.values, "kind");
3077
+ if (outcome && !["created", "updated", "skipped", "failed"].includes(outcome)) {
3078
+ throw new CliError("invalid_arguments", `--outcome is created, updated, skipped or failed; got "${outcome}".`);
3079
+ }
3080
+ if (kind && kind !== "user" && kind !== "organization") throw new CliError("invalid_arguments", `--kind is user or organization; got "${kind}".`);
3081
+ const client = api(ctx);
3082
+ const records = [];
3083
+ let total = 0;
3084
+ for (let page = 1; ; page++) {
3085
+ const answer = await client.listRecords(id, { page, limit: 100, outcome, kind });
3086
+ records.push(...answer.data);
3087
+ total = answer.pagination.total;
3088
+ if (page >= answer.pagination.total_pages || answer.data.length === 0) break;
3089
+ }
3090
+ const human = records.map((r) => {
3091
+ const errors = (r.errors ?? []).map((e) => `${e.code}${e.field ? ` ${e.field}` : ""}${e.message ? `: ${e.message}` : ""}`).join("; ");
3092
+ return `${r.kind.padEnd(12)} batch ${r.batch} #${r.index} ${r.outcome.padEnd(7)} ${r.key}${r.reverted ? " (reverted)" : ""}${errors ? ` ${errors}` : ""}`;
3093
+ });
3094
+ return { data: { run_id: id, total, records }, human: human.length > 0 ? human : ["No records."] };
3095
+ }
3096
+ async function revertCommand(ctx) {
3097
+ const id = ctx.positionals[1];
3098
+ if (!id) throw new CliError("invalid_arguments", "Name the run: pontive migrate revert <uimp_…>.");
3099
+ const apply = ctx.values.apply === true;
3100
+ if (apply) requireConsentAvailable(ctx, "revert --apply");
3101
+ const client = api(ctx);
3102
+ const dry = await client.revert(id, true);
3103
+ const dryLines = [
3104
+ `Dry run of reverting ${id}: nothing was deleted.`,
3105
+ ` users to delete: ${dry.users_deleted}, organizations to delete: ${dry.organizations_deleted}, kept: ${dry.kept.length}${dry.remaining > 0 ? `, ${dry.remaining} more records after these` : ""}`,
3106
+ ...keptLines(dry.kept)
3107
+ ];
3108
+ if (!apply) return { data: { run_id: id, applied: false, dry_run: dry }, human: [...dryLines, "", `Delete them: pontive migrate revert ${id} --apply`] };
3109
+ for (const line of dryLines) ctx.out.info(line);
3110
+ if (!await confirm(ctx, `Delete what run ${id} created? This cannot be undone.`)) throw cancelled("Not reverted.", { run_id: id, dry_run: dry });
3111
+ const total = { users_deleted: 0, organizations_deleted: 0, kept: [], calls: 0 };
3112
+ for (; ; ) {
3113
+ const answer = await client.revert(id, false);
3114
+ total.calls++;
3115
+ total.users_deleted += answer.users_deleted;
3116
+ total.organizations_deleted += answer.organizations_deleted;
3117
+ total.kept.push(...answer.kept);
3118
+ ctx.out.info(`Reverting: ${total.users_deleted} users and ${total.organizations_deleted} organizations deleted, ${answer.remaining} records remaining.`);
3119
+ if (answer.remaining === 0) break;
3120
+ }
3121
+ return {
3122
+ data: { run_id: id, applied: true, ...total },
3123
+ human: [`Reverted ${id}: ${total.users_deleted} users and ${total.organizations_deleted} organizations deleted, ${total.kept.length} kept.`, ...keptLines(total.kept)]
3124
+ };
3125
+ }
3126
+ function keptLines(kept) {
3127
+ const byReason = /* @__PURE__ */ new Map();
3128
+ for (const k of kept) byReason.set(k.reason, [...byReason.get(k.reason) ?? [], k.user_id ?? k.organization_id ?? "?"]);
3129
+ return [...byReason].map(([reason, ids]) => ` kept, ${reason}: ${ids.length} (${ids.slice(0, 10).join(", ")}${ids.length > 10 ? ", …" : ""})`);
3130
+ }
3131
+ function sourceLines(s) {
3132
+ const fb = s.hash_config?.firebase_scrypt;
3133
+ return [
3134
+ `${s.id} ${s.source_type} ${s.name}${s.imported_passwords !== void 0 ? ` (${s.imported_passwords} imported passwords pending)` : ""}`,
3135
+ ...fb ? [` firebase_scrypt: signer key ${fb.signer_key_preview ?? "set"}, rounds ${fb.rounds}, mem_cost ${fb.mem_cost}`] : []
3136
+ ];
3137
+ }
3138
+ async function hashConfigFlags(ctx, complete) {
3139
+ const file = flagString(ctx.values, "hash-config");
3140
+ const config = await readHashConfig(
3141
+ {
3142
+ file: file ? resolve(ctx.cwd, file) : void 0,
3143
+ saltSeparator: flagString(ctx.values, "salt-separator"),
3144
+ rounds: flagString(ctx.values, "rounds"),
3145
+ memCost: flagString(ctx.values, "mem-cost"),
3146
+ env: ctx.env
3147
+ },
3148
+ complete
3149
+ );
3150
+ return config ? { firebase_scrypt: config } : void 0;
3151
+ }
3152
+ async function sourceCommand(ctx) {
3153
+ const action = ctx.positionals[1];
3154
+ const id = ctx.positionals[2];
3155
+ const client = api(ctx);
3156
+ const needId = () => {
3157
+ if (!id) throw new CliError("invalid_arguments", `Name the source: pontive migrate source ${action} <msrc_…>.`);
3158
+ return id;
3159
+ };
3160
+ switch (action) {
3161
+ case "list": {
3162
+ const page = await client.listSources();
3163
+ return { data: { sources: page.data, pagination: page.pagination }, human: page.data.length === 0 ? ["No migration sources."] : page.data.flatMap(sourceLines) };
3164
+ }
3165
+ case "get": {
3166
+ const s = await client.getSource(needId());
3167
+ return { data: { source: s }, human: sourceLines(s) };
3168
+ }
3169
+ case "create": {
3170
+ const name = flagString(ctx.values, "name");
3171
+ const type = flagString(ctx.values, "type");
3172
+ if (!name || !type) throw new CliError("invalid_arguments", "source create needs --name and --type.");
3173
+ if (!SOURCE_TYPES.includes(type)) throw new CliError("invalid_arguments", `--type is one of ${SOURCE_TYPES.join(", ")}.`);
3174
+ const hash = await hashConfigFlags(ctx, true);
3175
+ if (type === "firebase" && !hash) ctx.out.warn("A firebase source without --hash-config cannot verify imported Firebase hashes; add it with source update.");
3176
+ const s = await client.createSource({ name, source_type: type, hash_config: hash ?? {} });
3177
+ return { data: { source: s }, human: [`Created ${s.id}.`, ...sourceLines(s), "", `Import with --source ${s.id}.`] };
3178
+ }
3179
+ case "update": {
3180
+ const hash = await hashConfigFlags(ctx, false);
3181
+ const name = flagString(ctx.values, "name");
3182
+ if (!hash && !name) throw new CliError("invalid_arguments", "source update needs --name or hash parameters.");
3183
+ const s = await client.updateSource(needId(), { ...name ? { name } : {}, ...hash ? { hash_config: hash } : {} });
3184
+ return { data: { source: s }, human: [`Updated ${s.id}.`, ...sourceLines(s)] };
3185
+ }
3186
+ case "validate": {
3187
+ const sourceId = needId();
3188
+ const sample = await validationSample(ctx);
3189
+ const answer = await client.validateSource(sourceId, sample ? { firebase_scrypt_sample: sample } : {});
3190
+ const failed = answer.checks.some((c) => c.status === "failed");
3191
+ return {
3192
+ exitCode: failed ? 1 : 0,
3193
+ data: { source_id: sourceId, checks: answer.checks },
3194
+ human: answer.checks.map((c) => `${c.status === "ok" ? "ok " : "FAILED"} ${c.check}${c.detail ? `: ${c.detail}` : ""}`)
3195
+ };
3196
+ }
3197
+ case "delete": {
3198
+ const sourceId = needId();
3199
+ requireConsentAvailable(ctx, "source delete");
3200
+ if (!await confirm(ctx, `Delete migration source ${sourceId} and its users' legacy identities?`)) throw cancelled("Not deleted.");
3201
+ await client.deleteSource(sourceId);
3202
+ return { data: { source_id: sourceId, deleted: true }, human: [`Deleted ${sourceId}.`] };
3203
+ }
3204
+ default:
3205
+ throw new CliError("invalid_arguments", "pontive migrate source create|get|update|validate|list|delete.");
3206
+ }
3207
+ }
3208
+ async function validationSample(ctx) {
3209
+ const file = flagString(ctx.values, "file");
3210
+ const email = flagString(ctx.values, "email");
3211
+ if (!file && !email) return void 0;
3212
+ if (!file || !email) throw new CliError("invalid_arguments", "validate takes --file and --email together.");
3213
+ const password = ctx.env.PONTIVE_SAMPLE_PASSWORD;
3214
+ if (!password) throw new CliError("invalid_arguments", "Set PONTIVE_SAMPLE_PASSWORD to that user's password; it is read from the environment only.");
3215
+ for await (const line of readLines(resolve(ctx.cwd, file))) {
3216
+ if (line.kind !== "user" || line.user.email?.toLowerCase() !== email.toLowerCase()) continue;
3217
+ const hash = line.user.password_hash;
3218
+ if (hash?.hasher !== "firebase_scrypt" || !hash.salt) throw new CliError("invalid_arguments", `${email} has no firebase_scrypt hash in ${file}.`);
3219
+ return { password, hash: hash.value, salt: hash.salt };
3220
+ }
3221
+ throw new CliError("invalid_arguments", `${email} is not in ${file}.`);
3222
+ }
3223
+ const SUBCOMMANDS = {
3224
+ export: exportCommand,
3225
+ import: importCommand,
3226
+ run: runCommand,
3227
+ status: statusCommand,
3228
+ records: recordsCommand,
3229
+ revert: revertCommand,
3230
+ source: sourceCommand
3231
+ };
3232
+ const migrate = {
3233
+ name: "migrate",
3234
+ summary: "Move users and organizations from Auth0, Clerk, Supabase, Firebase or Cognito into Pontive",
3235
+ help,
3236
+ options,
3237
+ allowPositionals: true,
3238
+ async run(ctx) {
3239
+ const sub = ctx.positionals[0];
3240
+ const handler = sub ? SUBCOMMANDS[sub] : void 0;
3241
+ if (!handler) {
3242
+ throw new CliError("invalid_arguments", `pontive migrate ${Object.keys(SUBCOMMANDS).join("|")}. See pontive migrate --help.`);
3243
+ }
3244
+ return handler(ctx);
3245
+ }
3246
+ };
3247
+ const __vite_glob_0_2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3248
+ __proto__: null,
3249
+ command: migrate
3250
+ }, Symbol.toStringTag, { value: "Module" }));
3251
+ async function run$1(ctx) {
3252
+ const keyless = readKeyless(ctx.cwd);
3253
+ const envFile = readEnvFile(ctx.cwd);
3254
+ const set = CONTRACT_VARIABLES.filter((name) => Boolean(envFile.get(name) || ctx.env[name]));
3255
+ const missing = CONTRACT_VARIABLES.filter((name) => !set.includes(name));
3256
+ const variables = { set, missing };
3257
+ let state;
3258
+ let live;
3259
+ let checked = false;
3260
+ if (!keyless) {
3261
+ state = envFile.get("PONTIVE_ISSUER") || ctx.env.PONTIVE_ISSUER ? "configured" : "none";
3262
+ } else if (!keyless.claim_token) {
3263
+ state = "claimed";
3264
+ } else if (ctx.values.offline === true) {
3265
+ state = isExpired(keyless, ctx.now()) ? "expired" : "unclaimed";
3266
+ } else {
3267
+ try {
3268
+ live = await apiFor(ctx).getUnclaimed(keyless.instance_id, keyless.claim_token);
3269
+ checked = true;
3270
+ state = live.status === "claimed" ? "claimed" : "unclaimed";
3271
+ if (state === "claimed") await markClaimed(ctx);
3272
+ } catch (error) {
3273
+ if (error instanceof CliError && error.exitCode === ExitCode.ExpiredOrClaimedAway) {
3274
+ checked = true;
3275
+ state = "expired";
3276
+ } else if (error instanceof CliError && error.exitCode === ExitCode.RateLimited) {
3277
+ throw error;
3278
+ } else {
3279
+ ctx.out.warn(`Could not reach Pontive (${error instanceof Error ? error.message : String(error)}); showing what is on disk.`);
3280
+ state = isExpired(keyless, ctx.now()) ? "expired" : "unclaimed";
3281
+ }
3282
+ }
3283
+ }
3284
+ const issuer = keyless?.issuer ?? envFile.get("PONTIVE_ISSUER") ?? ctx.env.PONTIVE_ISSUER;
3285
+ const instanceId = keyless?.instance_id ?? envFile.get("PONTIVE_INSTANCE_ID") ?? ctx.env.PONTIVE_INSTANCE_ID;
3286
+ const expiresAt = state === "unclaimed" || state === "expired" ? live?.expires_at ?? keyless?.expires_at : void 0;
3287
+ const instance = state === "none" ? null : {
3288
+ instance_id: instanceId ?? null,
3289
+ region: live?.region ?? keyless?.region ?? null,
3290
+ issuer: issuer ?? null,
3291
+ app_id: keyless?.app_id ?? envFile.get("PONTIVE_CLIENT_ID") ?? null,
3292
+ status: state,
3293
+ ...expiresAt ? { expires_at: expiresAt } : {},
3294
+ ...live?.claimed_at ? { claimed_at: live.claimed_at } : {},
3295
+ checked_with_pontive: checked
3296
+ };
3297
+ const describe = {
3298
+ unclaimed: `unclaimed, deleted on ${expiresAt ? humanDate(expiresAt) : "?"} unless claimed (pontive claim)`,
3299
+ claimed: "claimed",
3300
+ expired: `expired${expiresAt ? ` on ${humanDate(expiresAt)}` : ""}; run pontive init --reset for a new one`,
3301
+ configured: `configured in ${ENV_FILE}`,
3302
+ none: "none; run pontive init"
3303
+ };
3304
+ const human = [
3305
+ `Instance: ${instance?.instance_id ?? "-"}`,
3306
+ `Region: ${instance?.region ?? "-"}`,
3307
+ `Issuer: ${instance?.issuer ?? "-"}`,
3308
+ `Status: ${describe[state]}`,
3309
+ `Set: ${set.length > 0 ? set.join(", ") : "-"}`,
3310
+ ...missing.length > 0 ? [`Not set: ${missing.join(", ")}`] : [],
3311
+ ...keyless ? [] : [`(no ${KEYLESS_FILE})`]
3312
+ ];
3313
+ return {
3314
+ exitCode: state === "expired" ? ExitCode.ExpiredOrClaimedAway : ExitCode.Success,
3315
+ data: { instance, variables },
3316
+ human
3317
+ };
3318
+ }
3319
+ const command = {
3320
+ name: "status",
3321
+ summary: "Show this app's Pontive instance and which PONTIVE_* variables are set",
3322
+ help: `Shows the instance, its region, when it is deleted unless claimed (or that it
3323
+ is claimed), and which PONTIVE_* variables ${ENV_FILE} or the environment set.
3324
+ Values are never printed. Exits 5 when the unclaimed instance has expired.
3325
+
3326
+ Options:
3327
+ --offline Do not ask Pontive; show what is on disk`,
3328
+ options: {
3329
+ offline: { type: "boolean" }
3330
+ },
3331
+ run: run$1
3332
+ };
3333
+ const __vite_glob_0_3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3334
+ __proto__: null,
3335
+ command
3336
+ }, Symbol.toStringTag, { value: "Module" }));
3337
+ const AGENT_VARIABLES = [
3338
+ ["CLAUDECODE", "claude-code"],
3339
+ ["CURSOR_AGENT", "cursor"],
3340
+ ["CODEX_SANDBOX", "codex"],
3341
+ ["GEMINI_CLI", "gemini-cli"]
3342
+ ];
3343
+ function isSet(value) {
3344
+ return value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
3345
+ }
3346
+ function detectAgent(env) {
3347
+ for (const [variable, agent] of AGENT_VARIABLES) {
3348
+ if (isSet(env[variable])) return agent;
3349
+ }
3350
+ return void 0;
3351
+ }
3352
+ function isAgentMode(env, json) {
3353
+ return json || detectAgent(env) !== void 0 || isSet(env.CI);
3354
+ }
3355
+ const modules = /* @__PURE__ */ Object.assign({ "./commands/claim.ts": __vite_glob_0_0, "./commands/init.ts": __vite_glob_0_1, "./commands/migrate.ts": __vite_glob_0_2, "./commands/status.ts": __vite_glob_0_3 });
45
3356
  const commands = new Map(
46
3357
  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
3358
  );
@@ -72,13 +3383,13 @@ Agent mode is on when CLAUDECODE, CURSOR_AGENT, CODEX_SANDBOX, GEMINI_CLI or CI
72
3383
  Exit codes: 0 success, 1 error, 2 cancelled, 3 rate limited, 4 sign-in required,
73
3384
  5 the unclaimed instance expired or was claimed away.`;
74
3385
  }
75
- async function main(options) {
76
- const { argv, env, out, version } = options;
3386
+ async function main(options2) {
3387
+ const { argv, env, out, version } = options2;
77
3388
  const name = argv[0];
78
3389
  const wantsJson = argv.includes("--json");
79
3390
  const agentMode = isAgentMode(env, wantsJson);
80
3391
  const report = (commandName, error) => {
81
- const err = error instanceof CliError ? error : options.signal.aborted ? new CliError("cancelled", "Cancelled.", ExitCode.Cancelled) : new CliError("internal_error", error instanceof Error ? error.message : String(error));
3392
+ const err = error instanceof CliError ? error : options2.signal.aborted ? new CliError("cancelled", "Cancelled.", ExitCode.Cancelled) : new CliError("internal_error", error instanceof Error ? error.message : String(error));
82
3393
  if (agentMode) {
83
3394
  out.result(JSON.stringify({ ok: false, command: commandName ?? null, error: { code: err.code, message: err.message }, ...err.extra }));
84
3395
  } else {
@@ -94,14 +3405,14 @@ async function main(options) {
94
3405
  out.result(agentMode ? JSON.stringify({ ok: true, command: "version", version }) : version);
95
3406
  return ExitCode.Success;
96
3407
  }
97
- const command = commands.get(name);
98
- if (!command) return report(void 0, new CliError("unknown_command", `Unknown command "${name}". Run pontive --help.`));
3408
+ const command2 = commands.get(name);
3409
+ if (!command2) return report(void 0, new CliError("unknown_command", `Unknown command "${name}". Run pontive --help.`));
99
3410
  let parsed;
100
3411
  try {
101
3412
  parsed = parseArgs({
102
3413
  args: argv.slice(1),
103
- options: { ...GLOBAL_OPTIONS, ...command.options },
104
- allowPositionals: command.allowPositionals ?? false,
3414
+ options: { ...GLOBAL_OPTIONS, ...command2.options },
3415
+ allowPositionals: command2.allowPositionals ?? false,
105
3416
  strict: true
106
3417
  });
107
3418
  } catch (error) {
@@ -109,18 +3420,18 @@ async function main(options) {
109
3420
  }
110
3421
  const { values, positionals } = parsed;
111
3422
  if (values.help) {
112
- out.result(`Usage: pontive ${command.name} [options]
3423
+ out.result(`Usage: pontive ${command2.name} [options]
113
3424
 
114
- ${command.summary}
3425
+ ${command2.summary}
115
3426
 
116
- ${command.help}
3427
+ ${command2.help}
117
3428
 
118
3429
  ${GLOBAL_HELP}`);
119
3430
  return ExitCode.Success;
120
3431
  }
121
3432
  const ctx = {
122
- ...options.runtime(agentMode),
123
- cwd: resolve(options.cwd, typeof values.cwd === "string" ? values.cwd : "."),
3433
+ ...options2.runtime(agentMode),
3434
+ cwd: resolve(options2.cwd, typeof values.cwd === "string" ? values.cwd : "."),
124
3435
  env,
125
3436
  out,
126
3437
  agentMode,
@@ -128,12 +3439,12 @@ ${GLOBAL_HELP}`);
128
3439
  yes: values.yes === true,
129
3440
  values,
130
3441
  positionals,
131
- signal: options.signal,
3442
+ signal: options2.signal,
132
3443
  version
133
3444
  };
134
3445
  let result;
135
3446
  try {
136
- result = await command.run(ctx);
3447
+ result = await command2.run(ctx);
137
3448
  } catch (error) {
138
3449
  return report(name, error);
139
3450
  }
@@ -155,12 +3466,12 @@ function streamOutput(stdout, stderr) {
155
3466
  `)
156
3467
  };
157
3468
  }
158
- function run(command, args, options) {
3469
+ function run(command2, args, options2) {
159
3470
  return new Promise((resolve2) => {
160
- const child = spawn(command, args, {
161
- cwd: options.cwd,
3471
+ const child = spawn(command2, args, {
3472
+ cwd: options2.cwd,
162
3473
  // Agent mode keeps stdout for the one JSON object, so a child's output goes to stderr.
163
- stdio: options.stdio === "inherit" ? "inherit" : ["ignore", process.stderr, process.stderr],
3474
+ stdio: options2.stdio === "inherit" ? "inherit" : ["ignore", process.stderr, process.stderr],
164
3475
  // npm, pnpm and yarn are .cmd shims on Windows.
165
3476
  shell: process.platform === "win32"
166
3477
  });
@@ -176,12 +3487,12 @@ function nodeRuntime(agentMode) {
176
3487
  return {
177
3488
  fetch: (...args) => fetch(...args),
178
3489
  interactive: Boolean(process.stdin.isTTY),
179
- exec: (command, args, options) => run(command, args, { cwd: options.cwd, stdio: agentMode ? "stderr" : "inherit" }),
3490
+ exec: (command2, args, options2) => run(command2, args, { cwd: options2.cwd, stdio: agentMode ? "stderr" : "inherit" }),
180
3491
  async openUrl(url) {
181
3492
  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]];
3493
+ const [command2, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
183
3494
  return new Promise((resolve2) => {
184
- const child = spawn(command, args, { stdio: "ignore", detached: true });
3495
+ const child = spawn(command2, args, { stdio: "ignore", detached: true });
185
3496
  child.on("error", () => resolve2(false));
186
3497
  child.on("spawn", () => {
187
3498
  child.unref();
@@ -190,7 +3501,7 @@ function nodeRuntime(agentMode) {
190
3501
  });
191
3502
  },
192
3503
  async ask(question) {
193
- const rl = createInterface({ input: process.stdin, output: process.stderr });
3504
+ const rl = createInterface$1({ input: process.stdin, output: process.stderr });
194
3505
  try {
195
3506
  const answer = await rl.question(`${question} [y/N] `);
196
3507
  return /^y(es)?$/i.test(answer.trim());
@@ -228,6 +3539,6 @@ const code = await main({
228
3539
  out: streamOutput(process.stdout, process.stderr),
229
3540
  runtime: nodeRuntime,
230
3541
  signal: controller.signal,
231
- version: "1.17.0"
3542
+ version: "1.19.0"
232
3543
  });
233
3544
  process.exitCode = code;