@midsummer-ai/sdk 0.1.0-staging.3653 → 0.1.0-staging.3656

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 (44) hide show
  1. package/THIRD-PARTY-NOTICES +1279 -0
  2. package/auth/client.d.mts +222 -18
  3. package/auth/client.mjs +321 -40
  4. package/auth/contract.d.mts +10 -1
  5. package/auth/contract.mjs +347 -30
  6. package/auth/files.d.mts +2 -28
  7. package/auth/files.mjs +2 -231
  8. package/auth/impersonate.d.mts +33 -0
  9. package/auth/impersonate.mjs +42 -0
  10. package/auth/import.d.mts +71 -0
  11. package/auth/import.mjs +195 -0
  12. package/auth/index.d.mts +5 -198
  13. package/auth/index.mjs +3 -2
  14. package/auth/mail.d.mts +23 -5
  15. package/auth/mail.mjs +93 -39
  16. package/auth/password.d.mts +10 -2
  17. package/auth/password.mjs +14 -2
  18. package/auth/react.d.mts +86 -0
  19. package/auth/react.mjs +865 -0
  20. package/auth/stand-in.d.mts +14 -3
  21. package/auth/stand-in.mjs +162 -29
  22. package/auth-CND9RW17.mjs +1819 -0
  23. package/authorize-BzDrbYtI-0gOzDrp2.mjs +18783 -0
  24. package/{client-BX56cXDt.mjs → connection-C_JSWUrt.mjs} +3 -668
  25. package/database/client.mjs +665 -1
  26. package/dist-DXtY-DJA.mjs +343 -0
  27. package/engine-BhA0XgI7.mjs +48423 -0
  28. package/esm-E3EvzsGX.mjs +1518 -0
  29. package/factory-9jfDGyc1.mjs +1138 -0
  30. package/files-C-FvBxT4.d.mts +75 -0
  31. package/files-DAFOuID_.mjs +692 -0
  32. package/get-id-field-vhOArqXN.mjs +1455 -0
  33. package/index-CsgQ_ouh.d.mts +246 -0
  34. package/package.json +24 -7
  35. package/qr-C1mfuCT9.mjs +1163 -0
  36. package/request-state-BaLB2Hrt.mjs +85 -0
  37. package/rolldown-runtime-CL6CfywC.mjs +36 -0
  38. package/schemas-DTJTcCdK.mjs +6046 -0
  39. package/settings-si8iBtwc.d.mts +47 -0
  40. package/store-CeIGY-xT.d.mts +16 -0
  41. package/{store-B-1coCxW.mjs → store-CsBhnabU.mjs} +1 -1
  42. package/{tabs-CDplCS02.mjs → tabs-gHJHkhm2.mjs} +1 -1
  43. package/auth-Bf7IuulG.mjs +0 -754
  44. package/store-gCz6XVaG.d.mts +0 -15
