@lunora/auth 1.0.0-alpha.13 → 1.0.0-alpha.130
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.md +38 -0
- package/README.md +99 -10
- package/dist/adapter.d.mts +4 -43
- package/dist/adapter.d.ts +4 -43
- package/dist/adapter.mjs +1 -48
- package/dist/audit.d.mts +131 -0
- package/dist/audit.d.ts +131 -0
- package/dist/audit.mjs +12 -0
- package/dist/email-guard.d.mts +127 -0
- package/dist/email-guard.d.ts +127 -0
- package/dist/email-guard.mjs +1 -0
- package/dist/index.d.mts +801 -157
- package/dist/index.d.ts +801 -157
- package/dist/index.mjs +1 -12
- package/dist/middleware.d.mts +167 -156
- package/dist/middleware.d.ts +167 -156
- package/dist/middleware.mjs +1 -53
- package/dist/packem_shared/AUTH_DO_AUDIT_PATH-ucS0M60j.mjs +1 -0
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs +1 -0
- package/dist/packem_shared/LunoraAuthAdminError-4r29Kj_y.mjs +1 -0
- package/dist/packem_shared/adapter-DA8DdALX.mjs +1 -0
- package/dist/packem_shared/adapter.d-2a61HAY2.d.ts +76 -0
- package/dist/packem_shared/adapter.d-DrD3bb1u.d.mts +76 -0
- package/dist/packem_shared/authAuditHook-C9Gt2iYp.mjs +1 -0
- package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
- package/dist/packem_shared/compileMigrationsSql-ByVJhjR6.mjs +1 -0
- package/dist/packem_shared/create-auth.d-D1CKOFWc.d.mts +142 -0
- package/dist/packem_shared/create-auth.d-D1CKOFWc.d.ts +142 -0
- package/dist/packem_shared/createAuth-8aUw8v8D.mjs +1 -0
- package/dist/packem_shared/createDoAuthWiring-68YJP-VM.mjs +1 -0
- package/dist/packem_shared/createLunoraAuthClient-DhjhCwmM.mjs +1 -0
- package/dist/packem_shared/createSignUpInvitation-ClvskwuB.mjs +1 -0
- package/dist/packem_shared/emailGateDatabaseHooks-CAygR3iq.mjs +1 -0
- package/dist/packem_shared/invite-only.d-CsPJWAwM.d.ts +126 -0
- package/dist/packem_shared/invite-only.d-DKyHHkkQ.d.mts +126 -0
- package/dist/packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs +1 -0
- package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
- package/dist/packem_shared/sessionPresets-C867Mlo4.mjs +1 -0
- package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
- package/dist/plugins-client.d.mts +165 -1
- package/dist/plugins-client.d.ts +165 -1
- package/dist/plugins-client.mjs +1 -2
- package/dist/plugins-enterprise-client.d.mts +15 -0
- package/dist/plugins-enterprise-client.d.ts +15 -0
- package/dist/plugins-enterprise-client.mjs +1 -0
- package/dist/plugins-enterprise.d.mts +1670 -0
- package/dist/plugins-enterprise.d.ts +1670 -0
- package/dist/plugins-enterprise.mjs +1 -0
- package/dist/plugins.d.mts +125 -2
- package/dist/plugins.d.ts +125 -2
- package/dist/plugins.mjs +1 -22
- package/dist/schema.d.mts +39 -39
- package/dist/schema.d.ts +39 -39
- package/dist/schema.mjs +1 -62
- package/dist/sql-store.d.mts +28 -28
- package/dist/sql-store.d.ts +28 -28
- package/dist/sql-store.mjs +1 -184
- package/dist/store.d.mts +65 -47
- package/dist/store.d.ts +65 -47
- package/dist/store.mjs +1 -183
- package/dist/turnstile-middleware.d.mts +66 -55
- package/dist/turnstile-middleware.d.ts +66 -55
- package/dist/turnstile-middleware.mjs +1 -45
- package/dist/turnstile.d.mts +42 -59
- package/dist/turnstile.d.ts +42 -59
- package/dist/turnstile.mjs +1 -61
- package/package.json +39 -5
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
- package/dist/packem_shared/LunoraAuthAdminError-BxrfEeA_.mjs +0 -249
- package/dist/packem_shared/compileMigrationsSql-cyE5U18R.mjs +0 -29
- package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
- package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
- package/dist/packem_shared/createAuth-hRGxUJ9w.mjs +0 -85
- package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
package/dist/sql-store.d.ts
CHANGED
|
@@ -12,40 +12,40 @@ interface D1Like {
|
|
|
12
12
|
};
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
* The minimal SQL seam a {@link createSqlAuthStore} runs on — structurally the
|
|
16
|
-
* same `{ all, run }` contract as `@lunora/d1`'s `D1Exec`, so a Lunora D1 binding
|
|
17
|
-
* satisfies it directly (see {@link d1Executor}) and a `node:sqlite` handle does
|
|
18
|
-
* too in tests. `all` runs reads and returns rows; `run` runs writes.
|
|
19
|
-
*/
|
|
15
|
+
* The minimal SQL seam a {@link createSqlAuthStore} runs on — structurally the
|
|
16
|
+
* same `{ all, run }` contract as `@lunora/d1`'s `D1Exec`, so a Lunora D1 binding
|
|
17
|
+
* satisfies it directly (see {@link d1Executor}) and a `node:sqlite` handle does
|
|
18
|
+
* too in tests. `all` runs reads and returns rows; `run` runs writes.
|
|
19
|
+
*/
|
|
20
20
|
interface SqlExecutor {
|
|
21
21
|
all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
|
|
22
22
|
run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<void>;
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
|
-
* An {@link AuthStore} backed by a SQL database through the {@link SqlExecutor}
|
|
26
|
-
* seam — the production counterpart to `createMemoryAuthStore`. Point it at the
|
|
27
|
-
* same database that hosts Lunora's global (D1) tables (the ones `authTables(...)`
|
|
28
|
-
* generates) and better-auth's reads/writes land there as ordinary rows Lunora
|
|
29
|
-
* can also query. Assumes the auth tables already exist (Lunora owns the schema /
|
|
30
|
-
* migrations); it never issues DDL.
|
|
31
|
-
*
|
|
32
|
-
* ```ts
|
|
33
|
-
* const store = createSqlAuthStore(d1Executor(env.DB));
|
|
34
|
-
* const auth = createAuth({ secret: env.AUTH_SECRET, database: lunoraAuthAdapter(store) });
|
|
35
|
-
* ```
|
|
36
|
-
*
|
|
37
|
-
* Clause semantics match `createMemoryAuthStore` (operator parity is
|
|
38
|
-
* covered by a cross-store agreement test) with one unavoidable caveat:
|
|
39
|
-
* case-**insensitive** matching uses SQLite's ASCII-only `LOWER()`, whereas the
|
|
40
|
-
* in-memory store uses JS full-Unicode `toLowerCase()`. They agree on ASCII
|
|
41
|
-
* (emails, ids, tokens — the credential path); they can differ only for
|
|
42
|
-
* case-insensitive comparison of non-ASCII text.
|
|
43
|
-
*/
|
|
25
|
+
* An {@link AuthStore} backed by a SQL database through the {@link SqlExecutor}
|
|
26
|
+
* seam — the production counterpart to `createMemoryAuthStore`. Point it at the
|
|
27
|
+
* same database that hosts Lunora's global (D1) tables (the ones `authTables(...)`
|
|
28
|
+
* generates) and better-auth's reads/writes land there as ordinary rows Lunora
|
|
29
|
+
* can also query. Assumes the auth tables already exist (Lunora owns the schema /
|
|
30
|
+
* migrations); it never issues DDL.
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* const store = createSqlAuthStore(d1Executor(env.DB));
|
|
34
|
+
* const auth = createAuth({ secret: env.AUTH_SECRET, database: lunoraAuthAdapter(store) });
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* Clause semantics match `createMemoryAuthStore` (operator parity is
|
|
38
|
+
* covered by a cross-store agreement test) with one unavoidable caveat:
|
|
39
|
+
* case-**insensitive** matching uses SQLite's ASCII-only `LOWER()`, whereas the
|
|
40
|
+
* in-memory store uses JS full-Unicode `toLowerCase()`. They agree on ASCII
|
|
41
|
+
* (emails, ids, tokens — the credential path); they can differ only for
|
|
42
|
+
* case-insensitive comparison of non-ASCII text.
|
|
43
|
+
*/
|
|
44
44
|
declare const createSqlAuthStore: (executor: SqlExecutor) => AuthStore;
|
|
45
45
|
/**
|
|
46
|
-
* Wrap a Cloudflare D1 binding (`env.DB`) as a {@link SqlExecutor}, so
|
|
47
|
-
* `createSqlAuthStore(d1Executor(env.DB))` routes better-auth onto D1 — the same
|
|
48
|
-
* binding Lunora's `.global()` tables use.
|
|
49
|
-
*/
|
|
46
|
+
* Wrap a Cloudflare D1 binding (`env.DB`) as a {@link SqlExecutor}, so
|
|
47
|
+
* `createSqlAuthStore(d1Executor(env.DB))` routes better-auth onto D1 — the same
|
|
48
|
+
* binding Lunora's `.global()` tables use.
|
|
49
|
+
*/
|
|
50
50
|
declare const d1Executor: (database: D1Like) => SqlExecutor;
|
|
51
51
|
export { SqlExecutor, createSqlAuthStore, d1Executor };
|
package/dist/sql-store.mjs
CHANGED
|
@@ -1,184 +1 @@
|
|
|
1
|
-
const
|
|
2
|
-
const NEVER = { params: [], sql: "0" };
|
|
3
|
-
const sided = (column, insensitive) => insensitive ? { column: `LOWER(${column})`, placeholder: "LOWER(?)" } : { column, placeholder: "?" };
|
|
4
|
-
const patternFragment = (column, value, operator, insensitive) => {
|
|
5
|
-
if (typeof value !== "string") {
|
|
6
|
-
return NEVER;
|
|
7
|
-
}
|
|
8
|
-
const side = sided(column, insensitive);
|
|
9
|
-
if (operator === "contains") {
|
|
10
|
-
return { params: [value], sql: `instr(${side.column}, ${side.placeholder}) > 0` };
|
|
11
|
-
}
|
|
12
|
-
if (operator === "starts_with") {
|
|
13
|
-
return { params: [value], sql: `instr(${side.column}, ${side.placeholder}) = 1` };
|
|
14
|
-
}
|
|
15
|
-
return { params: [value, value], sql: `substr(${side.column}, -length(?)) = ${side.placeholder}` };
|
|
16
|
-
};
|
|
17
|
-
const equalityFragment = (column, value, insensitive, negated) => {
|
|
18
|
-
if (value === null) {
|
|
19
|
-
return { params: [], sql: `${column} IS ${negated ? "NOT " : ""}NULL` };
|
|
20
|
-
}
|
|
21
|
-
const side = sided(column, insensitive);
|
|
22
|
-
const symbol = negated ? "<>" : "=";
|
|
23
|
-
return { params: [value], sql: `${side.column} ${symbol} ${side.placeholder}` };
|
|
24
|
-
};
|
|
25
|
-
const inFragment = (column, value, negated, insensitive) => {
|
|
26
|
-
const values = Array.isArray(value) ? value : [];
|
|
27
|
-
if (values.length === 0) {
|
|
28
|
-
return { params: [], sql: negated ? "1" : "0" };
|
|
29
|
-
}
|
|
30
|
-
const side = sided(column, insensitive);
|
|
31
|
-
const placeholders = values.map(() => side.placeholder).join(", ");
|
|
32
|
-
return { params: [...values], sql: `${side.column} ${negated ? "NOT IN" : "IN"} (${placeholders})` };
|
|
33
|
-
};
|
|
34
|
-
const compileClause = (clause) => {
|
|
35
|
-
const column = quoteId(clause.field);
|
|
36
|
-
const { mode, operator, value } = clause;
|
|
37
|
-
const insensitive = mode === "insensitive";
|
|
38
|
-
switch (operator) {
|
|
39
|
-
case "contains":
|
|
40
|
-
case "ends_with":
|
|
41
|
-
case "starts_with": {
|
|
42
|
-
return patternFragment(column, value, operator, insensitive);
|
|
43
|
-
}
|
|
44
|
-
case "gt": {
|
|
45
|
-
return { params: [value], sql: `${column} > ?` };
|
|
46
|
-
}
|
|
47
|
-
case "gte": {
|
|
48
|
-
return { params: [value], sql: `${column} >= ?` };
|
|
49
|
-
}
|
|
50
|
-
case "in": {
|
|
51
|
-
return inFragment(column, value, false, insensitive);
|
|
52
|
-
}
|
|
53
|
-
case "lt": {
|
|
54
|
-
return { params: [value], sql: `${column} < ?` };
|
|
55
|
-
}
|
|
56
|
-
case "lte": {
|
|
57
|
-
return { params: [value], sql: `${column} <= ?` };
|
|
58
|
-
}
|
|
59
|
-
case "ne": {
|
|
60
|
-
return equalityFragment(column, value, insensitive, true);
|
|
61
|
-
}
|
|
62
|
-
case "not_in": {
|
|
63
|
-
return inFragment(column, value, true, insensitive);
|
|
64
|
-
}
|
|
65
|
-
// "eq" and the default: null-aware equality.
|
|
66
|
-
default: {
|
|
67
|
-
return equalityFragment(column, value, insensitive, false);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
const compileWhere = (where) => {
|
|
72
|
-
if (where.length === 0) {
|
|
73
|
-
return { params: [], sql: "" };
|
|
74
|
-
}
|
|
75
|
-
let accumulator = compileClause(where[0]);
|
|
76
|
-
for (const clause of where.slice(1)) {
|
|
77
|
-
const fragment = compileClause(clause);
|
|
78
|
-
const connector = clause.connector === "OR" ? "OR" : "AND";
|
|
79
|
-
accumulator = { params: [...accumulator.params, ...fragment.params], sql: `(${accumulator.sql} ${connector} ${fragment.sql})` };
|
|
80
|
-
}
|
|
81
|
-
return accumulator;
|
|
82
|
-
};
|
|
83
|
-
const whereSuffix = (fragment) => fragment.sql ? ` WHERE ${fragment.sql}` : "";
|
|
84
|
-
const createSqlAuthStore = (executor) => {
|
|
85
|
-
const selectRows = (model, where) => {
|
|
86
|
-
const fragment = compileWhere(where);
|
|
87
|
-
return executor.all(`SELECT * FROM ${quoteId(model)}${whereSuffix(fragment)}`, fragment.params);
|
|
88
|
-
};
|
|
89
|
-
return {
|
|
90
|
-
consumeOne: async (model, where) => {
|
|
91
|
-
const fragment = compileWhere(where);
|
|
92
|
-
const table = quoteId(model);
|
|
93
|
-
const [row] = await executor.all(
|
|
94
|
-
`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table}${whereSuffix(fragment)} LIMIT 1) RETURNING *`,
|
|
95
|
-
fragment.params
|
|
96
|
-
);
|
|
97
|
-
return row;
|
|
98
|
-
},
|
|
99
|
-
count: async (model, where) => {
|
|
100
|
-
const fragment = compileWhere(where);
|
|
101
|
-
const [row] = await executor.all(`SELECT COUNT(*) AS __count FROM ${quoteId(model)}${whereSuffix(fragment)}`, fragment.params);
|
|
102
|
-
return Number(row?.["__count"] ?? 0);
|
|
103
|
-
},
|
|
104
|
-
create: async (model, data) => {
|
|
105
|
-
const columns = Object.keys(data);
|
|
106
|
-
const placeholders = columns.map(() => "?").join(", ");
|
|
107
|
-
const sql = `INSERT INTO ${quoteId(model)} (${columns.map((column) => quoteId(column)).join(", ")}) VALUES (${placeholders})`;
|
|
108
|
-
await executor.run(
|
|
109
|
-
sql,
|
|
110
|
-
columns.map((column) => data[column])
|
|
111
|
-
);
|
|
112
|
-
return { ...data };
|
|
113
|
-
},
|
|
114
|
-
incrementOne: async (model, where, increment, set) => {
|
|
115
|
-
const table = quoteId(model);
|
|
116
|
-
const incrementColumns = Object.keys(increment);
|
|
117
|
-
const setColumns = set ? Object.keys(set) : [];
|
|
118
|
-
const fragment = compileWhere(where);
|
|
119
|
-
if (incrementColumns.length === 0 && setColumns.length === 0) {
|
|
120
|
-
const [row2] = await executor.all(`SELECT * FROM ${table}${whereSuffix(fragment)} LIMIT 1`, fragment.params);
|
|
121
|
-
return row2;
|
|
122
|
-
}
|
|
123
|
-
const assignments = [
|
|
124
|
-
// COALESCE(col, 0) so a NULL counter advances from 0 rather than staying
|
|
125
|
-
// NULL (`NULL + ? = NULL` in SQLite/D1) — matches the memory store, which
|
|
126
|
-
// treats a non-numeric/absent counter as 0.
|
|
127
|
-
...incrementColumns.map((column) => `${quoteId(column)} = COALESCE(${quoteId(column)}, 0) + ?`),
|
|
128
|
-
...setColumns.map((column) => `${quoteId(column)} = ?`)
|
|
129
|
-
].join(", ");
|
|
130
|
-
const [row] = await executor.all(
|
|
131
|
-
`UPDATE ${table} SET ${assignments} WHERE rowid IN (SELECT rowid FROM ${table}${whereSuffix(fragment)} LIMIT 1) RETURNING *`,
|
|
132
|
-
[...incrementColumns.map((column) => increment[column]), ...setColumns.map((column) => set[column]), ...fragment.params]
|
|
133
|
-
);
|
|
134
|
-
return row;
|
|
135
|
-
},
|
|
136
|
-
read: async (model, query) => {
|
|
137
|
-
const fragment = compileWhere(query.where);
|
|
138
|
-
const parameters = [...fragment.params];
|
|
139
|
-
let sql = `SELECT * FROM ${quoteId(model)}${whereSuffix(fragment)}`;
|
|
140
|
-
if (query.sortBy) {
|
|
141
|
-
sql += ` ORDER BY ${quoteId(query.sortBy.field)} ${query.sortBy.direction === "asc" ? "ASC" : "DESC"}`;
|
|
142
|
-
}
|
|
143
|
-
if (query.limit !== void 0) {
|
|
144
|
-
sql += " LIMIT ?";
|
|
145
|
-
parameters.push(Math.trunc(query.limit));
|
|
146
|
-
}
|
|
147
|
-
if (query.offset) {
|
|
148
|
-
sql += `${query.limit === void 0 ? " LIMIT -1" : ""} OFFSET ?`;
|
|
149
|
-
parameters.push(Math.trunc(query.offset));
|
|
150
|
-
}
|
|
151
|
-
return executor.all(sql, parameters);
|
|
152
|
-
},
|
|
153
|
-
remove: async (model, where) => {
|
|
154
|
-
const fragment = compileWhere(where);
|
|
155
|
-
const deleted = await executor.all(`DELETE FROM ${quoteId(model)}${whereSuffix(fragment)} RETURNING *`, fragment.params);
|
|
156
|
-
return deleted.length;
|
|
157
|
-
},
|
|
158
|
-
update: async (model, where, values) => {
|
|
159
|
-
const columns = Object.keys(values);
|
|
160
|
-
if (columns.length === 0) {
|
|
161
|
-
return selectRows(model, where);
|
|
162
|
-
}
|
|
163
|
-
const assignments = columns.map((column) => `${quoteId(column)} = ?`).join(", ");
|
|
164
|
-
const fragment = compileWhere(where);
|
|
165
|
-
return executor.all(`UPDATE ${quoteId(model)} SET ${assignments}${whereSuffix(fragment)} RETURNING *`, [
|
|
166
|
-
...columns.map((column) => values[column]),
|
|
167
|
-
...fragment.params
|
|
168
|
-
]);
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
};
|
|
172
|
-
const d1Executor = (database) => {
|
|
173
|
-
return {
|
|
174
|
-
all: async (sql, parameters) => {
|
|
175
|
-
const result = await database.prepare(sql).bind(...parameters).all();
|
|
176
|
-
return result.results ?? [];
|
|
177
|
-
},
|
|
178
|
-
run: async (sql, parameters) => {
|
|
179
|
-
await database.prepare(sql).bind(...parameters).run();
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
};
|
|
183
|
-
|
|
184
|
-
export { createSqlAuthStore, d1Executor };
|
|
1
|
+
const l=s=>`"${s.replaceAll('"','""')}"`,T="_creationTime",N=/no such column|column .{0,64}? does not exist/iu,g={params:[],sql:"0"},R=(s,r)=>r?{column:`LOWER(${s})`,placeholder:"LOWER(?)"}:{column:s,placeholder:"?"},M=(s,r,a,c)=>{if(typeof r!="string")return g;const t=R(s,c);return a==="contains"?{params:[r],sql:`instr(${t.column}, ${t.placeholder}) > 0`}:a==="starts_with"?{params:[r],sql:`instr(${t.column}, ${t.placeholder}) = 1`}:{params:[r,r],sql:`substr(${t.column}, -length(?)) = ${t.placeholder}`}},h=(s,r,a,c)=>{if(r===null)return{params:[],sql:`${s} IS ${c?"NOT ":""}NULL`};const t=R(s,a),n=c?"<>":"=";return{params:[r],sql:`${t.column} ${n} ${t.placeholder}`}},O=(s,r,a,c)=>{const t=Array.isArray(r)?r:[];if(t.length===0)return{params:[],sql:a?"1":"0"};const n=R(s,c),e=t.map(()=>n.placeholder).join(", ");return{params:[...t],sql:`${n.column} ${a?"NOT IN":"IN"} (${e})`}},L=s=>{const r=l(s.field),{mode:a,operator:c,value:t}=s,n=a==="insensitive";switch(c){case"contains":case"ends_with":case"starts_with":return M(r,t,c,n);case"gt":return{params:[t],sql:`${r} > ?`};case"gte":return{params:[t],sql:`${r} >= ?`};case"in":return O(r,t,!1,n);case"lt":return{params:[t],sql:`${r} < ?`};case"lte":return{params:[t],sql:`${r} <= ?`};case"ne":return h(r,t,n,!0);case"not_in":return O(r,t,!0,n);default:return h(r,t,n,!1)}},d=(s,r)=>{if(s.length===0)return;const a=s.map(c=>L(c));return{params:a.flatMap(c=>c.params),sql:a.map(c=>`(${c.sql})`).join(` ${r} `)}},E=s=>{const r=[d(s.filter(a=>a.connector!=="OR"),"AND"),d(s.filter(a=>a.connector==="OR"),"OR")].filter(a=>a!==void 0);return r.length===0?{params:[],sql:""}:{params:r.flatMap(a=>a.params),sql:r.map(a=>`(${a.sql})`).join(" AND ")}},$=s=>s.sql?` WHERE ${s.sql}`:"",S=s=>{const r=(t,n)=>{const e=E(n);return s.all(`SELECT * FROM ${l(t)}${$(e)}`,e.params)},a=new Map,c=async t=>{const n=a.get(t);if(n!==void 0)return n;try{await s.all(`SELECT ${l(t)}.${l(T)} FROM ${l(t)} LIMIT 0`,[])}catch(e){return N.test(e instanceof Error?e.message:String(e))&&a.set(t,!1),!1}return a.set(t,!0),!0};return{consumeOne:async(t,n)=>{const e=E(n),o=l(t),[i]=await s.all(`DELETE FROM ${o} WHERE rowid IN (SELECT rowid FROM ${o}${$(e)} LIMIT 1) RETURNING *`,e.params);return i},count:async(t,n)=>{const e=E(n),[o]=await s.all(`SELECT COUNT(*) AS __count FROM ${l(t)}${$(e)}`,e.params);return Number(o?.__count??0)},create:async(t,n)=>{const e=T in n||!await c(t)?n:{[T]:Date.now(),...n},o=Object.keys(e),i=o.map(()=>"?").join(", "),u=`INSERT INTO ${l(t)} (${o.map(m=>l(m)).join(", ")}) VALUES (${i})`;return await s.run(u,o.map(m=>e[m])),{...n}},incrementOne:async(t,n,e,o)=>{const i=l(t),u=Object.keys(e),m=o?Object.keys(o):[],f=E(n);if(u.length===0&&m.length===0){const[p]=await s.all(`SELECT * FROM ${i}${$(f)} LIMIT 1`,f.params);return p}const I=[...u.map(p=>`${l(p)} = COALESCE(${l(p)}, 0) + ?`),...m.map(p=>`${l(p)} = ?`)].join(", "),[w]=await s.all(`UPDATE ${i} SET ${I} WHERE rowid IN (SELECT rowid FROM ${i}${$(f)} LIMIT 1) RETURNING *`,[...u.map(p=>e[p]),...m.map(p=>o[p]),...f.params]);return w},read:async(t,n)=>{const e=E(n.where),o=[...e.params];let i=`SELECT * FROM ${l(t)}${$(e)}`;return n.sortBy&&(i+=` ORDER BY ${l(n.sortBy.field)} ${n.sortBy.direction==="asc"?"ASC":"DESC"}`),n.limit!==void 0&&(i+=" LIMIT ?",o.push(Math.trunc(n.limit))),n.offset&&(i+=`${n.limit===void 0?" LIMIT -1":""} OFFSET ?`,o.push(Math.trunc(n.offset))),s.all(i,o)},remove:async(t,n)=>{const e=E(n);return(await s.all(`DELETE FROM ${l(t)}${$(e)} RETURNING *`,e.params)).length},update:async(t,n,e)=>{const o=Object.keys(e);if(o.length===0)return r(t,n);const i=o.map(m=>`${l(m)} = ?`).join(", "),u=E(n);return s.all(`UPDATE ${l(t)} SET ${i}${$(u)} RETURNING *`,[...o.map(m=>e[m]),...u.params])}}},C=s=>({all:async(r,a)=>(await s.prepare(r).bind(...a).all()).results??[],run:async(r,a)=>{await s.prepare(r).bind(...a).run()}});export{S as createSqlAuthStore,C as d1Executor};
|
package/dist/store.d.mts
CHANGED
|
@@ -2,10 +2,10 @@ import { CustomAdapter } from 'better-auth/adapters';
|
|
|
2
2
|
/** A stored auth row — an opaque bag of columns keyed by better-auth field name. */
|
|
3
3
|
type AuthRow = Record<string, unknown>;
|
|
4
4
|
/**
|
|
5
|
-
* One normalized better-auth where clause. Derived from {@link CustomAdapter}'s
|
|
6
|
-
* own method signature (rather than re-declared) so a better-auth change to the
|
|
7
|
-
* clause shape surfaces as a compile error here, not a silent mis-match.
|
|
8
|
-
*/
|
|
5
|
+
* One normalized better-auth where clause. Derived from {@link CustomAdapter}'s
|
|
6
|
+
* own method signature (rather than re-declared) so a better-auth change to the
|
|
7
|
+
* clause shape surfaces as a compile error here, not a silent mis-match.
|
|
8
|
+
*/
|
|
9
9
|
type AuthWhereClause = NonNullable<Parameters<CustomAdapter["findOne"]>[0]["where"]>[number];
|
|
10
10
|
/** Read query handed to {@link AuthStore.read}: a where filter plus optional sort/window. */
|
|
11
11
|
interface AuthQuery {
|
|
@@ -18,48 +18,48 @@ interface AuthQuery {
|
|
|
18
18
|
where: ReadonlyArray<AuthWhereClause>;
|
|
19
19
|
}
|
|
20
20
|
/**
|
|
21
|
-
* The minimal table-addressed store the `lunoraAuthAdapter` drives. This is the
|
|
22
|
-
* seam a Lunora runtime binds to its ORM: back each method with `ctx.db` over
|
|
23
|
-
* the global (D1) auth tables that `authTables(...)` generates, and better-auth's
|
|
24
|
-
* reads/writes flow through Lunora's data layer (triggers, aggregates, OCC)
|
|
25
|
-
* instead of better-auth's own adapter. Field names and table (`model`) names are
|
|
26
|
-
* already the database names better-auth resolved from the schema, so a store
|
|
27
|
-
* passes them straight through.
|
|
28
|
-
*
|
|
29
|
-
* {@link createMemoryAuthStore} is a reference in-memory implementation (also
|
|
30
|
-
* what the tests run better-auth against); `createSqlAuthStore` is the SQL one.
|
|
31
|
-
*/
|
|
21
|
+
* The minimal table-addressed store the `lunoraAuthAdapter` drives. This is the
|
|
22
|
+
* seam a Lunora runtime binds to its ORM: back each method with `ctx.db` over
|
|
23
|
+
* the global (D1) auth tables that `authTables(...)` generates, and better-auth's
|
|
24
|
+
* reads/writes flow through Lunora's data layer (triggers, aggregates, OCC)
|
|
25
|
+
* instead of better-auth's own adapter. Field names and table (`model`) names are
|
|
26
|
+
* already the database names better-auth resolved from the schema, so a store
|
|
27
|
+
* passes them straight through.
|
|
28
|
+
*
|
|
29
|
+
* {@link createMemoryAuthStore} is a reference in-memory implementation (also
|
|
30
|
+
* what the tests run better-auth against); `createSqlAuthStore` is the SQL one.
|
|
31
|
+
*/
|
|
32
32
|
interface AuthStore {
|
|
33
33
|
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
34
|
+
* Atomically delete **at most one** row in `model` matching `where` and
|
|
35
|
+
* return it (or `undefined` if none matched). Backs better-auth's
|
|
36
|
+
* single-use-token consume (OTP / magic-link / email-verification /
|
|
37
|
+
* password-reset): implementing it natively — one round trip that finds and
|
|
38
|
+
* deletes in a single statement — closes the read-then-delete race the
|
|
39
|
+
* factory's `findMany` + `deleteMany` fallback would otherwise leave open.
|
|
40
|
+
*/
|
|
41
41
|
consumeOne: (model: string, where: ReadonlyArray<AuthWhereClause>) => Promise<AuthRow | undefined>;
|
|
42
42
|
/** Count rows in `model` matching `where` (empty `where` = all rows). */
|
|
43
43
|
count: (model: string, where: ReadonlyArray<AuthWhereClause>) => Promise<number>;
|
|
44
44
|
/** Insert `data` into `model`; return the stored row (the adapter pre-fills `id`). */
|
|
45
45
|
create: (model: string, data: AuthRow) => Promise<AuthRow>;
|
|
46
46
|
/**
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
47
|
+
* Atomically apply signed numeric deltas to **at most one** row in `model`
|
|
48
|
+
* matching `where`, then return the updated row (or `undefined` if the guard
|
|
49
|
+
* matched none). For each `increment` entry it applies `field = field + delta`
|
|
50
|
+
* (a negative delta decrements); the optional `set` map assigns absolute
|
|
51
|
+
* values in the same step. The `where` clause is both selector **and** guard
|
|
52
|
+
* — comparison operators are honoured, so a guard like
|
|
53
|
+
* `{ field: "count", operator: "lt", value: max }` only mutates the row while
|
|
54
|
+
* it still satisfies the predicate.
|
|
55
|
+
*
|
|
56
|
+
* Backs better-auth's durable (`storage: "database"`) rate limiter, whose
|
|
57
|
+
* counter rides these tables. Implementing it natively — one statement that
|
|
58
|
+
* guards, increments, and returns — gives the **one-winner-across-isolates**
|
|
59
|
+
* guarantee the read-then-update fallback cannot: on Workers two concurrent
|
|
60
|
+
* requests would otherwise both read `count=4` and both write `5`, letting a
|
|
61
|
+
* `max` of 5 pass 6+. Same race-closing rationale as {@link AuthStore.consumeOne}.
|
|
62
|
+
*/
|
|
63
63
|
incrementOne: (model: string, where: ReadonlyArray<AuthWhereClause>, increment: Record<string, number>, set?: AuthRow) => Promise<AuthRow | undefined>;
|
|
64
64
|
/** Read rows from `model` honouring the filter/sort/window in `query`. */
|
|
65
65
|
read: (model: string, query: AuthQuery) => Promise<AuthRow[]>;
|
|
@@ -69,16 +69,34 @@ interface AuthStore {
|
|
|
69
69
|
update: (model: string, where: ReadonlyArray<AuthWhereClause>, values: AuthRow) => Promise<AuthRow[]>;
|
|
70
70
|
}
|
|
71
71
|
/**
|
|
72
|
-
* Evaluate a better-auth where clause list against a row.
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
|
|
72
|
+
* Evaluate a better-auth where clause list against a row.
|
|
73
|
+
*
|
|
74
|
+
* better-auth hands an adapter a FLAT list in which each clause carries its own
|
|
75
|
+
* `connector` (`AND` by default). Every persistent adapter it ships resolves that
|
|
76
|
+
* by PARTITIONING: `AND(and-clauses) AND OR(or-clauses)`. The OR clauses are
|
|
77
|
+
* alternatives among themselves, never an escape hatch from the AND clauses —
|
|
78
|
+
* `@better-auth/kysely-adapter` pushes each group into its own `.where()` (two
|
|
79
|
+
* `.where()` calls are ANDed), `@better-auth/drizzle-adapter` ends in
|
|
80
|
+
* `and(andClause, orClause)`, and `@better-auth/prisma-adapter` emits
|
|
81
|
+
* `{ AND: […], OR: […] }`, which Prisma also ANDs.
|
|
82
|
+
*
|
|
83
|
+
* This used to fold the list left-associatively instead, so `[A, B(OR), C(OR)]`
|
|
84
|
+
* meant `A OR B OR C` — strictly BROADER than any of them. On a credential lookup
|
|
85
|
+
* that is an authentication bypass in shape: a row failing the primary condition
|
|
86
|
+
* is still returned because a secondary one matched. `@better-auth/memory-adapter`
|
|
87
|
+
* does fold left, but it is the only one and it re-evaluates `where[0]` inside the
|
|
88
|
+
* same loop; the persistent adapters are the contract worth mirroring, and they
|
|
89
|
+
* are also what a plugin author will have tested against.
|
|
90
|
+
*
|
|
91
|
+
* An empty list matches every row, and a list with no OR clause is unaffected —
|
|
92
|
+
* which is every clause list better-auth 1.7.1 itself builds. Exported so any
|
|
93
|
+
* in-memory-style {@link AuthStore} can reuse it.
|
|
94
|
+
*/
|
|
77
95
|
declare const matchesWhere: (row: AuthRow, where: ReadonlyArray<AuthWhereClause>) => boolean;
|
|
78
96
|
/**
|
|
79
|
-
* Reference in-memory {@link AuthStore} — used to run better-auth end to end in
|
|
80
|
-
* tests, and a worked example of the contract a Lunora-`ctx.db`-backed store
|
|
81
|
-
* fulfils. Not for production (state is per-instance and non-durable).
|
|
82
|
-
*/
|
|
97
|
+
* Reference in-memory {@link AuthStore} — used to run better-auth end to end in
|
|
98
|
+
* tests, and a worked example of the contract a Lunora-`ctx.db`-backed store
|
|
99
|
+
* fulfils. Not for production (state is per-instance and non-durable).
|
|
100
|
+
*/
|
|
83
101
|
declare const createMemoryAuthStore: () => AuthStore;
|
|
84
102
|
export { AuthQuery, type AuthRow, AuthStore, type AuthWhereClause, createMemoryAuthStore, matchesWhere };
|
package/dist/store.d.ts
CHANGED
|
@@ -2,10 +2,10 @@ import { CustomAdapter } from 'better-auth/adapters';
|
|
|
2
2
|
/** A stored auth row — an opaque bag of columns keyed by better-auth field name. */
|
|
3
3
|
type AuthRow = Record<string, unknown>;
|
|
4
4
|
/**
|
|
5
|
-
* One normalized better-auth where clause. Derived from {@link CustomAdapter}'s
|
|
6
|
-
* own method signature (rather than re-declared) so a better-auth change to the
|
|
7
|
-
* clause shape surfaces as a compile error here, not a silent mis-match.
|
|
8
|
-
*/
|
|
5
|
+
* One normalized better-auth where clause. Derived from {@link CustomAdapter}'s
|
|
6
|
+
* own method signature (rather than re-declared) so a better-auth change to the
|
|
7
|
+
* clause shape surfaces as a compile error here, not a silent mis-match.
|
|
8
|
+
*/
|
|
9
9
|
type AuthWhereClause = NonNullable<Parameters<CustomAdapter["findOne"]>[0]["where"]>[number];
|
|
10
10
|
/** Read query handed to {@link AuthStore.read}: a where filter plus optional sort/window. */
|
|
11
11
|
interface AuthQuery {
|
|
@@ -18,48 +18,48 @@ interface AuthQuery {
|
|
|
18
18
|
where: ReadonlyArray<AuthWhereClause>;
|
|
19
19
|
}
|
|
20
20
|
/**
|
|
21
|
-
* The minimal table-addressed store the `lunoraAuthAdapter` drives. This is the
|
|
22
|
-
* seam a Lunora runtime binds to its ORM: back each method with `ctx.db` over
|
|
23
|
-
* the global (D1) auth tables that `authTables(...)` generates, and better-auth's
|
|
24
|
-
* reads/writes flow through Lunora's data layer (triggers, aggregates, OCC)
|
|
25
|
-
* instead of better-auth's own adapter. Field names and table (`model`) names are
|
|
26
|
-
* already the database names better-auth resolved from the schema, so a store
|
|
27
|
-
* passes them straight through.
|
|
28
|
-
*
|
|
29
|
-
* {@link createMemoryAuthStore} is a reference in-memory implementation (also
|
|
30
|
-
* what the tests run better-auth against); `createSqlAuthStore` is the SQL one.
|
|
31
|
-
*/
|
|
21
|
+
* The minimal table-addressed store the `lunoraAuthAdapter` drives. This is the
|
|
22
|
+
* seam a Lunora runtime binds to its ORM: back each method with `ctx.db` over
|
|
23
|
+
* the global (D1) auth tables that `authTables(...)` generates, and better-auth's
|
|
24
|
+
* reads/writes flow through Lunora's data layer (triggers, aggregates, OCC)
|
|
25
|
+
* instead of better-auth's own adapter. Field names and table (`model`) names are
|
|
26
|
+
* already the database names better-auth resolved from the schema, so a store
|
|
27
|
+
* passes them straight through.
|
|
28
|
+
*
|
|
29
|
+
* {@link createMemoryAuthStore} is a reference in-memory implementation (also
|
|
30
|
+
* what the tests run better-auth against); `createSqlAuthStore` is the SQL one.
|
|
31
|
+
*/
|
|
32
32
|
interface AuthStore {
|
|
33
33
|
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
34
|
+
* Atomically delete **at most one** row in `model` matching `where` and
|
|
35
|
+
* return it (or `undefined` if none matched). Backs better-auth's
|
|
36
|
+
* single-use-token consume (OTP / magic-link / email-verification /
|
|
37
|
+
* password-reset): implementing it natively — one round trip that finds and
|
|
38
|
+
* deletes in a single statement — closes the read-then-delete race the
|
|
39
|
+
* factory's `findMany` + `deleteMany` fallback would otherwise leave open.
|
|
40
|
+
*/
|
|
41
41
|
consumeOne: (model: string, where: ReadonlyArray<AuthWhereClause>) => Promise<AuthRow | undefined>;
|
|
42
42
|
/** Count rows in `model` matching `where` (empty `where` = all rows). */
|
|
43
43
|
count: (model: string, where: ReadonlyArray<AuthWhereClause>) => Promise<number>;
|
|
44
44
|
/** Insert `data` into `model`; return the stored row (the adapter pre-fills `id`). */
|
|
45
45
|
create: (model: string, data: AuthRow) => Promise<AuthRow>;
|
|
46
46
|
/**
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
47
|
+
* Atomically apply signed numeric deltas to **at most one** row in `model`
|
|
48
|
+
* matching `where`, then return the updated row (or `undefined` if the guard
|
|
49
|
+
* matched none). For each `increment` entry it applies `field = field + delta`
|
|
50
|
+
* (a negative delta decrements); the optional `set` map assigns absolute
|
|
51
|
+
* values in the same step. The `where` clause is both selector **and** guard
|
|
52
|
+
* — comparison operators are honoured, so a guard like
|
|
53
|
+
* `{ field: "count", operator: "lt", value: max }` only mutates the row while
|
|
54
|
+
* it still satisfies the predicate.
|
|
55
|
+
*
|
|
56
|
+
* Backs better-auth's durable (`storage: "database"`) rate limiter, whose
|
|
57
|
+
* counter rides these tables. Implementing it natively — one statement that
|
|
58
|
+
* guards, increments, and returns — gives the **one-winner-across-isolates**
|
|
59
|
+
* guarantee the read-then-update fallback cannot: on Workers two concurrent
|
|
60
|
+
* requests would otherwise both read `count=4` and both write `5`, letting a
|
|
61
|
+
* `max` of 5 pass 6+. Same race-closing rationale as {@link AuthStore.consumeOne}.
|
|
62
|
+
*/
|
|
63
63
|
incrementOne: (model: string, where: ReadonlyArray<AuthWhereClause>, increment: Record<string, number>, set?: AuthRow) => Promise<AuthRow | undefined>;
|
|
64
64
|
/** Read rows from `model` honouring the filter/sort/window in `query`. */
|
|
65
65
|
read: (model: string, query: AuthQuery) => Promise<AuthRow[]>;
|
|
@@ -69,16 +69,34 @@ interface AuthStore {
|
|
|
69
69
|
update: (model: string, where: ReadonlyArray<AuthWhereClause>, values: AuthRow) => Promise<AuthRow[]>;
|
|
70
70
|
}
|
|
71
71
|
/**
|
|
72
|
-
* Evaluate a better-auth where clause list against a row.
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
|
|
72
|
+
* Evaluate a better-auth where clause list against a row.
|
|
73
|
+
*
|
|
74
|
+
* better-auth hands an adapter a FLAT list in which each clause carries its own
|
|
75
|
+
* `connector` (`AND` by default). Every persistent adapter it ships resolves that
|
|
76
|
+
* by PARTITIONING: `AND(and-clauses) AND OR(or-clauses)`. The OR clauses are
|
|
77
|
+
* alternatives among themselves, never an escape hatch from the AND clauses —
|
|
78
|
+
* `@better-auth/kysely-adapter` pushes each group into its own `.where()` (two
|
|
79
|
+
* `.where()` calls are ANDed), `@better-auth/drizzle-adapter` ends in
|
|
80
|
+
* `and(andClause, orClause)`, and `@better-auth/prisma-adapter` emits
|
|
81
|
+
* `{ AND: […], OR: […] }`, which Prisma also ANDs.
|
|
82
|
+
*
|
|
83
|
+
* This used to fold the list left-associatively instead, so `[A, B(OR), C(OR)]`
|
|
84
|
+
* meant `A OR B OR C` — strictly BROADER than any of them. On a credential lookup
|
|
85
|
+
* that is an authentication bypass in shape: a row failing the primary condition
|
|
86
|
+
* is still returned because a secondary one matched. `@better-auth/memory-adapter`
|
|
87
|
+
* does fold left, but it is the only one and it re-evaluates `where[0]` inside the
|
|
88
|
+
* same loop; the persistent adapters are the contract worth mirroring, and they
|
|
89
|
+
* are also what a plugin author will have tested against.
|
|
90
|
+
*
|
|
91
|
+
* An empty list matches every row, and a list with no OR clause is unaffected —
|
|
92
|
+
* which is every clause list better-auth 1.7.1 itself builds. Exported so any
|
|
93
|
+
* in-memory-style {@link AuthStore} can reuse it.
|
|
94
|
+
*/
|
|
77
95
|
declare const matchesWhere: (row: AuthRow, where: ReadonlyArray<AuthWhereClause>) => boolean;
|
|
78
96
|
/**
|
|
79
|
-
* Reference in-memory {@link AuthStore} — used to run better-auth end to end in
|
|
80
|
-
* tests, and a worked example of the contract a Lunora-`ctx.db`-backed store
|
|
81
|
-
* fulfils. Not for production (state is per-instance and non-durable).
|
|
82
|
-
*/
|
|
97
|
+
* Reference in-memory {@link AuthStore} — used to run better-auth end to end in
|
|
98
|
+
* tests, and a worked example of the contract a Lunora-`ctx.db`-backed store
|
|
99
|
+
* fulfils. Not for production (state is per-instance and non-durable).
|
|
100
|
+
*/
|
|
83
101
|
declare const createMemoryAuthStore: () => AuthStore;
|
|
84
102
|
export { AuthQuery, type AuthRow, AuthStore, type AuthWhereClause, createMemoryAuthStore, matchesWhere };
|