@hulla/db-better-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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Samuel Hulla
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @hulla/db-better-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```sh
4
+ npm install @hulla/db@0.1.0 @hulla/db-better-auth@0.1.0 better-auth
5
+ ```
6
+
7
+ Better Auth storage and schema support for `@hulla/db`, tested with Better Auth
8
+ 1.7.12 on PostgreSQL under Node and Bun. Both packages are peers; no UI framework
9
+ is installed by this adapter.
10
+
11
+ ```ts
12
+ import { betterAuth } from 'better-auth'
13
+ import { hullaAdapter } from '@hulla/db-better-auth'
14
+ import { db } from './db/_generated/server'
15
+
16
+ export const auth = betterAuth({
17
+ database: hullaAdapter(db),
18
+ emailAndPassword: { enabled: true },
19
+ })
20
+ ```
21
+
22
+ Add `...betterAuthTables()` from `@hulla/db-better-auth/schema` to `defineSchema`
23
+ before generating/initializing the database. Supply the same shared provider
24
+ options to the schema helper and Better Auth when using plugins or custom fields.
25
+
26
+ See the [complete setup](https://github.com/hulladev/db/blob/main/docs/better-auth.md) for schema bootstrap, generated
27
+ static schemas, session verification, browser auth changes and supported limits.
28
+ Better Auth owns authentication; the application owns routes and authorization.
@@ -0,0 +1,6 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ import { type AdapterFactory } from "better-auth/adapters";
3
+ import type { SchemaDefinition } from "@hulla/db/schema";
4
+ import type { Database } from "@hulla/db/server";
5
+ /** Store Better Auth records in the application's generated server database. */
6
+ export declare function hullaAdapter<S extends SchemaDefinition>(db: Database<S>): AdapterFactory<BetterAuthOptions>;
package/dist/index.js ADDED
@@ -0,0 +1,116 @@
1
+ import { createAdapterFactory } from "better-auth/adapters";
2
+ import { generateAuthSchema } from "./schema.js";
3
+ function filter(where = []) {
4
+ return q => {
5
+ const exact = (field, value) => q.ilike(field, value.replace(/[\\%_]/g, "\\$&"));
6
+ const condition = (w) => {
7
+ const { field, value, operator, mode } = w;
8
+ const insensitive = mode === "insensitive";
9
+ switch (operator) {
10
+ case "eq": return insensitive && typeof value === "string" ? exact(field, value) : q.eq(field, value);
11
+ case "ne": return insensitive && typeof value === "string" ? q.not(exact(field, value)) : q.ne(field, value);
12
+ case "lt": return q.lt(field, value);
13
+ case "lte": return q.lte(field, value);
14
+ case "gt": return q.gt(field, value);
15
+ case "gte": return q.gte(field, value);
16
+ case "in":
17
+ case "not_in": {
18
+ if (!Array.isArray(value))
19
+ throw new TypeError(`Better Auth ${operator} requires an array`);
20
+ const matched = insensitive && value.every(item => typeof item === "string")
21
+ ? q.or(...value.map(item => exact(field, item)))
22
+ : q.inArray(field, value);
23
+ return operator === "not_in" ? q.not(matched) : matched;
24
+ }
25
+ case "contains": return q.contains(field, value, { caseSensitive: !insensitive });
26
+ case "starts_with": return q.startsWith(field, value, { caseSensitive: !insensitive });
27
+ case "ends_with": return q.endsWith(field, value, { caseSensitive: !insensitive });
28
+ default: throw new TypeError(`Unsupported Better Auth operator: ${String(operator)}`);
29
+ }
30
+ };
31
+ // Match Better Auth's adapter convention: AND predicates constrain the
32
+ // complete OR group, rather than interpreting the array left to right.
33
+ const and = where.filter(w => w.connector !== "OR").map(condition);
34
+ const or = where.filter(w => w.connector === "OR").map(condition);
35
+ return q.and(...and, ...(or.length ? [q.or(...or)] : []));
36
+ };
37
+ }
38
+ /** Store Better Auth records in the application's generated server database. */
39
+ export function hullaAdapter(db) {
40
+ return (options) => {
41
+ if (options.advanced?.database?.joins)
42
+ throw new TypeError("Hulla uses Better Auth's portable join fallback; disable advanced.database.joins");
43
+ function adapter(database, inTransaction) {
44
+ const atomic = (callback) => inTransaction
45
+ ? callback(database)
46
+ // Only these internal DB-only callbacks can retry after a confirmed OCC
47
+ // rollback. Better Auth's application transaction callbacks run once.
48
+ : db.transaction(tx => callback(tx), { retries: 3 });
49
+ const first = async (tx, model, where) => (await tx.select(model).where(filter(where)).limit(1))[0] ?? null;
50
+ return createAdapterFactory({
51
+ config: {
52
+ adapterId: "hulla", adapterName: "Hulla DB",
53
+ supportsDates: true, supportsBooleans: true, supportsJSON: true,
54
+ supportsArrays: true, supportsNumericIds: false, supportsUUIDs: false,
55
+ transaction: inTransaction ? false : callback => db.transaction(tx => callback(adapter(tx, true))),
56
+ },
57
+ adapter: ({ getFieldName }) => ({
58
+ async create({ model, data }) { return await database.insert(model, data); },
59
+ async findOne({ model, modelKey, where, select }) {
60
+ const projection = select?.length ? select.map(field => getFieldName({ model: modelKey ?? model, field })) : undefined;
61
+ return (await database.select(model, projection).where(filter(where)).limit(1))[0] ?? null;
62
+ },
63
+ async findMany({ model, modelKey, where, limit, offset = 0, select, sortBy }) {
64
+ if (!Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(offset + limit)) {
65
+ throw new TypeError("Better Auth limit/offset must be nonnegative safe integers");
66
+ }
67
+ if (limit === 0)
68
+ return [];
69
+ const projection = select?.length ? select.map(field => getFieldName({ model: modelKey ?? model, field })) : undefined;
70
+ let query = database.select(model, projection).where(filter(where));
71
+ if (sortBy)
72
+ query = query.orderBy(getFieldName({ model: modelKey ?? model, field: sortBy.field }), sortBy.direction);
73
+ // Core exposes cursor pagination. Better Auth requires offset; read a
74
+ // bounded ordered prefix under the normal database execution limits.
75
+ return (await query.limit(offset + limit)).slice(offset);
76
+ },
77
+ async update({ model, where, update }) {
78
+ return atomic(async (tx) => {
79
+ const row = await first(tx, model, where);
80
+ if (!row)
81
+ return null;
82
+ return (await tx.update(model, update).where({ id: row.id }))[0] ?? null;
83
+ });
84
+ },
85
+ async updateMany({ model, where, update }) {
86
+ return (await database.update(model, update).where(filter(where))).length;
87
+ },
88
+ async delete({ model, where }) {
89
+ await atomic(async (tx) => {
90
+ const row = await first(tx, model, where);
91
+ if (row)
92
+ await tx.delete(model).where({ id: row.id });
93
+ });
94
+ },
95
+ async deleteMany({ model, where }) { return (await database.delete(model).where(filter(where))).length; },
96
+ async consumeOne({ model, where }) {
97
+ return atomic(async (tx) => {
98
+ const row = await first(tx, model, where);
99
+ return row ? (await tx.delete(model).where({ id: row.id }))[0] ?? null : null;
100
+ });
101
+ },
102
+ async count({ model, where }) {
103
+ const result = await database.select(model).where(filter(where)).aggregate(({ count }) => ({ count: count() }));
104
+ if (!Number.isSafeInteger(result.count))
105
+ throw new RangeError("Better Auth count exceeds the safe integer range");
106
+ return result.count;
107
+ },
108
+ async createSchema({ file, tables }) {
109
+ return { code: generateAuthSchema(tables), path: file ?? "./db/auth-schema.ts", overwrite: false };
110
+ },
111
+ }),
112
+ })(options);
113
+ }
114
+ return adapter(db, false);
115
+ };
116
+ }
@@ -0,0 +1,66 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ import { type BetterAuthDBSchema } from "@better-auth/core/db";
3
+ import { v, type TableDefinition, type TableOptions } from "@hulla/db/schema";
4
+ type AuthField = TableDefinition["fields"][string];
5
+ type AuthTable = TableDefinition<Record<string, AuthField>, {
6
+ primaryKey: "id";
7
+ keyGeneration: "none";
8
+ unique: NonNullable<TableOptions["unique"]>;
9
+ }>;
10
+ type StringField = ReturnType<typeof v.string>;
11
+ type DateField = ReturnType<typeof v.timestamp<{}>>;
12
+ type NullableString = ReturnType<ReturnType<StringField["nullable"]>["default"]>;
13
+ type NullableDate = ReturnType<ReturnType<DateField["nullable"]>["default"]>;
14
+ type CoreTable<F extends Record<string, AuthField>> = TableDefinition<F & {
15
+ id: StringField;
16
+ }, {
17
+ primaryKey: "id";
18
+ keyGeneration: "none";
19
+ }>;
20
+ /** The default core schema has known names. Configured schemas are discovered at runtime. */
21
+ export type BetterAuthCoreTables = {
22
+ user: CoreTable<{
23
+ name: StringField;
24
+ email: StringField;
25
+ emailVerified: ReturnType<ReturnType<typeof v.boolean>["default"]>;
26
+ image: NullableString;
27
+ createdAt: DateField;
28
+ updatedAt: DateField;
29
+ }>;
30
+ session: CoreTable<{
31
+ expiresAt: DateField;
32
+ token: StringField;
33
+ createdAt: DateField;
34
+ updatedAt: DateField;
35
+ ipAddress: NullableString;
36
+ userAgent: NullableString;
37
+ userId: StringField;
38
+ }>;
39
+ account: CoreTable<{
40
+ accountId: StringField;
41
+ providerId: StringField;
42
+ userId: StringField;
43
+ accessToken: NullableString;
44
+ refreshToken: NullableString;
45
+ idToken: NullableString;
46
+ accessTokenExpiresAt: NullableDate;
47
+ refreshTokenExpiresAt: NullableDate;
48
+ scope: NullableString;
49
+ password: NullableString;
50
+ createdAt: DateField;
51
+ updatedAt: DateField;
52
+ }>;
53
+ verification: CoreTable<{
54
+ identifier: StringField;
55
+ value: StringField;
56
+ expiresAt: DateField;
57
+ createdAt: DateField;
58
+ updatedAt: DateField;
59
+ }>;
60
+ };
61
+ /** Produce tables with Better Auth's physical model and column names. */
62
+ export declare function betterAuthTables(): BetterAuthCoreTables;
63
+ export declare function betterAuthTables(options: BetterAuthOptions): Record<string, AuthTable>;
64
+ /** Generate an independent schema module; it can be imported before the application database exists. */
65
+ export declare function generateAuthSchema(tables: BetterAuthDBSchema): string;
66
+ export {};
package/dist/schema.js ADDED
@@ -0,0 +1,188 @@
1
+ import { getAuthTables } from "@better-auth/core/db";
2
+ import { defineTable, v } from "@hulla/db/schema";
3
+ function unsupported(path, detail) {
4
+ throw new TypeError(`Better Auth schema ${path}: ${detail}`);
5
+ }
6
+ function literal(value, path) {
7
+ if (value instanceof Date) {
8
+ if (!Number.isFinite(value.getTime()))
9
+ unsupported(path, "invalid Date default");
10
+ return `new Date(${JSON.stringify(value.toISOString())})`;
11
+ }
12
+ // Schema defaults must be JSON values or Dates, with no lossy serialization.
13
+ if (value === null || typeof value === "string" || typeof value === "boolean")
14
+ return JSON.stringify(value);
15
+ if (typeof value === "number" && Number.isFinite(value))
16
+ return Object.is(value, -0) ? "-0" : String(value);
17
+ if (Array.isArray(value))
18
+ return `[${value.map(item => literal(item, path)).join(", ")}]`;
19
+ if (typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
20
+ return `{ ${Object.entries(value).map(([key, item]) => `[${JSON.stringify(key)}]: ${literal(item, path)}`).join(", ")} }`;
21
+ }
22
+ return unsupported(path, "unsupported literal default");
23
+ }
24
+ function describeField(attribute, path, tables) {
25
+ let field;
26
+ let code;
27
+ const reference = attribute.references;
28
+ if (reference) {
29
+ const target = tables[reference.model] ?? Object.values(tables).find(table => table.modelName === reference.model);
30
+ if (!target)
31
+ unsupported(path, `unknown reference model ${reference.model}`);
32
+ if (reference.field !== "id")
33
+ unsupported(path, "references must target the model's id primary key");
34
+ if (attribute.type !== "string")
35
+ unsupported(path, "references require string IDs");
36
+ const action = reference.onDelete ?? "cascade";
37
+ if (action !== "cascade" && action !== "restrict" && action !== "set null")
38
+ unsupported(path, `unsupported onDelete action ${action}`);
39
+ if (action === "set null" && attribute.required !== false)
40
+ unsupported(path, "set null references must be optional");
41
+ const onDelete = action === "set null" ? "setNull" : action;
42
+ field = v.id(target.modelName, { onDelete });
43
+ code = `v.id(${JSON.stringify(target.modelName)}, { onDelete: ${JSON.stringify(onDelete)} })`;
44
+ }
45
+ else if (Array.isArray(attribute.type)) {
46
+ if (!attribute.type.length || attribute.type.some(value => typeof value !== "string"))
47
+ unsupported(path, "enum fields need a nonempty list of strings");
48
+ field = v.string().oneOf(attribute.type);
49
+ code = `v.string().oneOf(${JSON.stringify(attribute.type)})`;
50
+ }
51
+ else {
52
+ switch (attribute.type) {
53
+ case "string":
54
+ field = v.string();
55
+ code = "v.string()";
56
+ break;
57
+ case "number":
58
+ field = v.int64();
59
+ code = "v.int64()";
60
+ break;
61
+ case "boolean":
62
+ field = v.boolean();
63
+ code = "v.boolean()";
64
+ break;
65
+ case "date":
66
+ field = v.timestamp();
67
+ code = "v.timestamp()";
68
+ break;
69
+ case "json":
70
+ field = v.json();
71
+ code = "v.json()";
72
+ break;
73
+ case "string[]":
74
+ field = v.json(v.array(v.string()));
75
+ code = "v.json(v.array(v.string()))";
76
+ break;
77
+ case "number[]":
78
+ field = v.json(v.array(v.number()));
79
+ code = "v.json(v.array(v.number()))";
80
+ break;
81
+ default: return unsupported(path, `unsupported field type ${String(attribute.type)}`);
82
+ }
83
+ }
84
+ if (attribute.required === false) {
85
+ field = field.nullable();
86
+ code += ".nullable()";
87
+ }
88
+ // Better Auth evaluates function defaults, transforms and onUpdate itself.
89
+ // A nullable database field may be omitted when inserting through Hulla too.
90
+ const value = typeof attribute.defaultValue === "function" ? undefined : attribute.defaultValue;
91
+ if (value !== undefined) {
92
+ code += `.default(${literal(value, path)})`;
93
+ field = field.default(value);
94
+ }
95
+ else if (attribute.required === false) {
96
+ field = field.default(null);
97
+ code += ".default(null)";
98
+ }
99
+ return { field, code };
100
+ }
101
+ function describeTables(tables) {
102
+ const names = new Set();
103
+ return Object.entries(tables).map(([logicalName, table], tableNumber) => {
104
+ if (table.disableMigrations)
105
+ unsupported(logicalName, "disableMigrations cannot be honored by a Hulla-managed schema");
106
+ if (!table.modelName || names.has(table.modelName))
107
+ unsupported(logicalName, "modelName must be nonempty and distinct");
108
+ names.add(table.modelName);
109
+ const fields = Object.create(null);
110
+ fields.id = { field: v.string(), code: "v.string()" };
111
+ const unique = Object.create(null);
112
+ const indexes = [];
113
+ const uniqueSignatures = new Set();
114
+ const indexSignatures = new Set();
115
+ const indexNames = new Set();
116
+ const physical = (key) => {
117
+ if (key === "id")
118
+ return "id";
119
+ const field = table.fields[key];
120
+ if (!field)
121
+ return unsupported(`${logicalName}.${key}`, "unknown index field");
122
+ return field.fieldName || key;
123
+ };
124
+ const addUnique = (selected, name) => {
125
+ const signature = JSON.stringify([...selected].sort());
126
+ if (uniqueSignatures.has(signature))
127
+ return;
128
+ uniqueSignatures.add(signature);
129
+ const constraintName = name ?? `ba_${tableNumber}_unique_${uniqueSignatures.size}`;
130
+ if (Object.hasOwn(unique, constraintName))
131
+ unsupported(logicalName, `duplicate unique name ${constraintName}`);
132
+ unique[constraintName] = { fields: selected, nulls: "distinct" };
133
+ };
134
+ const addIndex = (selected, name) => {
135
+ const signature = JSON.stringify(selected);
136
+ if (indexSignatures.has(signature))
137
+ return;
138
+ if (name && indexNames.has(name))
139
+ unsupported(logicalName, `duplicate index name ${name}`);
140
+ indexSignatures.add(signature);
141
+ if (name)
142
+ indexNames.add(name);
143
+ indexes.push({ fields: selected, ...(name === undefined ? {} : { name }) });
144
+ };
145
+ for (const [key, attribute] of Object.entries(table.fields)) {
146
+ const fieldName = attribute.fieldName || key;
147
+ if (Object.hasOwn(fields, fieldName))
148
+ unsupported(`${logicalName}.${key}`, `duplicate or reserved column ${fieldName}`);
149
+ fields[fieldName] = describeField(attribute, `${logicalName}.${key}`, tables);
150
+ if (attribute.unique)
151
+ addUnique([fieldName]);
152
+ else if (attribute.index)
153
+ addIndex([fieldName]);
154
+ }
155
+ for (const index of table.indexes ?? []) {
156
+ if (!index.fields.length || new Set(index.fields).size !== index.fields.length)
157
+ unsupported(logicalName, "indexes require distinct fields");
158
+ const selected = index.fields.map(physical);
159
+ if (new Set(selected).size !== selected.length)
160
+ unsupported(logicalName, "index fields resolve to the same database column");
161
+ if (index.unique)
162
+ addUnique(selected, index.name);
163
+ else
164
+ addIndex(selected, index.name);
165
+ }
166
+ return { name: table.modelName, fields, unique, indexes };
167
+ });
168
+ }
169
+ export function betterAuthTables(options = {}) {
170
+ if (options.advanced?.database?.generateId === "serial")
171
+ unsupported("advanced.database.generateId", "serial numeric IDs are unsupported; use Better Auth string IDs");
172
+ return Object.fromEntries(describeTables(getAuthTables(options)).map(table => {
173
+ let definition = defineTable(Object.fromEntries(Object.entries(table.fields).map(([key, value]) => [key, value.field])), { primaryKey: "id", keyGeneration: "none", unique: table.unique });
174
+ for (const index of table.indexes)
175
+ definition = definition.index(index.fields, index.name === undefined ? {} : { name: index.name });
176
+ return [table.name, definition];
177
+ }));
178
+ }
179
+ /** Generate an independent schema module; it can be imported before the application database exists. */
180
+ export function generateAuthSchema(tables) {
181
+ const declarations = describeTables(tables).map(table => {
182
+ const fields = Object.entries(table.fields).map(([key, value]) => ` [${JSON.stringify(key)}]: ${value.code},`).join("\n");
183
+ const options = `{ primaryKey: "id", keyGeneration: "none", unique: ${JSON.stringify(table.unique)} }`;
184
+ const indexes = table.indexes.map(index => `.index(${JSON.stringify(index.fields)}${index.name === undefined ? "" : `, { name: ${JSON.stringify(index.name)} }`})`).join("");
185
+ return ` [${JSON.stringify(table.name)}]: defineTable({\n${fields}\n }, ${options})${indexes},`;
186
+ }).join("\n");
187
+ return `// Generated from Better Auth's schema. Better Auth owns IDs and function defaults.\nimport { defineTable, v } from "@hulla/db/schema";\n\nexport const authTables = {\n${declarations}\n};\n\nexport default authTables;\n`;
188
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@hulla/db-better-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
+ },
10
+ "./schema": {
11
+ "types": "./dist/schema.d.ts",
12
+ "default": "./dist/schema.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "peerDependencies": {
21
+ "@hulla/db": "^0.1.0",
22
+ "better-auth": "^1.7.12"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.18.0"
26
+ },
27
+ "dependencies": {
28
+ "@better-auth/core": "1.7.12"
29
+ },
30
+ "description": "Better Auth storage adapter for @hulla/db",
31
+ "license": "MIT",
32
+ "author": {
33
+ "name": "Samuel Hulla",
34
+ "url": "https://hulla.dev"
35
+ },
36
+ "homepage": "https://github.com/hulladev/db#readme",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/hulladev/db.git",
40
+ "directory": "packages/better-auth"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/hulladev/db/issues"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "registry": "https://registry.npmjs.org/"
48
+ }
49
+ }