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