pontive 1.18.0 → 1.19.0

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