direct-auth 0.0.0-stage → 0.1.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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +486 -2
  3. package/dist/accounts.d.ts +118 -0
  4. package/dist/accounts.js +314 -0
  5. package/dist/apps.d.ts +85 -0
  6. package/dist/apps.js +449 -0
  7. package/dist/auth.d.ts +396 -0
  8. package/dist/auth.js +699 -0
  9. package/dist/base64.d.ts +20 -0
  10. package/dist/base64.js +45 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +463 -0
  13. package/dist/client.d.ts +170 -0
  14. package/dist/client.js +438 -0
  15. package/dist/codes.d.ts +81 -0
  16. package/dist/codes.js +91 -0
  17. package/dist/crypto.d.ts +11 -0
  18. package/dist/crypto.js +37 -0
  19. package/dist/d1.d.ts +2 -0
  20. package/dist/d1.js +2 -0
  21. package/dist/db/limits.d.ts +16 -0
  22. package/dist/db/limits.js +23 -0
  23. package/dist/db/schema.d.ts +25 -0
  24. package/dist/db/schema.js +136 -0
  25. package/dist/db/sql.d.ts +52 -0
  26. package/dist/db/sql.js +121 -0
  27. package/dist/dns.d.ts +48 -0
  28. package/dist/dns.js +133 -0
  29. package/dist/env.d.ts +39 -0
  30. package/dist/env.js +169 -0
  31. package/dist/index.d.ts +19 -0
  32. package/dist/index.js +14 -0
  33. package/dist/init.d.ts +134 -0
  34. package/dist/init.js +912 -0
  35. package/dist/jwks.d.ts +18 -0
  36. package/dist/jwks.js +63 -0
  37. package/dist/jwt.d.ts +90 -0
  38. package/dist/jwt.js +99 -0
  39. package/dist/keys.d.ts +33 -0
  40. package/dist/keys.js +54 -0
  41. package/dist/messages.d.ts +26 -0
  42. package/dist/messages.js +57 -0
  43. package/dist/migrate-cli.d.ts +82 -0
  44. package/dist/migrate-cli.js +564 -0
  45. package/dist/migrate.d.ts +99 -0
  46. package/dist/migrate.js +396 -0
  47. package/dist/node.d.ts +16 -0
  48. package/dist/node.js +63 -0
  49. package/dist/passkeys.d.ts +126 -0
  50. package/dist/passkeys.js +383 -0
  51. package/dist/passwords.d.ts +53 -0
  52. package/dist/passwords.js +326 -0
  53. package/dist/pgwire.d.ts +86 -0
  54. package/dist/pgwire.js +445 -0
  55. package/dist/phone.d.ts +11 -0
  56. package/dist/phone.js +18 -0
  57. package/dist/postgres.d.ts +2 -0
  58. package/dist/postgres.js +2 -0
  59. package/dist/providers/apple-revoke.d.ts +55 -0
  60. package/dist/providers/apple-revoke.js +113 -0
  61. package/dist/providers/apple.d.ts +28 -0
  62. package/dist/providers/apple.js +51 -0
  63. package/dist/providers/github.d.ts +28 -0
  64. package/dist/providers/github.js +67 -0
  65. package/dist/providers/google.d.ts +23 -0
  66. package/dist/providers/google.js +47 -0
  67. package/dist/providers/identity.d.ts +24 -0
  68. package/dist/providers/identity.js +3 -0
  69. package/dist/proxy.d.ts +19 -0
  70. package/dist/proxy.js +43 -0
  71. package/dist/records.d.ts +91 -0
  72. package/dist/records.js +264 -0
  73. package/dist/scrypt.d.ts +26 -0
  74. package/dist/scrypt.js +179 -0
  75. package/dist/senders/aws.d.ts +13 -0
  76. package/dist/senders/aws.js +47 -0
  77. package/dist/senders/dev.d.ts +6 -0
  78. package/dist/senders/dev.js +13 -0
  79. package/dist/senders/index.d.ts +5 -0
  80. package/dist/senders/index.js +4 -0
  81. package/dist/senders/mail.d.ts +26 -0
  82. package/dist/senders/mail.js +66 -0
  83. package/dist/senders/sms.d.ts +34 -0
  84. package/dist/senders/sms.js +69 -0
  85. package/dist/senders/smtp.d.ts +32 -0
  86. package/dist/senders/smtp.js +145 -0
  87. package/dist/senders/types.d.ts +31 -0
  88. package/dist/senders/types.js +25 -0
  89. package/dist/server.d.ts +67 -0
  90. package/dist/server.js +494 -0
  91. package/dist/sessions.d.ts +74 -0
  92. package/dist/sessions.js +146 -0
  93. package/dist/skill.d.ts +25 -0
  94. package/dist/skill.js +66 -0
  95. package/dist/sources.d.ts +138 -0
  96. package/dist/sources.js +931 -0
  97. package/dist/sqlite.d.ts +2 -0
  98. package/dist/sqlite.js +2 -0
  99. package/dist/stores/d1.d.ts +22 -0
  100. package/dist/stores/d1.js +23 -0
  101. package/dist/stores/postgres.d.ts +33 -0
  102. package/dist/stores/postgres.js +71 -0
  103. package/dist/stores/sqlite.d.ts +27 -0
  104. package/dist/stores/sqlite.js +55 -0
  105. package/dist/supabase.d.ts +71 -0
  106. package/dist/supabase.js +283 -0
  107. package/dist/tui.d.ts +178 -0
  108. package/dist/tui.js +537 -0
  109. package/package.json +90 -4
  110. package/skills/direct-auth/SKILL.md +101 -0