package/auth/files.mjs CHANGED
@@ -1,231 +1,2 @@
1
- import { getAuthTables } from "better-auth/db";
2
- //#region src/auth/files.ts
3
- /** The Database's shape of a better-auth field. */
4
- function shapeOf(field, tables) {
5
- const type = field.type;
6
- const base = field.references?.field === "id" ? `v.id(${JSON.stringify(tables[field.references.model] ?? field.references.model)})` : type === "string" ? "v.string()" : type === "number" || type === "date" ? "v.number()" : type === "boolean" ? "v.boolean()" : type === "string[]" ? "v.array(v.string())" : type === "number[]" ? "v.array(v.number())" : Array.isArray(type) ? `v.union(${type.map((one) => `v.literal(${JSON.stringify(one)})`).join(", ")})` : "v.any()";
7
- return field.required === true ? base : `v.optional(${base})`;
8
- }
9
- /**
10
- * The tables better-auth asks for under `options` (its plugins add theirs), as the Database keeps them. A
11
- * field is looked up by an index when better-auth marks it unique or indexed, when it names another row, and
12
- * for `expiresAt`, by which old rows are cleared.
13
- */
14
- function authTablesOf(options) {
15
- const tables = getAuthTables(options);
16
- const names = Object.fromEntries(Object.entries(tables).map(([key, table]) => [key, table.modelName]));
17
- return Object.fromEntries(Object.values(tables).map((table) => {
18
- const fields = {}, indexed = [], unique = [];
19
- for (const [key, field] of Object.entries(table.fields)) {
20
- const name = field.fieldName ?? key;
21
- fields[name] = shapeOf(field, names);
22
- if (field.unique && field.type === "string") unique.push(name);
23
- else if (field.unique || field.index || field.references || name === "expiresAt") indexed.push(name);
24
- }
25
- return [table.modelName, {
26
- fields,
27
- indexed,
28
- unique
29
- }];
30
- }));
31
- }
32
- /** `db/authTables.ts`: each table as `defineTable(...)` with its indexes, and the fields each is looked up by. */
33
- function tablesFile(tables) {
34
- const lines = Object.entries(tables).map(([name, table]) => {
35
- return ` ${name}: defineTable({ ${Object.entries(table.fields).map(([field, shape]) => `${field}: ${shape}`).join(", ")} })${[...table.unique.map((field) => `.index("by_${field}", "${field}", { unique: true })`), ...table.indexed.map((field) => `.index("by_${field}", "${field}")`)].join("")},`;
36
- });
37
- const one = (field) => field === "key" || field === "token" ? 0 : 1;
38
- const lookups = Object.entries(tables).map(([name, table]) => ` ${name}: ${JSON.stringify([...table.unique, ...[...table.indexed].sort((a, b) => one(a) - one(b))])},`);
39
- return `// Written by \`midsummer auth init\` from the tables sign-in uses. Write it again with that command; don't edit it.
40
- import { defineTable, v } from "@midsummer-ai/sdk/server"
41
-
42
- /** Sign-in's tables. Name each in db/schema.ts: \`user: authTables.user\`. */
43
- export const authTables = {
44
- ${lines.join("\n")}
45
- }
46
-
47
- /** The fields each table is looked up by, each with its index \`by_<field>\`, those that find one row first. */
48
- export const authLookups = {
49
- ${lookups.join("\n")}
50
- }
51
- `;
52
- }
53
- /** The lines db/schema.ts names sign-in's tables with, inside `defineSchema({ ... })`. */
54
- function schemaLines(tables) {
55
- return Object.keys(tables).map((name) => `${name}: authTables.${name},`).join(" ");
56
- }
57
- /**
58
- * `db/auth.ts`: what `@midsummer-ai/sdk/auth` calls, `auth.create`, `auth.findOne`, `auth.findMany`,
59
- * `auth.count`, `auth.update`, `auth.updateMany`, `auth.deleteMany`, `auth.increment` and `auth.consume`. A `where` is
60
- * better-auth's: clauses of `{ field, operator, value, connector, mode }`, `id` meaning the row's `_id`. All
61
- * joined by AND with an `eq` (or a range) on a field looked up by reads only that index's rows; anything else
62
- * reads the table.
63
- */
64
- const FUNCTIONS_FILE = `// Written by \`midsummer auth init\`: what @midsummer-ai/sdk/auth keeps your app's users with. Write it again with that command; don't edit it.
65
- import { mutation, query, v } from "./_generated/server"
66
- import { authLookups } from "./authTables"
67
-
68
- const where = v.optional(v.array(v.any()))
69
-
70
- function server(ctx) {
71
- if (!ctx.identity.server) throw new Error("Only the app's own server reads and writes sign-in's tables.")
72
- }
73
- function table(model) {
74
- if (!Object.hasOwn(authLookups, model)) throw new Error(\`\${model} is not one of sign-in's tables\`)
75
- return model
76
- }
77
- /** A row as better-auth takes it: its \`_id\` as \`id\`. */
78
- function shown(doc) {
79
- if (!doc) return null
80
- const { _id, _creationTime, _version, ...fields } = doc
81
- return { id: _id, ...fields }
82
- }
83
- const text = (value) => (typeof value === "string" ? value.toLowerCase() : value)
84
- function holds(row, clause) {
85
- const { field, value, operator = "eq", mode } = clause
86
- const have = row[field], loose = mode === "insensitive"
87
- const same = (a, b) => (loose ? text(a) === text(b) : a === b)
88
- switch (operator) {
89
- case "eq": return value === null ? have == null : same(have, value)
90
- case "ne": return value === null ? have != null : !same(have, value)
91
- case "in": return Array.isArray(value) && value.some((one) => same(have, one))
92
- case "not_in": return Array.isArray(value) && !value.some((one) => same(have, one))
93
- case "lt": return value != null && have != null && have < value
94
- case "lte": return value != null && have != null && have <= value
95
- case "gt": return value != null && have != null && have > value
96
- case "gte": return value != null && have != null && have >= value
97
- case "contains": return typeof have === "string" && typeof value === "string" && (loose ? text(have).includes(text(value)) : have.includes(value))
98
- case "starts_with": return typeof have === "string" && typeof value === "string" && (loose ? text(have).startsWith(text(value)) : have.startsWith(value))
99
- case "ends_with": return typeof have === "string" && typeof value === "string" && (loose ? text(have).endsWith(text(value)) : have.endsWith(value))
100
- default: throw new Error(\`sign-in asked with an operator the Database's sign-in tables don't take: \${operator}\`)
101
- }
102
- }
103
- /** Whether a row matches a where: its clauses in order, each joined to those before by its own connector. */
104
- function matches(row, clauses) {
105
- if (!clauses?.length) return true
106
- let result = holds(row, clauses[0])
107
- for (const clause of clauses.slice(1)) result = clause.connector === "OR" ? result || holds(row, clause) : result && holds(row, clause)
108
- return result
109
- }
110
- const RANGE = { lt: "lt", lte: "lte", gt: "gt", gte: "gte" }
111
- /** The rows of \`model\` a where can hold: by id, through the index of a field it asks for by value, or the whole table. */
112
- async function candidates(ctx, model, clauses) {
113
- const all = clauses ?? []
114
- const ands = all.every((clause, index) => index === 0 || clause.connector !== "OR")
115
- if (ands) {
116
- const byId = all.find((clause) => clause.field === "id" && (clause.operator ?? "eq") === "eq")
117
- if (byId) {
118
- const id = typeof byId.value === "string" ? ctx.db.normalizeId(model, byId.value) : null
119
- const doc = id ? await ctx.db.get(model, id) : null
120
- return doc ? [doc] : []
121
- }
122
- const ids = all.find((clause) => clause.field === "id" && clause.operator === "in" && Array.isArray(clause.value))
123
- if (ids) return (await Promise.all(ids.value.map((one) => (typeof one === "string" && ctx.db.normalizeId(model, one) ? ctx.db.get(model, one) : null)))).filter(Boolean)
124
- const lookups = authLookups[model]
125
- // Of the fields it asks for by value, the one listed first finds the fewest rows: a unique one, a key or a token.
126
- const exact = all.filter((clause) => (clause.operator ?? "eq") === "eq" && clause.mode !== "insensitive" && clause.value !== null && lookups.includes(clause.field)).sort((a, b) => lookups.indexOf(a.field) - lookups.indexOf(b.field))[0]
127
- if (exact) return ctx.db.query(model).withIndex(\`by_\${exact.field}\`, (q) => q.eq(exact.field, exact.value)).collect()
128
- const ranged = all.find((clause) => RANGE[clause.operator] && clause.value != null && lookups.includes(clause.field))
129
- if (ranged) return ctx.db.query(model).withIndex(\`by_\${ranged.field}\`, (q) => q[RANGE[ranged.operator]](ranged.field, ranged.value)).collect()
130
- }
131
- return ctx.db.query(model).collect()
132
- }
133
- async function found(ctx, model, clauses) {
134
- return (await candidates(ctx, model, clauses)).map(shown).filter((row) => matches(row, clauses))
135
- }
136
- function ordered(rows, sortBy) {
137
- if (!sortBy) return rows
138
- const sign = sortBy.direction === "desc" ? -1 : 1
139
- return [...rows].sort((a, b) => {
140
- const x = a[sortBy.field], y = b[sortBy.field]
141
- return x == null && y == null ? 0 : x == null ? -sign : y == null ? sign : x < y ? -sign : x > y ? sign : 0
142
- })
143
- }
144
- /** A row's fields as written: better-auth's id is the Database's, and \`undefined\` takes a field out. */
145
- const fieldsOf = (data) => Object.fromEntries(Object.entries(data ?? {}).filter(([field]) => field !== "id" && field !== "_id"))
146
-
147
- export const create = mutation({
148
- args: { model: v.string(), data: v.any() },
149
- handler: async (ctx, { model, data }) => {
150
- server(ctx)
151
- const id = await ctx.db.insert(table(model), fieldsOf(data))
152
- return shown(await ctx.db.get(model, id))
153
- },
154
- })
155
- export const findOne = query({
156
- args: { model: v.string(), where },
157
- handler: async (ctx, { model, where }) => {
158
- server(ctx)
159
- return (await found(ctx, table(model), where))[0] ?? null
160
- },
161
- })
162
- export const findMany = query({
163
- args: { model: v.string(), where, limit: v.optional(v.number()), offset: v.optional(v.number()), sortBy: v.optional(v.any()) },
164
- handler: async (ctx, { model, where, limit, offset, sortBy }) => {
165
- server(ctx)
166
- const rows = ordered(await found(ctx, table(model), where), sortBy)
167
- return rows.slice(offset ?? 0, limit === undefined ? undefined : (offset ?? 0) + limit)
168
- },
169
- })
170
- export const count = query({
171
- args: { model: v.string(), where },
172
- handler: async (ctx, { model, where }) => {
173
- server(ctx)
174
- return (await found(ctx, table(model), where)).length
175
- },
176
- })
177
- export const update = mutation({
178
- args: { model: v.string(), where, update: v.any() },
179
- handler: async (ctx, { model, where, update }) => {
180
- server(ctx)
181
- const row = (await found(ctx, table(model), where))[0]
182
- if (!row) return null
183
- await ctx.db.patch(model, row.id, fieldsOf(update))
184
- return shown(await ctx.db.get(model, row.id))
185
- },
186
- })
187
- export const updateMany = mutation({
188
- args: { model: v.string(), where, update: v.any() },
189
- handler: async (ctx, { model, where, update }) => {
190
- server(ctx)
191
- const rows = await found(ctx, table(model), where)
192
- await Promise.all(rows.map((row) => ctx.db.patch(model, row.id, fieldsOf(update))))
193
- return rows.length
194
- },
195
- })
196
- export const deleteMany = mutation({
197
- args: { model: v.string(), where },
198
- handler: async (ctx, { model, where }) => {
199
- server(ctx)
200
- const rows = await found(ctx, table(model), where)
201
- await Promise.all(rows.map((row) => ctx.db.delete(model, row.id)))
202
- return rows.length
203
- },
204
- })
205
- /** Adds to a row's numbers and sets its fields in one step, returning the row, or null when the where finds none: a count is never passed by two at once. */
206
- export const increment = mutation({
207
- args: { model: v.string(), where, increment: v.any(), set: v.optional(v.any()) },
208
- handler: async (ctx, { model, where, increment, set }) => {
209
- server(ctx)
210
- const row = (await found(ctx, table(model), where))[0]
211
- if (!row) return null
212
- const next = fieldsOf(set)
213
- for (const [field, delta] of Object.entries(increment ?? {})) next[field] = (row[field] ?? 0) + delta
214
- await ctx.db.patch(model, row.id, next)
215
- return shown(await ctx.db.get(model, row.id))
216
- },
217
- })
218
- /** Deletes the first row a where holds and returns it, in one step: a code or a link is used once. */
219
- export const consume = mutation({
220
- args: { model: v.string(), where },
221
- handler: async (ctx, { model, where }) => {
222
- server(ctx)
223
- const row = (await found(ctx, table(model), where))[0]
224
- if (!row) return null
225
- await ctx.db.delete(model, row.id)
226
- return row
227
- },
228
- })
229
- `;
230
- //#endregion
231
- export { FUNCTIONS_FILE, authTablesOf, schemaLines, tablesFile };
1
+ import { a as tablesFile, i as schemaLines, n as authFiles, o as tablesFromEngine, r as authTables, t as FUNCTIONS_FILE } from "../files-DAFOuID_.mjs";
2
+ export { FUNCTIONS_FILE, authFiles, authTables, schemaLines, tablesFile, tablesFromEngine };
@@ -0,0 +1,33 @@
1
+ //#region src/auth/impersonate.d.ts
2
+ /**
3
+ * "Sign in as": how the platform lets a project's owner open the app as one of its users. The platform makes a
4
+ * one-time token with `startImpersonation`, writes `row` into the app's `authVerifications` (through `auth.create`),
5
+ * and gives the owner `path` on the app's address to open. The app's sign-in uses the token once, within a minute,
6
+ * and makes a session for the user that says who opened it (`impersonatedBy`) and ends by itself.
7
+ *
8
+ * const started = await startImpersonation({ userId, by: "Ada Lovelace (ada@acme.dev)", reason: "Checking a bug report", now: Date.now() })
9
+ * await rows.call("create", { model: "authVerifications", data: started.row })
10
+ * return { url: `${environmentOrigin}${started.path}` }
11
+ */
12
+ /** How long the token works once made, in ms. */
13
+ declare const IMPERSONATION_TOKEN_MS = 60000;
14
+ /** A token's row id: what `authVerifications.identifier` keeps for it, never the token itself. */
15
+ declare function impersonationIdentifier(token: string): Promise<string>;
16
+ /** A new "sign in as" for `userId`: the token's path to open, and the row that lets it in once. Throws for a reason that isn't 1 to 200 characters. */
17
+ declare function startImpersonation(input: {
18
+ readonly userId: string;
19
+ readonly by: string;
20
+ readonly reason: string;
21
+ readonly now: number;
22
+ }): Promise<{
23
+ readonly path: string;
24
+ readonly row: {
25
+ readonly identifier: string;
26
+ readonly value: string;
27
+ readonly expiresAt: number;
28
+ readonly createdAt: number;
29
+ readonly updatedAt: number;
30
+ };
31
+ }>;
32
+ //#endregion
33
+ export { IMPERSONATION_TOKEN_MS, impersonationIdentifier, startImpersonation };
@@ -0,0 +1,42 @@
1
+ //#region src/auth/impersonate.ts
2
+ /**
3
+ * "Sign in as": how the platform lets a project's owner open the app as one of its users. The platform makes a
4
+ * one-time token with `startImpersonation`, writes `row` into the app's `authVerifications` (through `auth.create`),
5
+ * and gives the owner `path` on the app's address to open. The app's sign-in uses the token once, within a minute,
6
+ * and makes a session for the user that says who opened it (`impersonatedBy`) and ends by itself.
7
+ *
8
+ * const started = await startImpersonation({ userId, by: "Ada Lovelace (ada@acme.dev)", reason: "Checking a bug report", now: Date.now() })
9
+ * await rows.call("create", { model: "authVerifications", data: started.row })
10
+ * return { url: `${environmentOrigin}${started.path}` }
11
+ */
12
+ /** How long the token works once made, in ms. */
13
+ const IMPERSONATION_TOKEN_MS = 6e4;
14
+ const hex = (bytes) => [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
15
+ const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
16
+ /** A token's row id: what `authVerifications.identifier` keeps for it, never the token itself. */
17
+ async function impersonationIdentifier(token) {
18
+ return `impersonate:${hex(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))))}`;
19
+ }
20
+ /** A new "sign in as" for `userId`: the token's path to open, and the row that lets it in once. Throws for a reason that isn't 1 to 200 characters. */
21
+ async function startImpersonation(input) {
22
+ const reason = input.reason.trim(), by = input.by.trim();
23
+ if (!reason || reason.length > 200) throw new Error("Say why you're signing in as them, in 1 to 200 characters.");
24
+ if (!by || by.length > 200) throw new Error("Name who is signing in as them, in 1 to 200 characters.");
25
+ const token = base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
26
+ return {
27
+ path: `/api/auth/impersonate?token=${token}`,
28
+ row: {
29
+ identifier: await impersonationIdentifier(token),
30
+ value: JSON.stringify({
31
+ userId: input.userId,
32
+ by,
33
+ reason
34
+ }),
35
+ expiresAt: input.now + IMPERSONATION_TOKEN_MS,
36
+ createdAt: input.now,
37
+ updatedAt: input.now
38
+ }
39
+ };
40
+ }
41
+ //#endregion
42
+ export { IMPERSONATION_TOKEN_MS, impersonationIdentifier, startImpersonation };
@@ -0,0 +1,71 @@
1
+ //#region src/auth/import.d.ts
2
+ /**
3
+ * Users brought from another sign-in service: their exports read into one shape, and each user's rows made as
4
+ * `@midsummer-ai/sdk/auth` would make them, so they sign in with the password they had. A bcrypt hash is kept as it
5
+ * came; sign-in checks it and writes the password again in its own hash at that person's first sign-in.
6
+ *
7
+ * const users = parseExport("auth0", await Bun.file("users.json").text())
8
+ * const rows = users.users.map((user) => importRows(user, Date.now()))
9
+ *
10
+ * What each service's export looks like:
11
+ * - Clerk: the CSV the dashboard's export makes (`id`, `first_name`, `last_name`, `primary_email_address`,
12
+ * `verified_email_addresses`, `password_digest`, `password_hasher`, …).
13
+ * - Auth0: one JSON object a line, from a user export job (`email`, `email_verified`, `name`, `picture`,
14
+ * `created_at`, `user_metadata`, `app_metadata`) or the password hash export support sends (`passwordHash`).
15
+ * - Supabase: `auth.users` as CSV with a header (`\copy (select * from auth.users) to 'users.csv' csv header`) or
16
+ * as a JSON array: `email`, `encrypted_password`, `email_confirmed_at`, `raw_user_meta_data`,
17
+ * `raw_app_meta_data`, `created_at`.
18
+ * Nothing is written by parsing; a row that can't be read is listed in `skipped` with why.
19
+ */
20
+ type ImportSource = "clerk" | "auth0" | "supabase";
21
+ declare const IMPORT_SOURCES: ReadonlyArray<ImportSource>;
22
+ /** One user from an export, in one shape whatever the service. */
23
+ interface ImportedUser {
24
+ readonly email: string;
25
+ readonly name: string;
26
+ readonly emailVerified: boolean;
27
+ readonly image?: string;
28
+ readonly createdAt?: number;
29
+ /** A bcrypt hash, when the export had one. */
30
+ readonly passwordHash?: string;
31
+ readonly publicMetadata?: unknown;
32
+ readonly privateMetadata?: unknown;
33
+ }
34
+ /** A user's rows as the platform writes them: the user, and a password sign-in when there is a hash. */
35
+ interface ImportedUserRows {
36
+ readonly user: {
37
+ readonly email: string;
38
+ readonly name: string;
39
+ readonly emailVerified: boolean;
40
+ readonly image?: string;
41
+ readonly publicMetadata?: unknown;
42
+ readonly privateMetadata?: unknown;
43
+ readonly createdAt: number;
44
+ readonly updatedAt: number;
45
+ };
46
+ readonly account?: {
47
+ readonly providerId: "credential";
48
+ readonly password: string;
49
+ readonly createdAt: number;
50
+ readonly updatedAt: number;
51
+ };
52
+ }
53
+ /** A bcrypt hash, as Clerk, Auth0 and Supabase export them. */
54
+ declare const isBcrypt: (hash: string) => boolean;
55
+ /** One CSV document as rows of fields, quotes and doubled quotes as RFC 4180 writes them. */
56
+ declare function csvRows(text: string): string[][];
57
+ /**
58
+ * The users an export holds, and the entries it couldn't read, each with why. A user whose password the export
59
+ * keeps in a hash other than bcrypt comes without one, and signs in by a code, a link or a reset.
60
+ */
61
+ declare function parseExport(from: ImportSource, document: string): {
62
+ readonly users: ReadonlyArray<ImportedUser>;
63
+ readonly skipped: ReadonlyArray<{
64
+ readonly entry: string;
65
+ readonly why: string;
66
+ }>;
67
+ };
68
+ /** One imported user's rows, as sign-in writes a user who signs up: made at `now`, unless the export has when they joined. */
69
+ declare function importRows(user: ImportedUser, now: number): ImportedUserRows;
70
+ //#endregion
71
+ export { IMPORT_SOURCES, ImportSource, ImportedUser, ImportedUserRows, csvRows, importRows, isBcrypt, parseExport };
@@ -0,0 +1,195 @@
1
+ //#region src/auth/import.ts
2
+ const IMPORT_SOURCES = [
3
+ "clerk",
4
+ "auth0",
5
+ "supabase"
6
+ ];
7
+ /** A bcrypt hash, as Clerk, Auth0 and Supabase export them. */
8
+ const isBcrypt = (hash) => /^\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}$/.test(hash);
9
+ const EMAIL = /^[^\s@<>()",;:]+@[^\s@<>()",;:]+\.[^\s@<>()",;:]+$/;
10
+ /** One CSV document as rows of fields, quotes and doubled quotes as RFC 4180 writes them. */
11
+ function csvRows(text) {
12
+ const rows = [];
13
+ let row = [], field = "", quoted = false;
14
+ for (let at = 0; at < text.length; at++) {
15
+ const c = text[at];
16
+ if (quoted) {
17
+ if (c === "\"" && text[at + 1] === "\"") {
18
+ field += "\"";
19
+ at++;
20
+ } else if (c === "\"") quoted = false;
21
+ else field += c;
22
+ } else if (c === "\"") quoted = true;
23
+ else if (c === ",") {
24
+ row.push(field);
25
+ field = "";
26
+ } else if (c === "\n" || c === "\r") {
27
+ if (c === "\r" && text[at + 1] === "\n") at++;
28
+ row.push(field);
29
+ field = "";
30
+ if (row.some((one) => one !== "")) rows.push(row);
31
+ row = [];
32
+ } else field += c;
33
+ }
34
+ row.push(field);
35
+ if (row.some((one) => one !== "")) rows.push(row);
36
+ return rows;
37
+ }
38
+ /** A CSV document's rows as records by its header's names. */
39
+ function csvRecords(text) {
40
+ const [header, ...rows] = csvRows(text.replace(/^/, ""));
41
+ return rows.map((row) => Object.fromEntries((header ?? []).map((name, at) => [name.trim(), row[at] ?? ""])));
42
+ }
43
+ const time = (value) => {
44
+ if (typeof value === "number" && Number.isFinite(value)) return value > 0xe8d4a51000 ? value : value * 1e3;
45
+ if (typeof value === "string" && value.trim()) {
46
+ const parsed = Date.parse(value);
47
+ return Number.isNaN(parsed) ? void 0 : parsed;
48
+ }
49
+ if (typeof value === "object" && value !== null && "$date" in value) return time(value.$date);
50
+ };
51
+ const json = (value) => {
52
+ if (typeof value !== "string") return value ?? void 0;
53
+ if (!value.trim()) return void 0;
54
+ try {
55
+ return JSON.parse(value);
56
+ } catch {
57
+ return;
58
+ }
59
+ };
60
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length ? value : void 0;
61
+ const text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
62
+ /** A user from its parts, or why it can't be one. */
63
+ function userOf(given) {
64
+ const email = text(given.email)?.toLowerCase();
65
+ if (!email || !EMAIL.test(email) || email.length > 254) return "it has no email address";
66
+ const hash = text(given.hash);
67
+ const createdAt = time(given.createdAt);
68
+ const image = text(given.image);
69
+ const publicMetadata = object(given.publicMetadata), privateMetadata = object(given.privateMetadata);
70
+ return {
71
+ email,
72
+ name: (text(given.name) ?? email.split("@")[0]).slice(0, 200),
73
+ emailVerified: given.emailVerified,
74
+ ...image && /^https:\/\//.test(image) ? { image } : {},
75
+ ...createdAt !== void 0 ? { createdAt } : {},
76
+ ...hash && isBcrypt(hash) ? { passwordHash: hash } : {},
77
+ ...publicMetadata ? { publicMetadata } : {},
78
+ ...privateMetadata ? { privateMetadata } : {}
79
+ };
80
+ }
81
+ /**
82
+ * The users an export holds, and the entries it couldn't read, each with why. A user whose password the export
83
+ * keeps in a hash other than bcrypt comes without one, and signs in by a code, a link or a reset.
84
+ */
85
+ function parseExport(from, document) {
86
+ const users = [], skipped = [];
87
+ const seen = /* @__PURE__ */ new Set();
88
+ const take = (entry, made) => {
89
+ if (typeof made === "string") skipped.push({
90
+ entry,
91
+ why: made
92
+ });
93
+ else if (seen.has(made.email)) skipped.push({
94
+ entry,
95
+ why: `${made.email} is in the export twice`
96
+ });
97
+ else {
98
+ seen.add(made.email);
99
+ users.push(made);
100
+ }
101
+ };
102
+ if (from === "clerk") for (const [at, record] of csvRecords(document).entries()) {
103
+ const email = record.primary_email_address;
104
+ const verified = (record.verified_email_addresses ?? "").split(/[|,;]/).map((one) => one.trim().toLowerCase());
105
+ const hasher = (record.password_hasher ?? "").trim().toLowerCase();
106
+ take(record.id || `line ${at + 2}`, userOf({
107
+ email,
108
+ name: [record.first_name, record.last_name].filter((one) => one?.trim()).join(" ") || record.username,
109
+ emailVerified: !!email && verified.includes(email.trim().toLowerCase()),
110
+ hash: hasher === "bcrypt" ? record.password_digest : void 0
111
+ }));
112
+ }
113
+ else if (from === "auth0") for (const [at, line] of document.split(/\r?\n/).entries()) {
114
+ if (!line.trim()) continue;
115
+ let record;
116
+ try {
117
+ record = JSON.parse(line);
118
+ } catch {
119
+ skipped.push({
120
+ entry: `line ${at + 1}`,
121
+ why: "it isn't JSON"
122
+ });
123
+ continue;
124
+ }
125
+ const name = text(record.name) ?? ([text(record.given_name), text(record.family_name)].filter(Boolean).join(" ") || text(record.nickname));
126
+ take(text(record.user_id) ?? text(record._id?.$oid) ?? `line ${at + 1}`, userOf({
127
+ email: record.email,
128
+ name,
129
+ emailVerified: record.email_verified === true,
130
+ image: record.picture,
131
+ createdAt: record.created_at ?? record.password_set_date,
132
+ hash: record.passwordHash ?? record.password_hash,
133
+ publicMetadata: record.user_metadata,
134
+ privateMetadata: record.app_metadata
135
+ }));
136
+ }
137
+ else {
138
+ const trimmed = document.replace(/^/, "").trimStart();
139
+ let records;
140
+ if (trimmed.startsWith("[")) try {
141
+ records = JSON.parse(trimmed);
142
+ } catch {
143
+ return {
144
+ users: [],
145
+ skipped: [{
146
+ entry: "the file",
147
+ why: "it isn't a JSON array"
148
+ }]
149
+ };
150
+ }
151
+ else records = csvRecords(trimmed);
152
+ for (const [at, record] of records.entries()) {
153
+ const meta = object(json(record.raw_user_meta_data));
154
+ const confirmed = record.email_confirmed_at ?? record.confirmed_at;
155
+ take(text(record.id) ?? `entry ${at + 1}`, userOf({
156
+ email: record.email,
157
+ name: meta?.full_name ?? meta?.name,
158
+ emailVerified: typeof confirmed === "string" ? confirmed.trim() !== "" : confirmed != null,
159
+ image: meta?.avatar_url ?? meta?.picture,
160
+ createdAt: record.created_at,
161
+ hash: record.encrypted_password,
162
+ publicMetadata: meta,
163
+ privateMetadata: json(record.raw_app_meta_data)
164
+ }));
165
+ }
166
+ }
167
+ return {
168
+ users,
169
+ skipped
170
+ };
171
+ }
172
+ /** One imported user's rows, as sign-in writes a user who signs up: made at `now`, unless the export has when they joined. */
173
+ function importRows(user, now) {
174
+ const createdAt = user.createdAt ?? now;
175
+ return {
176
+ user: {
177
+ email: user.email,
178
+ name: user.name,
179
+ emailVerified: user.emailVerified,
180
+ ...user.image ? { image: user.image } : {},
181
+ ...user.publicMetadata !== void 0 ? { publicMetadata: user.publicMetadata } : {},
182
+ ...user.privateMetadata !== void 0 ? { privateMetadata: user.privateMetadata } : {},
183
+ createdAt,
184
+ updatedAt: now
185
+ },
186
+ ...user.passwordHash ? { account: {
187
+ providerId: "credential",
188
+ password: user.passwordHash,
189
+ createdAt: now,
190
+ updatedAt: now
191
+ } } : {}
192
+ };
193
+ }
194
+ //#endregion
195
+ export { IMPORT_SOURCES, csvRows, importRows, isBcrypt, parseExport };