@@ -0,0 +1,931 @@
1
+ /**
2
+ * The other sources of `direct-auth migrate`: Firebase Auth, Clerk and Auth0 from their export files, Auth.js and
3
+ * Better Auth from their tables in the same Postgres database. Each is only a reader: it turns what the service kept
4
+ * into `Account`s, one shape for all, and one writer moves those into direct-auth's tables, once, in one transaction.
5
+ *
6
+ * What a reader keeps: an address or number only once the service had checked it (a password goes with a checked
7
+ * address), Apple, Google and GitHub accounts by their subject, anonymous users as guests (with no claim: their
8
+ * sessions don't come over), and the password hashes direct-auth can check (bcrypt, Firebase's and Better Auth's
9
+ * scrypt), each made PBKDF2 at its first sign-in. An id that isn't a UUID gets a new one, and the old id stays in
10
+ * `{users}.source_id`, for the app's own tables.
11
+ */
12
+ import { MIGRATIONS } from "./db/schema.js";
13
+ /** As migrate's: an id with its middle taken out. (Not imported: migrate.ts imports this file.) */
14
+ const maskId = (id) => (id.length > 10 ? `${id.slice(0, 4)}…${id.slice(-4)}` : "…");
15
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16
+ const idFor = (sourceId) => (UUID.test(sourceId) ? sourceId.toLowerCase() : crypto.randomUUID());
17
+ export function cleanEmail(v) {
18
+ if (typeof v !== "string")
19
+ return undefined;
20
+ const e = v.trim().toLowerCase();
21
+ return /^[^\s@]+@[^\s@]+$/.test(e) && e.length <= 320 ? e : undefined;
22
+ }
23
+ export function cleanPhone(v) {
24
+ if (typeof v !== "string")
25
+ return undefined;
26
+ const digits = v.replace(/[\s().-]/g, "").replace(/^\+/, "");
27
+ return /^[1-9]\d{6,14}$/.test(digits) ? `+${digits}` : undefined;
28
+ }
29
+ const time = (v, fallback) => {
30
+ if (v === null || v === undefined || v === "")
31
+ return fallback;
32
+ const n = typeof v === "number" ? v : /^\d+$/.test(String(v)) ? Number(v) : Date.parse(String(v));
33
+ return Number.isFinite(n) && n > 0 ? Math.round(n) : fallback;
34
+ };
35
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim().slice(0, 500) : undefined);
36
+ /** A count line that only shows when it isn't zero. */
37
+ const left = (counts, label, count, note) => {
38
+ if (count > 0)
39
+ counts.push({ label, count, note, warn: true });
40
+ };
41
+ // --- Firebase Auth ---------------------------------------------------------------------------------------------
42
+ const FIREBASE_PROVIDERS = { "apple.com": "apple", "google.com": "google", "github.com": "github" };
43
+ const B64 = /^[A-Za-z0-9+/]+={0,2}$/;
44
+ /**
45
+ * `firebase auth:export users.json --format=json`: `{ users: [{ localId, email, emailVerified, passwordHash, salt,
46
+ * phoneNumber, displayName, photoUrl, disabled, createdAt, lastSignedInAt, providerUserInfo: [{ providerId, rawId,
47
+ * email }] }] }`. Without the hash parameters the passwords stay behind (an email code still gets those users in).
48
+ */
49
+ /**
50
+ * JSON, a byte order mark ahead of it or not. A file that doesn't parse says so by line, never with its text (a
51
+ * parser's message quotes it, and an export holds addresses and hashes).
52
+ */
53
+ function parseJson(text, what) {
54
+ const t = text.replace(/^\uFEFF/, "");
55
+ try {
56
+ return JSON.parse(t);
57
+ }
58
+ catch {
59
+ let line = 1;
60
+ try {
61
+ // Where it stops: the position a parser gives, as a line number only.
62
+ JSON.parse(t);
63
+ }
64
+ catch (e) {
65
+ const at = /position (\d+)/.exec(e instanceof Error ? e.message : "")?.[1];
66
+ if (at)
67
+ line = t.slice(0, Number(at)).split("\n").length;
68
+ }
69
+ throw new Error(`${what} isn't valid JSON (line ${line})`);
70
+ }
71
+ }
72
+ export function readFirebase(json, hash, o = {}) {
73
+ const now = o.now ?? Date.now();
74
+ const data = parseJson(json, "the export");
75
+ if (!Array.isArray(data.users))
76
+ throw new Error("this isn't a Firebase export: no users list (firebase auth:export users.json --format=json)");
77
+ const accounts = [];
78
+ const counts = [];
79
+ let disabled = 0, unverified = 0, unreadable = 0, noParams = 0, other = 0;
80
+ const others = new Set();
81
+ for (const u of data.users) {
82
+ const uid = text(u.localId);
83
+ if (!uid)
84
+ continue;
85
+ if (u.disabled === true) {
86
+ disabled += 1;
87
+ continue;
88
+ }
89
+ const providers = Array.isArray(u.providerUserInfo) ? u.providerUserInfo : [];
90
+ const a = { sourceId: uid, id: idFor(uid), createdAt: time(u.createdAt, now), lastSignInAt: time(u.lastSignedInAt ?? u.lastLoginAt, 0) || undefined, emails: [], phones: [], name: text(u.displayName), picture: text(u.photoUrl), identities: [] };
91
+ const email = cleanEmail(u.email);
92
+ const hasPassword = typeof u.passwordHash === "string" && u.passwordHash !== "";
93
+ const verified = u.emailVerified === true;
94
+ if (email && (verified || (hasPassword && o.keepUnprovenPasswords)))
95
+ a.emails.push(email);
96
+ else if (email && hasPassword)
97
+ unverified += 1;
98
+ const phone = cleanPhone(u.phoneNumber);
99
+ if (phone)
100
+ a.phones.push(phone);
101
+ if (hasPassword && a.emails.length) {
102
+ if (!hash)
103
+ noParams += 1;
104
+ else if (!B64.test(String(u.passwordHash)) || (typeof u.salt === "string" && u.salt !== "" && !B64.test(u.salt)))
105
+ unreadable += 1;
106
+ else
107
+ a.password = `$fbscrypt$r=${hash.rounds},m=${hash.memCost}$${hash.signerKey}$${hash.saltSeparator}$${u.salt ?? ""}$${u.passwordHash}`;
108
+ }
109
+ for (const p of providers) {
110
+ const id = String(p.providerId ?? "");
111
+ const provider = FIREBASE_PROVIDERS[id];
112
+ if (provider && text(p.rawId))
113
+ a.identities.push({ provider, subject: String(p.rawId), email: cleanEmail(p.email) });
114
+ else if (!["password", "phone", ""].includes(id)) {
115
+ other += 1;
116
+ others.add(id);
117
+ }
118
+ }
119
+ // Anonymous: Firebase keeps nothing to sign in with.
120
+ a.guest = !providers.length && !email && !phone && !hasPassword;
121
+ if (Array.isArray(u.mfaInfo) && u.mfaInfo.length)
122
+ a.mfa = true;
123
+ accounts.push(a);
124
+ }
125
+ left(counts, "Disabled", disabled, "left out");
126
+ left(counts, "Unverified", unverified, "password users whose address Firebase never verified: they move without it and the password (--keep-unproven-passwords moves both)");
127
+ left(counts, "No hash parameters", noParams, "passwords stay behind: give the project's hash parameters, or those users sign in with an email code");
128
+ left(counts, "Unreadable hashes", unreadable, "passwords that aren't Firebase scrypt hashes stay behind: an email code gets those users in");
129
+ left(counts, "Other providers", other, `ways in direct-auth doesn't have (${[...others].join(", ")}): those users need another one`);
130
+ const notes = ["Guests (anonymous users) move with their ids, but their app's Firebase session doesn't: unlike Supabase there is no claim, so a guest starts over in the new version."];
131
+ return { accounts, counts, notes, attention: [], total: data.users.length };
132
+ }
133
+ // --- Clerk -----------------------------------------------------------------------------------------------------
134
+ /** RFC 4180 CSV: quoted fields, doubled quotes, line breaks inside quotes; a line starting with # is a comment. */
135
+ export function parseCsv(input) {
136
+ const rows = [];
137
+ let row = [];
138
+ let field = "";
139
+ let quoted = false;
140
+ let start = true;
141
+ const s = input.replace(/^/, "");
142
+ for (let i = 0; i < s.length; i += 1) {
143
+ const c = s[i];
144
+ if (quoted) {
145
+ if (c === '"' && s[i + 1] === '"') {
146
+ field += '"';
147
+ i += 1;
148
+ }
149
+ else if (c === '"')
150
+ quoted = false;
151
+ else
152
+ field += c;
153
+ continue;
154
+ }
155
+ if (start && c === "#") {
156
+ while (i < s.length && s[i] !== "\n")
157
+ i += 1;
158
+ continue;
159
+ }
160
+ start = false;
161
+ if (c === '"' && field === "")
162
+ quoted = true;
163
+ else if (c === ",") {
164
+ row.push(field);
165
+ field = "";
166
+ }
167
+ else if (c === "\n" || c === "\r") {
168
+ if (c === "\r" && s[i + 1] === "\n")
169
+ i += 1;
170
+ row.push(field);
171
+ if (row.some((f) => f !== ""))
172
+ rows.push(row);
173
+ row = [];
174
+ field = "";
175
+ start = true;
176
+ }
177
+ else
178
+ field += c;
179
+ }
180
+ row.push(field);
181
+ if (row.some((f) => f !== ""))
182
+ rows.push(row);
183
+ const [head, ...body] = rows;
184
+ if (!head)
185
+ return [];
186
+ const names = head.map((h) => h.trim().toLowerCase());
187
+ return body.map((r) => Object.fromEntries(names.map((n, i) => [n, (r[i] ?? "").trim()])));
188
+ }
189
+ const many = (v) => (v ?? "").split(/[|;,\s]+/).filter(Boolean);
190
+ /**
191
+ * Clerk's dashboard export (Settings › User exports): `id, first_name, last_name, username, primary_email_address,
192
+ * primary_phone_number, verified_email_addresses, unverified_email_addresses, verified_phone_numbers,
193
+ * unverified_phone_numbers, totp_secret, password_digest, password_hasher, created_at`, several values in a cell
194
+ * split by `|`; bcrypt digests `$2a$` (made by Clerk) or `$2b$` (imported). It has no Google, Apple or GitHub
195
+ * accounts: those users get in with that provider again, which joins the account by its verified address. Nor does
196
+ * it say who is banned: a banned user moves like any other.
197
+ */
198
+ export function readClerk(csv, o = {}) {
199
+ const now = o.now ?? Date.now();
200
+ const rows = parseCsv(csv);
201
+ if (rows.length && !("id" in rows[0]))
202
+ throw new Error("this isn't Clerk's export: no id column");
203
+ const accounts = [];
204
+ const counts = [];
205
+ let otherHash = 0, unverifiedOnly = 0;
206
+ const hashers = new Set();
207
+ for (const r of rows) {
208
+ if (!r.id)
209
+ continue;
210
+ const verified = many(r.verified_email_addresses).map(cleanEmail).filter((e) => !!e);
211
+ const primary = cleanEmail(r.primary_email_address);
212
+ const emails = [...new Set([...(primary && verified.includes(primary) ? [primary] : []), ...verified])];
213
+ const phonesOk = many(r.verified_phone_numbers).map(cleanPhone).filter((p) => !!p);
214
+ const primaryPhone = cleanPhone(r.primary_phone_number);
215
+ const phones = [...new Set([...(primaryPhone && phonesOk.includes(primaryPhone) ? [primaryPhone] : []), ...phonesOk])];
216
+ if (!emails.length && !phones.length && (many(r.unverified_email_addresses).length || many(r.unverified_phone_numbers).length))
217
+ unverifiedOnly += 1;
218
+ const name = [r.first_name, r.last_name].filter(Boolean).join(" ") || r.username || undefined;
219
+ const a = { sourceId: r.id, id: idFor(r.id), createdAt: time(r.created_at, now), emails, phones, name, identities: [] };
220
+ if (r.password_digest) {
221
+ const hasher = (r.password_hasher || "bcrypt").toLowerCase();
222
+ if (hasher === "bcrypt" && /^\$2[aby]\$\d\d\$/.test(r.password_digest) && emails.length)
223
+ a.password = r.password_digest;
224
+ else if (hasher !== "bcrypt") {
225
+ otherHash += 1;
226
+ hashers.add(hasher);
227
+ }
228
+ }
229
+ if (r.totp_secret)
230
+ a.mfa = true;
231
+ accounts.push(a);
232
+ }
233
+ left(counts, "Other hashes", otherHash, `passwords hashed with ${[...hashers].join(", ")} stay behind: an email code gets those users in`);
234
+ left(counts, "Unverified only", unverifiedOnly, "users with no verified address or number: they move with nothing to sign in with");
235
+ return {
236
+ accounts,
237
+ counts,
238
+ notes: [
239
+ "Clerk's export has no Google, Apple or GitHub accounts: a user who signed in with one gets in with it again, and joins the account by the verified address they share.",
240
+ "Clerk's export doesn't say who is banned: a banned user moves and signs in. Take them out after the move: delete from auth_users where source_id in ('user_…').",
241
+ ],
242
+ attention: [],
243
+ total: rows.length,
244
+ };
245
+ }
246
+ // --- Auth0 -----------------------------------------------------------------------------------------------------
247
+ const AUTH0_PROVIDERS = { "google-oauth2": "google", apple: "apple", github: "github" };
248
+ /** NDJSON, or a JSON array: one object per line or element. */
249
+ function records(input) {
250
+ const t = input.trim();
251
+ if (!t)
252
+ return [];
253
+ if (t.startsWith("["))
254
+ return parseJson(t, "the file");
255
+ return t.split(/\r?\n/).filter((l) => l.trim()).map((l, i) => {
256
+ try {
257
+ return parseJson(l, "the file");
258
+ }
259
+ catch {
260
+ throw new Error(`the file isn't valid JSON (line ${i + 1})`);
261
+ }
262
+ });
263
+ }
264
+ /**
265
+ * Auth0's bulk export (`POST /api/v2/jobs/users-exports`, format json: NDJSON) with `user_id, email, email_verified,
266
+ * phone_number, phone_verified, name, picture, blocked, created_at, last_login, identities[{ provider, connection,
267
+ * user_id }]`. Auth0 gives no hashes in it: database users move without a password and sign in with an email code
268
+ * (and can set a password then). A hashes file from Auth0's support (one JSON object per line, or an array, each
269
+ * with the user's id or email and a bcrypt `passwordHash` / `password_hash`) moves theirs.
270
+ */
271
+ export function readAuth0(ndjson, hashes, o = {}) {
272
+ const now = o.now ?? Date.now();
273
+ const users = records(ndjson);
274
+ if (users.length && !("user_id" in users[0]))
275
+ throw new Error("this isn't Auth0's export: no user_id (export with the user_id field)");
276
+ const byId = new Map();
277
+ // By address only within the user's connection (a line naming none: any), and for an address both call verified.
278
+ const byEmail = new Map();
279
+ const emailKey = (connection, email) => `${typeof connection === "string" ? connection : ""}\n${email}`;
280
+ for (const h of hashes ? records(hashes) : []) {
281
+ const custom = h.custom_password_hash;
282
+ const value = String(h.passwordHash ?? h.password_hash ?? (custom?.algorithm === "bcrypt" ? custom.hash?.value : "") ?? "");
283
+ if (!/^\$2[aby]\$\d\d\$/.test(value))
284
+ continue;
285
+ const oid = h._id?.$oid ?? (typeof h._id === "string" ? h._id : undefined);
286
+ for (const id of [h.user_id, oid].filter((x) => typeof x === "string"))
287
+ byId.set(id.replace(/^auth0\|/, ""), value);
288
+ const e = cleanEmail(h.email);
289
+ if (e && h.email_verified !== false && h.email_verified !== "false")
290
+ byEmail.set(emailKey(h.connection, e), value);
291
+ }
292
+ const accounts = [];
293
+ const counts = [];
294
+ let blocked = 0, unverified = 0, other = 0, withoutHash = 0;
295
+ const others = new Set();
296
+ for (const u of users) {
297
+ const userId = text(u.user_id);
298
+ if (!userId)
299
+ continue;
300
+ if (u.blocked === true) {
301
+ blocked += 1;
302
+ continue;
303
+ }
304
+ const identities = Array.isArray(u.identities) ? u.identities : [];
305
+ const database = identities.find((i) => i.provider === "auth0");
306
+ const email = cleanEmail(u.email);
307
+ const verified = u.email_verified === true || u.email_verified === "true";
308
+ const a = { sourceId: userId, id: idFor(userId), createdAt: time(u.created_at, now), lastSignInAt: time(u.last_login, 0) || undefined, emails: [], phones: [], name: text(u.name), picture: text(u.picture), identities: [] };
309
+ if (email && (verified || (database && o.keepUnprovenPasswords)))
310
+ a.emails.push(email);
311
+ else if (email && database)
312
+ unverified += 1;
313
+ const phone = cleanPhone(u.phone_number);
314
+ if (phone && (u.phone_verified === true || u.phone_verified === "true" || identities.some((i) => i.provider === "sms")))
315
+ a.phones.push(phone);
316
+ for (const i of identities) {
317
+ const provider = AUTH0_PROVIDERS[String(i.provider)];
318
+ if (provider && i.user_id !== undefined && i.user_id !== null)
319
+ a.identities.push({ provider, subject: String(i.user_id), email: verified ? email : undefined });
320
+ else if (!["auth0", "sms", "email"].includes(String(i.provider))) {
321
+ other += 1;
322
+ others.add(String(i.provider));
323
+ }
324
+ }
325
+ if (Array.isArray(u.multifactor) && u.multifactor.length)
326
+ a.mfa = true;
327
+ if (database && a.emails.length) {
328
+ const h = byId.get(String(database.user_id ?? "")) ?? byId.get(userId.replace(/^auth0\|/, "")) ?? (verified && email ? (byEmail.get(emailKey(database.connection, email)) ?? byEmail.get(emailKey(undefined, email))) : undefined);
329
+ if (h)
330
+ a.password = h;
331
+ else
332
+ withoutHash += 1;
333
+ }
334
+ accounts.push(a);
335
+ }
336
+ left(counts, "Blocked", blocked, "left out");
337
+ left(counts, "Unverified", unverified, "database users whose address Auth0 never verified: they move without it (--keep-unproven-passwords moves it)");
338
+ left(counts, "Other providers", other, `ways in direct-auth doesn't have (${[...others].join(", ")}): those users need another one`);
339
+ if (withoutHash)
340
+ counts.push({ label: "No password", count: withoutHash, note: "database users sign in with an email code, and can set a password then", warn: false });
341
+ return { accounts, counts, notes: [], attention: [], total: users.length };
342
+ }
343
+ async function columns(q) {
344
+ const r = await q(`select table_name, column_name from information_schema.columns where table_schema = 'public'`);
345
+ const m = new Map();
346
+ for (const row of r.rows) {
347
+ if (!m.has(row.table_name))
348
+ m.set(row.table_name, new Set());
349
+ m.get(row.table_name).add(row.column_name);
350
+ }
351
+ return m;
352
+ }
353
+ const pick = (cols, ...names) => names.find((n) => cols?.has(n));
354
+ const qi = (name) => `"${name.replace(/"/g, '""')}"`;
355
+ /** The app's foreign keys on the source's users table: they stay there; the mapping is `source_id`. */
356
+ async function keysOn(q, table, own, prefix) {
357
+ const r = await q(`select c.conrelid::regclass::text as tbl, a.attname as col from pg_constraint c
358
+ join pg_attribute a on a.attrelid = c.conrelid and a.attnum = c.conkey[1]
359
+ where c.contype = 'f' and c.confrelid = to_regclass('public.${qi(table)}') order by 1, 2`);
360
+ return r.rows
361
+ .filter((x) => !own.includes(String(x.tbl).replace(/^public\./, "").replace(/"/g, "")))
362
+ .map((x) => ({
363
+ name: `${x.tbl}.${x.col}`,
364
+ kind: "foreign key",
365
+ todo: `points at ${table}, which stays. Give it the new ids with public.${prefix}users.source_id (update … set user_id = u.id from public.${prefix}users u where u.source_id = old_id::text), then point it at public.${prefix}users(id)`,
366
+ }));
367
+ }
368
+ /**
369
+ * Auth.js's database adapters: `users` (or `user`, `User`) with `id, name, email, emailVerified, image`, and
370
+ * `accounts` (`account`, `Account`) with `userId, provider, providerAccountId`, camelCase or snake_case. Verification
371
+ * tokens are ignored. Auth.js keeps no passwords (its credentials provider is the app's own code).
372
+ */
373
+ export const authjsReader = {
374
+ id: "authjs",
375
+ label: "Auth.js",
376
+ kind: "tables",
377
+ async read(q, o) {
378
+ const cols = await columns(q);
379
+ const userTable = ["users", "user", "User"].find((t) => cols.get(t)?.has("emailVerified") || cols.get(t)?.has("email_verified"));
380
+ const accountTable = ["accounts", "account", "Account"].find((t) => pick(cols.get(t), "providerAccountId", "provider_account_id"));
381
+ if (!userTable || !accountTable)
382
+ throw new Error("no Auth.js tables in public: looked for users (emailVerified) and accounts (providerAccountId)");
383
+ const uc = cols.get(userTable);
384
+ const ac = cols.get(accountTable);
385
+ const verified = pick(uc, "emailVerified", "email_verified");
386
+ const created = pick(uc, "createdAt", "created_at");
387
+ const users = await q(`select u.id::text as id, u.name::text as name, u.email::text as email, (u.${qi(verified)} is not null) as verified,
388
+ ${pick(uc, "image") ? "u.image::text" : "null"} as image, ${created ? `(extract(epoch from u.${qi(created)}::timestamptz) * 1000)::bigint::text` : "null"} as created
389
+ from public.${qi(userTable)} u`);
390
+ const userCol = pick(ac, "userId", "user_id");
391
+ const subjectCol = pick(ac, "providerAccountId", "provider_account_id");
392
+ const ways = await q(`select a.${qi(userCol)}::text as user_id, a.provider::text as provider, a.${qi(subjectCol)}::text as subject from public.${qi(accountTable)} a`);
393
+ const now = Date.now();
394
+ const byUser = new Map();
395
+ for (const w of ways.rows) {
396
+ if (!byUser.has(w.user_id))
397
+ byUser.set(w.user_id, []);
398
+ byUser.get(w.user_id).push({ provider: w.provider, subject: w.subject });
399
+ }
400
+ const accounts = [];
401
+ const counts = [];
402
+ let unverified = 0, other = 0;
403
+ const others = new Set();
404
+ for (const u of users.rows) {
405
+ const email = cleanEmail(u.email);
406
+ const a = { sourceId: u.id, id: idFor(u.id), createdAt: time(u.created, now), emails: [], phones: [], name: text(u.name), picture: text(u.image), identities: [] };
407
+ if (email && u.verified === "t")
408
+ a.emails.push(email);
409
+ else if (email)
410
+ unverified += 1;
411
+ for (const w of byUser.get(u.id) ?? []) {
412
+ const provider = ["apple", "google", "github"].find((p) => p === w.provider);
413
+ if (provider)
414
+ a.identities.push({ provider, subject: w.subject });
415
+ else if (!["email", "nodemailer", "resend", "sendgrid", "postmark", "http-email", "credentials"].includes(w.provider)) {
416
+ other += 1;
417
+ others.add(w.provider);
418
+ }
419
+ }
420
+ accounts.push(a);
421
+ }
422
+ left(counts, "Unverified", unverified, "addresses Auth.js never verified (an OAuth sign-in's, mostly) stay behind: those users get in with their provider");
423
+ left(counts, "Other providers", other, `ways in direct-auth doesn't have (${[...others].join(", ")}): those users need another one`);
424
+ const own = [accountTable, ...["sessions", "session", "Session"].filter((t) => cols.has(t))];
425
+ return { accounts, counts, notes: ["Auth.js's tables stay as they are: drop them once the new version is the minimum."], attention: await keysOn(q, userTable, own, o.prefix), total: users.rows.length };
426
+ },
427
+ };
428
+ /**
429
+ * Better Auth: `user` with `id, name, email, emailVerified, image, createdAt` (and `isAnonymous`, `phoneNumber`,
430
+ * `phoneNumberVerified` from its plugins), `account` with `userId, providerId, accountId, password`: providerId
431
+ * `credential` is a password (its scrypt hash, `salt:key`), apple, google and github the providers' accounts.
432
+ */
433
+ export const betterAuthReader = {
434
+ id: "better-auth",
435
+ label: "Better Auth",
436
+ kind: "tables",
437
+ async read(q, o) {
438
+ const cols = await columns(q);
439
+ const userTable = ["user", "users"].find((t) => pick(cols.get(t), "emailVerified", "email_verified"));
440
+ const accountTable = ["account", "accounts"].find((t) => pick(cols.get(t), "providerId", "provider_id"));
441
+ if (!userTable || !accountTable)
442
+ throw new Error("no Better Auth tables in public: looked for user (emailVerified) and account (providerId)");
443
+ const uc = cols.get(userTable);
444
+ const ac = cols.get(accountTable);
445
+ const c = (set, ...names) => pick(set, ...names);
446
+ const col = (alias, set, type, ...names) => {
447
+ const n = c(set, ...names);
448
+ return n ? `${alias}.${qi(n)}::${type}` : "null";
449
+ };
450
+ const created = col("u", uc, "timestamptz", "createdAt", "created_at");
451
+ const banEnds = col("u", uc, "timestamptz", "banExpires", "ban_expires");
452
+ const users = await q(`select u.id::text as id, u.name::text as name, u.email::text as email, ${col("u", uc, "boolean", "emailVerified", "email_verified")} as verified,
453
+ ${col("u", uc, "text", "image")} as image, ${created === "null" ? "null" : `(extract(epoch from ${created}) * 1000)::bigint`} as created,
454
+ ${col("u", uc, "boolean", "isAnonymous", "is_anonymous")} as anonymous, ${col("u", uc, "text", "phoneNumber", "phone_number")} as phone,
455
+ ${col("u", uc, "boolean", "phoneNumberVerified", "phone_number_verified")} as phone_verified,
456
+ ${col("u", uc, "boolean", "twoFactorEnabled", "two_factor_enabled")} as two_factor,
457
+ (${col("u", uc, "boolean", "banned")} is true and (${banEnds} is null or ${banEnds} > now())) as banned
458
+ from public.${qi(userTable)} u`);
459
+ // Its two-factor plugin: twoFactorEnabled on the user, a secret in twoFactor.
460
+ const factorTable = ["twoFactor", "two_factor", "twoFactors", "two_factors"].find((t) => pick(cols.get(t), "userId", "user_id"));
461
+ const withFactor = new Set(factorTable ? (await q(`select distinct ${col("f", cols.get(factorTable), "text", "userId", "user_id")} as user_id from public.${qi(factorTable)} f`)).rows.map((r) => r.user_id) : []);
462
+ const ways = await q(`select ${col("a", ac, "text", "userId", "user_id")} as user_id, ${col("a", ac, "text", "providerId", "provider_id")} as provider,
463
+ ${col("a", ac, "text", "accountId", "account_id")} as subject, ${col("a", ac, "text", "password")} as password from public.${qi(accountTable)} a`);
464
+ const now = Date.now();
465
+ const byUser = new Map();
466
+ for (const w of ways.rows) {
467
+ if (!byUser.has(w.user_id))
468
+ byUser.set(w.user_id, []);
469
+ byUser.get(w.user_id).push(w);
470
+ }
471
+ const accounts = [];
472
+ const counts = [];
473
+ let unverified = 0, other = 0, unreadable = 0, banned = 0;
474
+ const others = new Set();
475
+ for (const u of users.rows) {
476
+ // The admin plugin's ban, still running: left out, as Supabase's banned are.
477
+ if (u.banned === "t") {
478
+ banned += 1;
479
+ continue;
480
+ }
481
+ const anonymous = u.anonymous === "t";
482
+ const email = anonymous ? undefined : cleanEmail(u.email);
483
+ const mine = byUser.get(u.id) ?? [];
484
+ const credential = mine.find((w) => w.provider === "credential" && w.password);
485
+ const a = { sourceId: u.id, id: idFor(u.id), createdAt: time(u.created, now), emails: [], phones: [], name: anonymous ? undefined : text(u.name), picture: text(u.image), identities: [], guest: anonymous };
486
+ if (u.two_factor === "t" || withFactor.has(u.id))
487
+ a.mfa = true;
488
+ if (email && (u.verified === "t" || (credential && o.keepUnprovenPasswords)))
489
+ a.emails.push(email);
490
+ else if (email && credential)
491
+ unverified += 1;
492
+ const phone = u.phone_verified === "t" ? cleanPhone(u.phone) : undefined;
493
+ if (phone)
494
+ a.phones.push(phone);
495
+ if (credential && a.emails.length) {
496
+ const m = /^([0-9a-f]{2,128}):([0-9a-f]{128})$/.exec(credential.password);
497
+ if (m)
498
+ a.password = `$bascrypt$${m[1]}$${m[2]}`;
499
+ else
500
+ unreadable += 1;
501
+ }
502
+ for (const w of mine) {
503
+ const provider = ["apple", "google", "github"].find((p) => p === w.provider);
504
+ if (provider && w.subject)
505
+ a.identities.push({ provider, subject: w.subject });
506
+ else if (w.provider !== "credential" && w.provider !== "anonymous") {
507
+ other += 1;
508
+ others.add(String(w.provider));
509
+ }
510
+ }
511
+ accounts.push(a);
512
+ }
513
+ left(counts, "Banned", banned, "left out (the admin plugin's ban, not over yet)");
514
+ left(counts, "Unverified", unverified, "password users whose address Better Auth never verified: they move without it and the password (--keep-unproven-passwords moves both)");
515
+ left(counts, "Unreadable hashes", unreadable, "passwords that aren't Better Auth's default scrypt (a custom hasher) stay behind: an email code gets those users in");
516
+ left(counts, "Other providers", other, `ways in direct-auth doesn't have (${[...others].join(", ")}): those users need another one`);
517
+ const own = [accountTable, ...["session", "sessions"].filter((t) => cols.has(t))];
518
+ const notes = ["Better Auth's tables stay as they are: drop them once the new version is the minimum."];
519
+ if (accounts.some((a) => a.guest))
520
+ notes.push("Guests (anonymous users) move with their ids, but not their sessions: there is no claim, so a guest starts over in the new version.");
521
+ return { accounts, counts, notes, attention: await keysOn(q, userTable, own, o.prefix), total: users.rows.length };
522
+ },
523
+ };
524
+ export const firebaseReader = {
525
+ id: "firebase",
526
+ label: "Firebase Auth",
527
+ kind: "file",
528
+ read: async (_q, o) => readFirebase(need(o.input?.users, "the export file"), o.input?.firebase, o),
529
+ };
530
+ export const clerkReader = {
531
+ id: "clerk",
532
+ label: "Clerk",
533
+ kind: "file",
534
+ read: async (_q, o) => readClerk(need(o.input?.users, "the CSV export")),
535
+ };
536
+ export const auth0Reader = {
537
+ id: "auth0",
538
+ label: "Auth0",
539
+ kind: "file",
540
+ read: async (_q, o) => readAuth0(need(o.input?.users, "the export file"), o.input?.hashes, o),
541
+ };
542
+ function need(v, what) {
543
+ if (v === undefined)
544
+ throw new Error(`${what} is needed (--file)`);
545
+ return v;
546
+ }
547
+ /**
548
+ * Firebase's hash parameters as the console shows them (`hash_config { algorithm: SCRYPT, base64_signer_key: …,
549
+ * base64_salt_separator: …, rounds: 8, mem_cost: 14 }`), or as JSON with those names; null when they aren't there.
550
+ */
551
+ export function parseFirebaseHash(t) {
552
+ const get = (name) => new RegExp(`"?${name}"?\\s*[:=]\\s*"?([A-Za-z0-9+/=]+)"?`).exec(t)?.[1];
553
+ const signerKey = get("base64_signer_key") ?? get("signerKey");
554
+ const saltSeparator = get("base64_salt_separator") ?? get("saltSeparator") ?? "Bw==";
555
+ const rounds = Number(get("rounds") ?? 8);
556
+ const memCost = Number(get("mem_cost") ?? get("memCost") ?? 14);
557
+ if (!signerKey || !B64.test(signerKey) || !B64.test(saltSeparator))
558
+ return null;
559
+ // Firebase's own range (rounds 1 to 8, mem_cost 1 to 14): no more memory or time per check than that.
560
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > 8 || !Number.isInteger(memCost) || memCost < 1 || memCost > 14)
561
+ return null;
562
+ return { signerKey, saltSeparator, rounds, memCost };
563
+ }
564
+ /** Whether `text` reads as the export `id` takes: undefined when it does, what's wrong otherwise. */
565
+ export function checkExport(id, text) {
566
+ try {
567
+ if (id === "firebase") {
568
+ const d = parseJson(text, "the export");
569
+ return Array.isArray(d.users) ? undefined : "not a Firebase export: no users list (firebase auth:export users.json --format=json)";
570
+ }
571
+ if (id === "clerk") {
572
+ const [first] = parseCsv(text.split(/\r?\n/).filter((l) => !l.startsWith("#")).slice(0, 2).join("\n"));
573
+ return first && "id" in first && "primary_email_address" in first ? undefined : "not Clerk's CSV export: no id and primary_email_address columns";
574
+ }
575
+ if (id === "auth0") {
576
+ const [first] = records(text.trim().startsWith("[") ? text : text.split(/\r?\n/).find((l) => l.trim()) ?? "");
577
+ return first && "user_id" in first ? undefined : "not Auth0's export: no user_id (export as json, with the user_id field)";
578
+ }
579
+ if (id === "auth0-hashes") {
580
+ const all = records(text);
581
+ return all.some((h) => /^\$2[aby]\$/.test(String(h.passwordHash ?? h.password_hash ?? h.custom_password_hash?.hash?.value ?? "")))
582
+ ? undefined
583
+ : "no bcrypt hashes in it (passwordHash or password_hash, $2a$/$2b$)";
584
+ }
585
+ }
586
+ catch (error) {
587
+ // Only what this code says: a parser's own message would quote the file.
588
+ return `it doesn't read: ${error instanceof Error && /^the (export|file) isn't valid JSON/.test(error.message) ? error.message : "not the format it should be"}`;
589
+ }
590
+ return undefined;
591
+ }
592
+ // --- The one writer ------------------------------------------------------------------------------------------------
593
+ /**
594
+ * A value as SQL. Text is an E'' string, backslashes and quotes doubled: read the same whatever
595
+ * standard_conforming_strings says (the move sets it on too).
596
+ */
597
+ const lit = (v) => v === null || v === undefined
598
+ ? "null"
599
+ : typeof v === "number"
600
+ ? String(Math.round(v))
601
+ : typeof v === "boolean"
602
+ ? String(v)
603
+ : `E'${String(v).replace(/\0/g, "").replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
604
+ const ident = (s) => {
605
+ if (!/^[a-z_][a-z0-9_]*$/.test(s))
606
+ throw new Error(`${s} is not a plain lowercase name`);
607
+ return s;
608
+ };
609
+ /** Rows in chunks, each its own insert, so no statement grows without end; each ten a part of their own (`BATCH`). */
610
+ function inserts(table, cols, rows) {
611
+ const out = [];
612
+ for (let i = 0; i < rows.length; i += 500) {
613
+ if (i > 0 && i % 5000 === 0)
614
+ out.push(BATCH);
615
+ out.push(`insert into ${table} (${cols}) values\n ${rows.slice(i, i + 500).join(",\n ")};`);
616
+ }
617
+ return out.join("\n");
618
+ }
619
+ /**
620
+ * Where the move's script splits into parts migrate sends one at a time, in the one transaction the first part
621
+ * begins: a big export never makes one huge query. As a file it is a comment line, and the script runs as it is.
622
+ */
623
+ const BATCH = "-- direct-auth: next part";
624
+ /** The move as the parts migrate sends one after another (see `BATCH`). */
625
+ export const moveParts = (sql) => sql.split(`\n${BATCH}\n`).filter((part) => part.trim());
626
+ /** The moving accounts and their ways in, as temporary tables (`pg_temp.da_moving`, `pg_temp.da_ways`). */
627
+ function staging(accounts, onCommitDrop) {
628
+ const drop = onCommitDrop ? " on commit drop" : "";
629
+ const users = accounts.map((a) => `(${[a.id, a.sourceId, a.emails[0], a.phones[0], a.name, a.picture, a.createdAt, a.lastSignInAt, !!a.guest, a.password].map(lit).join(", ")})`);
630
+ const ways = [];
631
+ for (const a of accounts) {
632
+ for (const i of a.identities)
633
+ ways.push(`(${[a.id, i.provider, i.subject, i.email, a.createdAt].map(lit).join(", ")})`);
634
+ for (const e of a.emails.slice(1))
635
+ ways.push(`(${[a.id, "email", e, e, a.createdAt].map(lit).join(", ")})`);
636
+ for (const p of a.phones.slice(1))
637
+ ways.push(`(${[a.id, "phone", p, null, a.createdAt].map(lit).join(", ")})`);
638
+ }
639
+ return `drop table if exists pg_temp.da_moving;
640
+ drop table if exists pg_temp.da_ways;
641
+ create temporary table da_moving (id uuid, source_id text, email text, phone text, name text, picture text, created_at bigint, last_sign_in_at bigint, guest boolean, password text)${drop};
642
+ create temporary table da_ways (user_id uuid, provider text, subject text, email text, created_at bigint)${drop};
643
+ ${BATCH}
644
+ ${inserts("pg_temp.da_moving", "id, source_id, email, phone, name, picture, created_at, last_sign_in_at, guest, password", users)}
645
+ ${BATCH}
646
+ ${inserts("pg_temp.da_ways", "user_id, provider, subject, email, created_at", ways)}
647
+ ${BATCH}
648
+ create index on pg_temp.da_moving (id);
649
+ create index on pg_temp.da_moving (source_id);
650
+ create index on pg_temp.da_moving (email);
651
+ create index on pg_temp.da_moving (phone);
652
+ create index on pg_temp.da_ways (user_id);
653
+ analyze pg_temp.da_moving;
654
+ analyze pg_temp.da_ways;`;
655
+ }
656
+ /** The move, one transaction, refused a second time (`source_moved` in `{meta}`). */
657
+ export function accountsMoveSql(accounts, o) {
658
+ const prefix = ident(o.prefix);
659
+ const t = (name) => `public.${prefix}${name}`;
660
+ const now = o.now ?? Date.now();
661
+ const tables = (sql) => sql.replace(/\{uuid\}/g, "uuid").replace(/\{([a-z_]+)\}/g, (_m, name) => t(name)).replace(/public\.(\w+)_(\w+) on/g, "$1_$2 on");
662
+ const schema = MIGRATIONS.map((m) => (typeof m === "string" ? m : m.postgres))
663
+ .filter((m) => !!m)
664
+ .map((m) => `${tables(m)};`.replace(/create (unique )?index if not exists public\./g, "create $1index if not exists "))
665
+ .join("\n\n");
666
+ const older = (a, b) => `(${a}.created_at, ${a}.id) < (${b}.created_at, ${b}.id)`;
667
+ return `-- direct-auth: moving users from ${o.source}, once (read it before running it)
668
+ begin;
669
+ set local lock_timeout = '30s';
670
+ set local search_path = '';
671
+ set local standard_conforming_strings = on;
672
+
673
+ -- 1. Once per database: run the way back first to move again.
674
+ do $$
675
+ begin
676
+ if to_regclass('${t("meta")}') is not null then
677
+ if exists (select 1 from ${t("meta")} where key in ('source_moved', 'supabase_moved')) then
678
+ raise exception 'direct-auth: users were moved here already: it runs once. To move again, run the way back first';
679
+ end if;
680
+ end if;
681
+ end $$;
682
+
683
+ -- 2. direct-auth's tables.
684
+ create table if not exists ${t("meta")} (key text primary key, value text not null);
685
+
686
+ ${schema}
687
+
688
+ insert into ${t("meta")} (key, value) values ('schema', '${MIGRATIONS.length}')
689
+ on conflict (key) do update set value = excluded.value;
690
+
691
+ -- 3. The users, then their ways in. An address or number another account has (here already, or an older one moving)
692
+ -- stays with it; the newer account moves without it, and with no password (a password goes with an address).
693
+ ${staging(accounts, true)}
694
+
695
+ do $$
696
+ declare
697
+ taken bigint;
698
+ emails bigint;
699
+ phones bigint;
700
+ begin
701
+ with x as (delete from pg_temp.da_moving m where exists (select 1 from ${t("users")} d where d.id = m.id or d.source_id = m.source_id) returning 1)
702
+ select count(*) into taken from x;
703
+ delete from pg_temp.da_ways w where not exists (select 1 from pg_temp.da_moving m where m.id = w.user_id);
704
+ with x as (
705
+ update pg_temp.da_moving m set email = null, password = null
706
+ where m.email is not null and (
707
+ exists (select 1 from ${t("users")} d where d.email = m.email)
708
+ or exists (select 1 from ${t("identities")} i where i.provider = 'email' and i.subject = m.email)
709
+ or exists (select 1 from pg_temp.da_moving o where o.email = m.email and ${older("o", "m")}))
710
+ returning 1)
711
+ select count(*) into emails from x;
712
+ with x as (
713
+ update pg_temp.da_moving m set phone = null
714
+ where m.phone is not null and (
715
+ exists (select 1 from ${t("users")} d where d.phone = m.phone)
716
+ or exists (select 1 from ${t("identities")} i where i.provider = 'phone' and i.subject = m.phone)
717
+ or exists (select 1 from pg_temp.da_moving o where o.phone = m.phone and ${older("o", "m")}))
718
+ returning 1)
719
+ select count(*) into phones from x;
720
+ if taken > 0 then
721
+ raise notice 'here already: % users with an id direct-auth has stay as they are', taken;
722
+ end if;
723
+ if emails + phones > 0 then
724
+ raise notice 'shared: % addresses, % numbers another account has: they stay with it, and these move without them', emails, phones;
725
+ end if;
726
+ end $$;
727
+
728
+ insert into ${t("users")} (id, email, phone, name, picture, created_at, updated_at, last_sign_in_at, is_guest, password_hash, source_id)
729
+ select m.id, m.email, m.phone, m.name, m.picture, m.created_at, ${now}, m.last_sign_in_at, case when m.guest then 1 else 0 end, m.password, m.source_id
730
+ from pg_temp.da_moving m
731
+ order by m.created_at, m.id;
732
+
733
+ insert into ${t("identities")} (id, user_id, provider, subject, email, created_at, last_used_at)
734
+ select pg_catalog.gen_random_uuid()::text, m.id, 'email', m.email, m.email, m.created_at, coalesce(m.last_sign_in_at, m.created_at)
735
+ from pg_temp.da_moving m where m.email is not null
736
+ on conflict (provider, subject) do nothing;
737
+
738
+ insert into ${t("identities")} (id, user_id, provider, subject, email, created_at, last_used_at)
739
+ select pg_catalog.gen_random_uuid()::text, m.id, 'phone', m.phone, null, m.created_at, coalesce(m.last_sign_in_at, m.created_at)
740
+ from pg_temp.da_moving m where m.phone is not null
741
+ on conflict (provider, subject) do nothing;
742
+
743
+ -- Apple, Google and GitHub accounts, and the further addresses and numbers: the older account first.
744
+ insert into ${t("identities")} (id, user_id, provider, subject, email, created_at, last_used_at)
745
+ select pg_catalog.gen_random_uuid()::text, w.user_id, w.provider, w.subject, w.email, w.created_at, w.created_at
746
+ from pg_temp.da_ways w
747
+ where not (w.provider = 'email' and exists (select 1 from ${t("users")} d where d.email = w.subject and d.id <> w.user_id))
748
+ and not (w.provider = 'phone' and exists (select 1 from ${t("users")} d where d.phone = w.subject and d.id <> w.user_id))
749
+ order by w.created_at, w.user_id
750
+ on conflict (provider, subject) do nothing;
751
+
752
+ insert into ${t("meta")} (key, value) values ('source_moved', ${lit(`${o.source} ${now}`)});
753
+ delete from ${t("meta")} where key = 'supabase_pending';
754
+
755
+ commit;
756
+ `;
757
+ }
758
+ /** The way back: the moved users out (or direct-auth's tables dropped, when the move made them). */
759
+ export function accountsRollbackSql(existing, o) {
760
+ const t = (name) => `public.${ident(o.prefix)}${name}`;
761
+ const lines = [
762
+ `-- direct-auth: the way back from moving users from ${o.source}, written right before it ran. Read it before running it.`,
763
+ existing
764
+ ? "-- direct-auth's tables were there before, so they stay; the users the move brought (those with a source_id) go."
765
+ : "-- direct-auth's tables didn't exist before, so they go, with whatever they got since (sessions, new users).",
766
+ "begin;",
767
+ ];
768
+ if (existing)
769
+ lines.push(`delete from ${t("users")} where source_id is not null;`, `delete from ${t("meta")} where key = 'source_moved';`);
770
+ else
771
+ for (const name of ["guest_claims", "refresh", "sessions", "identities", "passkeys", "challenges", "codes", "limits", "users", "meta"])
772
+ lines.push(`drop table if exists ${t(name)} cascade;`);
773
+ lines.push("commit;", "");
774
+ return lines.join("\n");
775
+ }
776
+ const n = (v) => Number(v ?? 0);
777
+ /** What the dry run says: the reader's reading, counted the same way for every source. */
778
+ export function readingReport(r, existing, label) {
779
+ const a = r.accounts;
780
+ const count = (f) => a.filter(f).length;
781
+ const ids = (p) => a.reduce((s, x) => s + x.identities.filter((i) => i.provider === p).length, 0);
782
+ const counts = [{ label: "Users", count: a.length, note: `of ${r.total} in ${label}` }];
783
+ for (const [p, l] of [["apple", "Sign in with Apple"], ["google", "Google"], ["github", "GitHub"]])
784
+ if (ids(p))
785
+ counts.push({ label: l, count: ids(p) });
786
+ counts.push({ label: "Email", count: count((x) => x.emails.length > 0), note: "checked addresses" });
787
+ if (count((x) => x.phones.length > 0))
788
+ counts.push({ label: "Phone", count: count((x) => x.phones.length > 0) });
789
+ if (count((x) => !!x.guest))
790
+ counts.push({ label: "Guests (anonymous)", count: count((x) => !!x.guest), note: "no claim: their sessions don't come over" });
791
+ counts.push({ label: "Password hashes", count: count((x) => !!x.password), note: count((x) => !!x.password) ? "checked as they are, made PBKDF2 at each first sign-in" : undefined });
792
+ const renamed = count((x) => x.id !== x.sourceId.toLowerCase());
793
+ if (renamed)
794
+ counts.push({ label: "New ids", count: renamed, note: "ids that weren't UUIDs: the old one stays in source_id" });
795
+ // Two moving with one address: the older keeps it.
796
+ const firstBy = new Map();
797
+ let shared = 0;
798
+ for (const x of [...a].sort((p, q) => p.createdAt - q.createdAt || (p.id < q.id ? -1 : 1))) {
799
+ const e = x.emails[0];
800
+ if (!e)
801
+ continue;
802
+ if (firstBy.has(e))
803
+ shared += 1;
804
+ else
805
+ firstBy.set(e, x);
806
+ }
807
+ if (shared)
808
+ counts.push({ label: "Shared", count: shared, note: "addresses two accounts have: the older keeps it, the other moves without it", warn: true });
809
+ const noWay = count((x) => !x.guest && !x.emails.length && !x.phones.length && !x.identities.length);
810
+ if (noWay)
811
+ counts.push({ label: "No way in", count: noWay, note: "nothing checked to sign in with: they move, but can't sign in until they're given one", warn: true });
812
+ const mfa = count((x) => !!x.mfa);
813
+ if (mfa)
814
+ counts.push({ label: "Second factors", count: mfa, note: "direct-auth doesn't check one: they'd sign in with the first alone. The move stops unless --without-mfa", warn: true });
815
+ counts.push(...r.counts);
816
+ return {
817
+ counts,
818
+ attention: r.attention,
819
+ notes: r.notes,
820
+ existing,
821
+ fks: [],
822
+ has: { guests: a.some((x) => !!x.guest), passwords: a.some((x) => !!x.password), passkeys: false },
823
+ mfa,
824
+ renamed,
825
+ };
826
+ }
827
+ /** A source made from a reader: the same four steps as Supabase's. */
828
+ export function readerSource(reader) {
829
+ let last;
830
+ return {
831
+ id: reader.id,
832
+ label: reader.label,
833
+ kind: reader.kind,
834
+ async inspect(q, o) {
835
+ const t = (name) => `public.${o.prefix}${name}`;
836
+ const one = async (sql) => (await q(sql)).rows[0] ?? {};
837
+ const ours = await one(`select to_regclass('${t("users")}') is not null as users, to_regclass('${t("meta")}') is not null as meta`);
838
+ const empty = { counts: [], attention: [], notes: [], existing: false, fks: [], has: { guests: false, passwords: false, passkeys: false }, mfa: 0 };
839
+ if (ours.users === "t" && ours.meta !== "t")
840
+ return { ...empty, blocked: `${t("users")} is there and isn't direct-auth's: give another prefix (--prefix da_)` };
841
+ if (ours.meta === "t" && (await one(`select count(*) as n from ${t("meta")} where key in ('source_moved', 'supabase_moved')`)).n !== "0") {
842
+ return { ...empty, blocked: "users were moved here already: the move runs once. To move again, run the way back (the rollback file) first" };
843
+ }
844
+ try {
845
+ last = await reader.read(q, o);
846
+ }
847
+ catch (error) {
848
+ return { ...empty, blocked: error instanceof Error ? error.message : String(error) };
849
+ }
850
+ const existing = ours.users === "t";
851
+ const report = readingReport(last, existing, reader.kind === "file" ? "the export" : `${reader.label}'s tables`);
852
+ if (existing && last.accounts.length) {
853
+ // Addresses direct-auth has already: they stay with whoever has them.
854
+ let taken = 0;
855
+ const emails = [...new Set(last.accounts.map((x) => x.emails[0]).filter((e) => !!e))];
856
+ for (let i = 0; i < emails.length; i += 1000) {
857
+ const chunk = emails.slice(i, i + 1000).map(lit).join(", ");
858
+ taken += n((await one(`select count(*) as n from (values ${chunk.split(", ").map((v) => `(${v})`).join(", ")}) v(e)
859
+ where exists (select 1 from ${t("users")} d where d.email = v.e) or exists (select 1 from ${t("identities")} d where d.provider = 'email' and d.subject = v.e)`)).n);
860
+ }
861
+ if (taken)
862
+ report.counts.push({ label: "Here already", count: taken, note: "addresses a direct-auth account has: they stay with it, and these move without them", warn: true });
863
+ }
864
+ report.notes.push(`A hard stop, in this order: ${reader.label}'s sign-ups off, move, then the app's new version with direct-auth as the minimum. No session comes over: everyone signs in again, as the same user.`);
865
+ return report;
866
+ },
867
+ applySql(o) {
868
+ if (!last)
869
+ throw new Error("inspect first");
870
+ const mfa = last.accounts.filter((a) => a.mfa).length;
871
+ if (mfa && !o.allowMfaLoss)
872
+ throw new Error(`${mfa} ${mfa === 1 ? "user has" : "users have"} a second factor, which direct-auth doesn't check: --without-mfa moves them knowing that`);
873
+ return accountsMoveSql(last.accounts, { prefix: o.prefix, source: reader.label });
874
+ },
875
+ rollbackSql: (report, o) => accountsRollbackSql(report.existing, { prefix: o.prefix, source: reader.label }),
876
+ async verify(q, o) {
877
+ if (!last)
878
+ throw new Error("inspect first");
879
+ const t = (name) => `public.${o.prefix}${name}`;
880
+ const one = async (sql) => (await q(sql)).rows[0] ?? {};
881
+ // Kept past the transaction (no on commit drop): it only sets standard_conforming_strings for its own while.
882
+ try {
883
+ for (const part of moveParts(`begin;\nset local standard_conforming_strings = on;\n${staging(last.accounts, false)}\ncommit;`))
884
+ await q(part);
885
+ }
886
+ catch (error) {
887
+ await q("rollback").catch(() => { });
888
+ throw error;
889
+ }
890
+ try {
891
+ const c = await one(`select
892
+ (select count(*) from pg_temp.da_moving) as expected,
893
+ (select count(*) from pg_temp.da_moving m where not exists (select 1 from ${t("users")} d where d.source_id = m.source_id)) as missing,
894
+ (select count(*) from pg_temp.da_moving m join ${t("users")} d on d.source_id = m.source_id where d.id <> m.id) as other_id,
895
+ (select count(*) from pg_temp.da_moving m join ${t("users")} d on d.id = m.id where m.guest and d.is_guest <> 1) as guests_missing,
896
+ (select count(*) from pg_temp.da_moving m join ${t("users")} d on d.id = m.id where m.password is not null and d.email = m.email and d.password_hash is null) as passwords_missing,
897
+ (select count(*) from pg_temp.da_moving m join ${t("users")} d on d.id = m.id where m.email is not null and d.email is distinct from m.email) as emails_elsewhere,
898
+ (select count(*) from pg_temp.da_ways w where w.provider in ('apple', 'google', 'github')
899
+ and not exists (select 1 from ${t("identities")} x where x.provider = w.provider and x.subject = w.subject)) as ways_missing,
900
+ (select count(*) from pg_temp.da_ways w where w.provider in ('apple', 'google', 'github')
901
+ and exists (select 1 from ${t("identities")} x where x.provider = w.provider and x.subject = w.subject and x.user_id <> w.user_id)) as ways_elsewhere`);
902
+ const checks = [];
903
+ checks.push({ label: "Users", ok: n(c.missing) === 0 && n(c.other_id) === 0, detail: n(c.missing) ? `${n(c.missing)} of ${n(c.expected)} not moved` : n(c.other_id) ? `${n(c.other_id)} under another id` : `all ${n(c.expected)} here` });
904
+ checks.push({ label: "Ways in", ok: n(c.ways_missing) === 0, detail: n(c.ways_missing) ? `${n(c.ways_missing)} Apple, Google or GitHub accounts missing` : "every Apple, Google and GitHub account, every checked address and number" });
905
+ const shared = n(c.emails_elsewhere) + n(c.ways_elsewhere);
906
+ checks.push({
907
+ label: "Shared",
908
+ ok: shared === 0,
909
+ detail: shared
910
+ ? `${shared} moved without an address or account another user has: two accounts of one person. Run the way back, find who made the other (sign-ups on before the move?), then move again`
911
+ : "no address or account split between two users",
912
+ });
913
+ checks.push({ label: "Guests", ok: n(c.guests_missing) === 0, detail: n(c.guests_missing) ? `${n(c.guests_missing)} missing` : "all there" });
914
+ checks.push({ label: "Passwords", ok: n(c.passwords_missing) === 0, detail: n(c.passwords_missing) ? `${n(c.passwords_missing)} hashes missing` : "every one with a checked address" });
915
+ const sample = await q(`select m.id, (d.id is not null) as there, (d.email is not distinct from m.email or m.email is null) as same_email
916
+ from pg_temp.da_moving m left join ${t("users")} d on d.source_id = m.source_id order by random() limit 5`);
917
+ const wrong = sample.rows.filter((r) => r.there !== "t" || r.same_email !== "t");
918
+ checks.push({
919
+ label: "Sample",
920
+ ok: wrong.length === 0,
921
+ detail: sample.rows.length ? `${sample.rows.map((r) => maskId(r.id ?? "")).join(", ")}${wrong.length ? `: ${wrong.map((r) => maskId(r.id ?? "")).join(", ")} differ` : ": the same users"}` : "nobody to sample",
922
+ });
923
+ return checks;
924
+ }
925
+ finally {
926
+ await q("drop table if exists pg_temp.da_moving; drop table if exists pg_temp.da_ways;").catch(() => { });
927
+ }
928
+ },
929
+ };
930
+ }
931
+ export const READERS = [firebaseReader, authjsReader, betterAuthReader, clerkReader, auth0Reader];