@lunora/auth 1.0.0-alpha.2 → 1.0.0-alpha.21
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 +6 -0
- package/__assets__/package-og.svg +1 -1
- package/dist/adapter.mjs +1 -0
- package/dist/index.d.mts +199 -7
- package/dist/index.d.ts +199 -7
- package/dist/index.mjs +4 -4
- package/dist/middleware.d.mts +3 -2
- package/dist/middleware.d.ts +3 -2
- package/dist/middleware.mjs +6 -3
- package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +510 -0
- package/dist/packem_shared/{compileMigrationsSql-wZH3oXDu.mjs → compileMigrationsSql-B9bj-mJv.mjs} +2 -1
- package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +128 -0
- package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +128 -0
- package/dist/packem_shared/{createAuth-B-tvsvQU.mjs → createAuth-BVMMllTm.mjs} +39 -8
- package/dist/packem_shared/{sessionPresets-B95rXrd8.mjs → sessionPresets-Dwwd74_J.mjs} +3 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.d.ts +1 -1
- package/dist/sql-store.mjs +22 -0
- package/dist/store.d.mts +18 -0
- package/dist/store.d.ts +18 -0
- package/dist/store.mjs +13 -0
- package/package.json +7 -6
- package/dist/packem_shared/LunoraAuthAdminError-BxrfEeA_.mjs +0 -249
- package/dist/packem_shared/create-auth.d-M36jwG_Y.d.mts +0 -58
- package/dist/packem_shared/create-auth.d-M36jwG_Y.d.ts +0 -58
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { betterAuth, BetterAuthOptions } from 'better-auth';
|
|
2
|
+
/**
|
|
3
|
+
* Lunora's options pass straight through to better-auth — the only thing we add
|
|
4
|
+
* is requiring `secret` up front so a misconfigured deployment fails loudly
|
|
5
|
+
* instead of at the first sign-in.
|
|
6
|
+
*
|
|
7
|
+
* For `database`, prefer `lunoraD1Adapter` (`database: lunoraD1Adapter(env.DB)`)
|
|
8
|
+
* over passing the raw `env.DB`. better-auth *does* accept a D1Database directly,
|
|
9
|
+
* but it then resolves its Kysely adapter via a runtime `await import(...)` inside
|
|
10
|
+
* `auth.$context` — and that import never settles under `@cloudflare/vite-plugin`'s
|
|
11
|
+
* worker runner, hanging every auth request in `pnpm dev`. The explicit adapter
|
|
12
|
+
* skips it, so dev and prod behave the same. (Raw `env.DB` is still correct for
|
|
13
|
+
* the migration-only instance — see `lunoraD1Adapter`'s note.)
|
|
14
|
+
*
|
|
15
|
+
* Session rotation / richer session policies are configured via the `session`
|
|
16
|
+
* field (a `SessionPolicy`); Lunora validates it for obviously-broken
|
|
17
|
+
* durations and forwards it verbatim to better-auth. See `sessionPresets`
|
|
18
|
+
* for ready-made rotation/expiry trade-offs.
|
|
19
|
+
*
|
|
20
|
+
* ## Serverless background tasks (Cloudflare Workers)
|
|
21
|
+
*
|
|
22
|
+
* better-auth runs some work *after* sending the response — most importantly the
|
|
23
|
+
* password-reset email, whose background send is what keeps reset responses
|
|
24
|
+
* constant-time (a timing-attack defence: the response doesn't reveal whether
|
|
25
|
+
* the account exists). On Cloudflare Workers a promise that isn't handed to
|
|
26
|
+
* `ctx.waitUntil` can be cancelled the moment the response returns, dropping
|
|
27
|
+
* that send and weakening the guarantee. Wire your request's `ctx.waitUntil`
|
|
28
|
+
* into better-auth's background handler so the work survives:
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* // in your worker fetch handler, where `ctx: ExecutionContext` is in scope
|
|
32
|
+
* const auth = createAuth({
|
|
33
|
+
* secret: env.AUTH_SECRET,
|
|
34
|
+
* database: lunoraD1Adapter(env.DB),
|
|
35
|
+
* advanced: {
|
|
36
|
+
* backgroundTasks: { handler: (promise) => ctx.waitUntil(promise) },
|
|
37
|
+
* },
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* (Lunora can't set this for you — `ctx.waitUntil` is per-request, but
|
|
42
|
+
* `createAuth` runs once at worker setup.)
|
|
43
|
+
*/
|
|
44
|
+
type LunoraAuthOptions = BetterAuthOptions;
|
|
45
|
+
/**
|
|
46
|
+
* The full better-auth instance: `auth.handler` accepts a `Request` and
|
|
47
|
+
* returns a `Response` (used by `handleAuthRequest`); `auth.api`
|
|
48
|
+
* exposes the typed endpoint surface for server-side calls (e.g.
|
|
49
|
+
* `auth.api.getSession({ headers })` inside a query/mutation).
|
|
50
|
+
*/
|
|
51
|
+
type LunoraAuth = ReturnType<typeof betterAuth>;
|
|
52
|
+
/**
|
|
53
|
+
* Resolve the caller's options into the exact shape `createAuth` hands to
|
|
54
|
+
* `betterAuth` — the hardened, default-filled options the running worker uses.
|
|
55
|
+
* Exported (and pure) so the migration path can compile the schema from the
|
|
56
|
+
* same resolved options: `compileMigrationsSql` routes through here, so the
|
|
57
|
+
* `rateLimit` table the worker's durable limiter writes to is included in the
|
|
58
|
+
* migration rather than silently omitted (it would be, if migrations saw the
|
|
59
|
+
* raw options while the worker ran the resolved ones).
|
|
60
|
+
*
|
|
61
|
+
* ## What it fills (each gated independently on caller silence)
|
|
62
|
+
*
|
|
63
|
+
* Secure-by-default cookies + secret-strength warning via {@link hardenAuthOptions},
|
|
64
|
+
* applied first so all hardening composes onto one options object.
|
|
65
|
+
*
|
|
66
|
+
* Rate limiting is ON by default for `/api/auth/*`.
|
|
67
|
+
*
|
|
68
|
+
* better-auth's own default is `rateLimit.enabled ?? isProduction`, and its
|
|
69
|
+
* `isProduction` is `"development" === "production"` resolved at
|
|
70
|
+
* module-load time. On Cloudflare Workers that check is unreliable: the
|
|
71
|
+
* runtime has no Node `process.env` (absent entirely without
|
|
72
|
+
* `nodejs_compat`, and even with it `NODE_ENV` is rarely `"production"` at
|
|
73
|
+
* request time). So better-auth would silently leave auth endpoints
|
|
74
|
+
* _unthrottled_ on a real deployment — the surprise we refuse to ship.
|
|
75
|
+
*
|
|
76
|
+
* We therefore default `enabled: true` whenever the caller hasn't made an
|
|
77
|
+
* explicit choice. We only fill the `enabled` flag and otherwise forward
|
|
78
|
+
* the caller's `rateLimit` verbatim, so better-auth's `window` (10s) / `max`
|
|
79
|
+
* (100) defaults and any custom rules still apply. Callers who genuinely
|
|
80
|
+
* want it off can pass `rateLimit: { enabled: false }` (e.g. when fronting
|
|
81
|
+
* auth with their own limiter), and any explicit `enabled` value wins.
|
|
82
|
+
*
|
|
83
|
+
* We also default `storage: "database"` — but only when rate limiting is not
|
|
84
|
+
* explicitly disabled (`enabled !== false`). Filling storage under a disabled
|
|
85
|
+
* limiter is harmless at runtime but makes `getAuthTables` emit an unused
|
|
86
|
+
* `rateLimit` table, so we skip it there.
|
|
87
|
+
*
|
|
88
|
+
* better-auth's own default is `storage: "memory"` — a per-isolate,
|
|
89
|
+
* non-durable counter. On Cloudflare Workers that means each isolate keeps
|
|
90
|
+
* its own tally, counters vanish on isolate recycle, and traffic spread
|
|
91
|
+
* across isolates never sums to the configured `max` — a limiter that
|
|
92
|
+
* reports "enabled" while never enforcing a global limit (the exact
|
|
93
|
+
* brute-force / credential-stuffing protection on `/sign-in`, OTP, and
|
|
94
|
+
* password-reset it is meant to buy). `storage: "database"` rides the counter
|
|
95
|
+
* through the configured `database` adapter — Lunora's store over the D1 auth
|
|
96
|
+
* tables — so the limit is durable *and* atomic (the store's native
|
|
97
|
+
* `incrementOne` gives a one-winner guarantee across isolates). Callers with
|
|
98
|
+
* their own durable store can pass an explicit `rateLimit: { storage: … }`
|
|
99
|
+
* (or `customStorage`), and any explicit value wins.
|
|
100
|
+
*
|
|
101
|
+
* Session cookie cache is ON by default too.
|
|
102
|
+
*
|
|
103
|
+
* Every authenticated call resolves identity through better-auth's
|
|
104
|
+
* `getSession`, which — without a cache — is a DB (D1) read on the hot path
|
|
105
|
+
* of every query/mutation/action that reads `ctx.auth` and of the WebSocket
|
|
106
|
+
* upgrade. better-auth's `session.cookieCache` carries the session payload in
|
|
107
|
+
* a short-lived signed cookie so `getSession` can answer without hitting the
|
|
108
|
+
* database until the cache window elapses. We default it on with a
|
|
109
|
+
* deliberately short 60s `maxAge` (better-auth's own default is 300s): long
|
|
110
|
+
* enough to erase the per-request read for a burst of calls, short enough
|
|
111
|
+
* that a revoked or role-changed session self-corrects within a minute.
|
|
112
|
+
* The one tradeoff — a revoked session stays valid until the cache expires —
|
|
113
|
+
* is bounded by that TTL; callers who need immediate revocation opt out with
|
|
114
|
+
* `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
|
|
115
|
+
*
|
|
116
|
+
* Every explicit caller value is forwarded verbatim. The two `rateLimit` fills
|
|
117
|
+
* merge into a single `rateLimit` object so neither clobbers the other.
|
|
118
|
+
*/
|
|
119
|
+
declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
|
|
120
|
+
/**
|
|
121
|
+
* Create the auth instance. Thin wrapper around `betterAuth` that enforces
|
|
122
|
+
* the `secret` requirement at construction time so misconfigured deployments
|
|
123
|
+
* fail loudly at the first fetch rather than the first sign-in attempt, then
|
|
124
|
+
* hands {@link resolveAuthOptions}'s hardened, default-filled options to
|
|
125
|
+
* better-auth.
|
|
126
|
+
*/
|
|
127
|
+
declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
|
|
128
|
+
export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { LunoraError } from '@lunora/errors';
|
|
1
2
|
import { betterAuth } from 'better-auth';
|
|
2
|
-
import { validateSessionPolicy } from './sessionPresets-
|
|
3
|
+
import { validateSessionPolicy } from './sessionPresets-Dwwd74_J.mjs';
|
|
3
4
|
|
|
4
5
|
const MIN_SECRET_LENGTH = 32;
|
|
5
6
|
const isWeakSecret = (secret) => {
|
|
@@ -21,11 +22,26 @@ const isHttpsBaseUrl = (baseURL) => {
|
|
|
21
22
|
}
|
|
22
23
|
return false;
|
|
23
24
|
};
|
|
25
|
+
const isExplicitHttpBaseUrl = (baseURL) => {
|
|
26
|
+
if (typeof baseURL === "string") {
|
|
27
|
+
return baseURL.toLowerCase().startsWith("http://");
|
|
28
|
+
}
|
|
29
|
+
if (baseURL && typeof baseURL === "object") {
|
|
30
|
+
if (baseURL.protocol === "http") {
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
if (baseURL.protocol === "https") {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
return typeof baseURL.fallback === "string" && baseURL.fallback.toLowerCase().startsWith("http://");
|
|
37
|
+
}
|
|
38
|
+
return false;
|
|
39
|
+
};
|
|
24
40
|
const hardenAuthOptions = (options) => {
|
|
25
41
|
if (isWeakSecret(options.secret)) {
|
|
26
42
|
const message = `@lunora/auth: AUTH_SECRET is only ${String(options.secret?.trim().length)} characters. Use at least ${String(MIN_SECRET_LENGTH)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;
|
|
27
43
|
if (isHttpsBaseUrl(options.baseURL)) {
|
|
28
|
-
throw new
|
|
44
|
+
throw new LunoraError("INTERNAL", message);
|
|
29
45
|
}
|
|
30
46
|
console.warn(message);
|
|
31
47
|
}
|
|
@@ -35,22 +51,37 @@ const hardenAuthOptions = (options) => {
|
|
|
35
51
|
advanced: {
|
|
36
52
|
...advanced,
|
|
37
53
|
defaultCookieAttributes: advanced.defaultCookieAttributes ?? { httpOnly: true, path: "/", sameSite: "lax" },
|
|
38
|
-
...advanced.useSecureCookies === void 0
|
|
54
|
+
...advanced.useSecureCookies === void 0 ? { useSecureCookies: !isExplicitHttpBaseUrl(options.baseURL) } : {}
|
|
39
55
|
}
|
|
40
56
|
};
|
|
41
57
|
};
|
|
58
|
+
const resolveAuthOptions = (options) => {
|
|
59
|
+
const hardened = hardenAuthOptions(options);
|
|
60
|
+
const needsRateLimitEnabled = hardened.rateLimit?.enabled === void 0;
|
|
61
|
+
const needsRateLimitStorage = hardened.rateLimit?.storage === void 0 && hardened.rateLimit?.enabled !== false;
|
|
62
|
+
return {
|
|
63
|
+
...hardened,
|
|
64
|
+
...needsRateLimitEnabled || needsRateLimitStorage ? {
|
|
65
|
+
rateLimit: {
|
|
66
|
+
...hardened.rateLimit,
|
|
67
|
+
...needsRateLimitEnabled ? { enabled: true } : {},
|
|
68
|
+
...needsRateLimitStorage ? { storage: "database" } : {}
|
|
69
|
+
}
|
|
70
|
+
} : {},
|
|
71
|
+
...hardened.session?.cookieCache === void 0 ? { session: { ...hardened.session, cookieCache: { enabled: true, maxAge: 60 } } } : {}
|
|
72
|
+
};
|
|
73
|
+
};
|
|
42
74
|
const createAuth = (options) => {
|
|
43
75
|
if (!options.secret || options.secret.trim() === "") {
|
|
44
|
-
throw new
|
|
76
|
+
throw new LunoraError(
|
|
77
|
+
"INTERNAL",
|
|
45
78
|
'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.'
|
|
46
79
|
);
|
|
47
80
|
}
|
|
48
81
|
if (options.session) {
|
|
49
82
|
validateSessionPolicy(options.session);
|
|
50
83
|
}
|
|
51
|
-
|
|
52
|
-
const resolvedOptions = hardened.rateLimit?.enabled === void 0 ? { ...hardened, rateLimit: { ...hardened.rateLimit, enabled: true } } : hardened;
|
|
53
|
-
return betterAuth(resolvedOptions);
|
|
84
|
+
return betterAuth(resolveAuthOptions(options));
|
|
54
85
|
};
|
|
55
86
|
|
|
56
|
-
export { createAuth };
|
|
87
|
+
export { createAuth, resolveAuthOptions };
|
|
@@ -16,16 +16,19 @@ const validateSessionPolicy = (policy) => {
|
|
|
16
16
|
};
|
|
17
17
|
const sessionPresets = {
|
|
18
18
|
longLived: {
|
|
19
|
+
cookieCache: { enabled: true, maxAge: 60 },
|
|
19
20
|
expiresIn: 30 * DAY,
|
|
20
21
|
freshAge: DAY,
|
|
21
22
|
updateAge: DAY
|
|
22
23
|
},
|
|
23
24
|
rolling: {
|
|
25
|
+
cookieCache: { enabled: true, maxAge: 60 },
|
|
24
26
|
expiresIn: 7 * DAY,
|
|
25
27
|
freshAge: DAY,
|
|
26
28
|
updateAge: DAY
|
|
27
29
|
},
|
|
28
30
|
strict: {
|
|
31
|
+
cookieCache: { enabled: false },
|
|
29
32
|
expiresIn: HOUR,
|
|
30
33
|
freshAge: 5 * MINUTE,
|
|
31
34
|
updateAge: 15 * MINUTE
|
package/dist/schema.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TableDefinition } from '@lunora/server';
|
|
2
|
-
import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-
|
|
2
|
+
import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-Mwhb4gSc.mjs";
|
|
3
3
|
import 'better-auth';
|
|
4
4
|
/**
|
|
5
5
|
* Derive Lunora table definitions from a better-auth config — the bridge that
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TableDefinition } from '@lunora/server';
|
|
2
|
-
import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-
|
|
2
|
+
import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-Mwhb4gSc.js";
|
|
3
3
|
import 'better-auth';
|
|
4
4
|
/**
|
|
5
5
|
* Derive Lunora table definitions from a better-auth config — the bridge that
|
package/dist/sql-store.mjs
CHANGED
|
@@ -111,6 +111,28 @@ const createSqlAuthStore = (executor) => {
|
|
|
111
111
|
);
|
|
112
112
|
return { ...data };
|
|
113
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
|
+
},
|
|
114
136
|
read: async (model, query) => {
|
|
115
137
|
const fragment = compileWhere(query.where);
|
|
116
138
|
const parameters = [...fragment.params];
|
package/dist/store.d.mts
CHANGED
|
@@ -43,6 +43,24 @@ interface AuthStore {
|
|
|
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
|
+
/**
|
|
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
|
+
incrementOne: (model: string, where: ReadonlyArray<AuthWhereClause>, increment: Record<string, number>, set?: AuthRow) => Promise<AuthRow | undefined>;
|
|
46
64
|
/** Read rows from `model` honouring the filter/sort/window in `query`. */
|
|
47
65
|
read: (model: string, query: AuthQuery) => Promise<AuthRow[]>;
|
|
48
66
|
/** Delete rows in `model` matching `where`; return how many were removed. */
|
package/dist/store.d.ts
CHANGED
|
@@ -43,6 +43,24 @@ interface AuthStore {
|
|
|
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
|
+
/**
|
|
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
|
+
incrementOne: (model: string, where: ReadonlyArray<AuthWhereClause>, increment: Record<string, number>, set?: AuthRow) => Promise<AuthRow | undefined>;
|
|
46
64
|
/** Read rows from `model` honouring the filter/sort/window in `query`. */
|
|
47
65
|
read: (model: string, query: AuthQuery) => Promise<AuthRow[]>;
|
|
48
66
|
/** Delete rows in `model` matching `where`; return how many were removed. */
|
package/dist/store.mjs
CHANGED
|
@@ -128,6 +128,19 @@ const createMemoryAuthStore = () => {
|
|
|
128
128
|
tableOf(model).push(row);
|
|
129
129
|
return Promise.resolve({ ...row });
|
|
130
130
|
},
|
|
131
|
+
incrementOne: (model, where, increment, set) => {
|
|
132
|
+
const row = tableOf(model).find((candidate) => matchesWhere(candidate, where));
|
|
133
|
+
if (!row) {
|
|
134
|
+
return Promise.resolve(void 0);
|
|
135
|
+
}
|
|
136
|
+
for (const [field, delta] of Object.entries(increment)) {
|
|
137
|
+
row[field] = (typeof row[field] === "number" ? row[field] : 0) + delta;
|
|
138
|
+
}
|
|
139
|
+
if (set) {
|
|
140
|
+
Object.assign(row, set);
|
|
141
|
+
}
|
|
142
|
+
return Promise.resolve({ ...row });
|
|
143
|
+
},
|
|
131
144
|
read: (model, query) => {
|
|
132
145
|
let rows = tableOf(model).filter((row) => matchesWhere(row, query.where));
|
|
133
146
|
if (query.sortBy) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/auth",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.21",
|
|
4
4
|
"description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"auth",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"directory": "packages/auth"
|
|
26
26
|
},
|
|
27
27
|
"files": [
|
|
28
|
-
"dist",
|
|
28
|
+
"./dist",
|
|
29
29
|
"__assets__",
|
|
30
30
|
"README.md",
|
|
31
31
|
"LICENSE.md"
|
|
@@ -82,10 +82,11 @@
|
|
|
82
82
|
"access": "public"
|
|
83
83
|
},
|
|
84
84
|
"dependencies": {
|
|
85
|
-
"@better-auth/passkey": "^1.6.
|
|
86
|
-
"@lunora/
|
|
87
|
-
"@lunora/
|
|
88
|
-
"
|
|
85
|
+
"@better-auth/passkey": "^1.6.23",
|
|
86
|
+
"@lunora/errors": "1.0.0-alpha.1",
|
|
87
|
+
"@lunora/server": "1.0.0-alpha.16",
|
|
88
|
+
"@lunora/values": "1.0.0-alpha.4",
|
|
89
|
+
"better-auth": "^1.6.23"
|
|
89
90
|
},
|
|
90
91
|
"engines": {
|
|
91
92
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
class LunoraAuthAdminError extends Error {
|
|
2
|
-
code;
|
|
3
|
-
constructor(message, code) {
|
|
4
|
-
super(message);
|
|
5
|
-
this.name = "LunoraAuthAdminError";
|
|
6
|
-
this.code = code;
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
const DEFAULT_LIMIT = 50;
|
|
10
|
-
const MAX_LIMIT = 500;
|
|
11
|
-
const DEFAULT_IMPERSONATION_SECONDS = 3600;
|
|
12
|
-
const MAX_IMPERSONATION_SECONDS = DEFAULT_IMPERSONATION_SECONDS * 24;
|
|
13
|
-
const MAX_BAN_SECONDS = 100 * 365 * 24 * 60 * 60;
|
|
14
|
-
const SENSITIVE_FIELDS = /* @__PURE__ */ new Set(["accessToken", "backupCodes", "idToken", "password", "publicKey", "refreshToken", "secret", "token"]);
|
|
15
|
-
const clampLimit = (limit) => Math.min(Math.max(Math.trunc(limit ?? DEFAULT_LIMIT), 1), MAX_LIMIT);
|
|
16
|
-
const clampOffset = (offset) => Math.max(0, Math.trunc(offset ?? 0));
|
|
17
|
-
const normalizeRow = (row) => {
|
|
18
|
-
const out = {};
|
|
19
|
-
for (const [key, value] of Object.entries(row)) {
|
|
20
|
-
if (SENSITIVE_FIELDS.has(key)) {
|
|
21
|
-
continue;
|
|
22
|
-
}
|
|
23
|
-
out[key] = value instanceof Date ? value.getTime() : value;
|
|
24
|
-
}
|
|
25
|
-
return out;
|
|
26
|
-
};
|
|
27
|
-
const serializeRole = (role) => Array.isArray(role) ? role.join(",") : role;
|
|
28
|
-
const asAdminError = (error) => {
|
|
29
|
-
if (error instanceof LunoraAuthAdminError) {
|
|
30
|
-
return error;
|
|
31
|
-
}
|
|
32
|
-
const candidate = error;
|
|
33
|
-
const code = candidate?.body?.code ?? candidate?.code ?? "AUTH_ADMIN_ERROR";
|
|
34
|
-
const message = candidate?.body?.message ?? candidate?.message ?? "auth admin operation failed";
|
|
35
|
-
return new LunoraAuthAdminError(message, code);
|
|
36
|
-
};
|
|
37
|
-
const createAuthAdmin = (auth, options = {}) => {
|
|
38
|
-
const context = auth.$context;
|
|
39
|
-
const features = options.features ?? {};
|
|
40
|
-
const withContext = async (function_) => {
|
|
41
|
-
try {
|
|
42
|
-
return await function_(await context);
|
|
43
|
-
} catch (error) {
|
|
44
|
-
throw asAdminError(error);
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
const toUser = (row) => normalizeRow(row);
|
|
48
|
-
const page = async (context_, model, options_) => {
|
|
49
|
-
const where = options_.where && options_.where.length > 0 ? options_.where : void 0;
|
|
50
|
-
const [rows, total] = await Promise.all([
|
|
51
|
-
context_.adapter.findMany({
|
|
52
|
-
limit: clampLimit(options_.limit),
|
|
53
|
-
model,
|
|
54
|
-
offset: clampOffset(options_.offset),
|
|
55
|
-
sortBy: options_.sortBy,
|
|
56
|
-
where
|
|
57
|
-
}),
|
|
58
|
-
context_.adapter.count({ model, where })
|
|
59
|
-
]);
|
|
60
|
-
return { rows: rows.map((row) => normalizeRow(row)), total };
|
|
61
|
-
};
|
|
62
|
-
return {
|
|
63
|
-
banUser: ({ expiresInSeconds, reason, userId }) => withContext(async (context_) => {
|
|
64
|
-
const seconds = typeof expiresInSeconds === "number" && Number.isFinite(expiresInSeconds) ? Math.min(Math.trunc(expiresInSeconds), MAX_BAN_SECONDS) : 0;
|
|
65
|
-
const banExpires = seconds > 0 ? new Date(Date.now() + seconds * 1e3) : void 0;
|
|
66
|
-
const user = await context_.internalAdapter.updateUser(userId, {
|
|
67
|
-
banExpires,
|
|
68
|
-
banned: true,
|
|
69
|
-
banReason: reason ?? "No reason"
|
|
70
|
-
});
|
|
71
|
-
await context_.internalAdapter.deleteUserSessions(userId);
|
|
72
|
-
return toUser(user);
|
|
73
|
-
}),
|
|
74
|
-
cancelInvitation: ({ invitationId }) => withContext(async (context_) => {
|
|
75
|
-
await context_.adapter.delete({ model: "invitation", where: [{ field: "id", value: invitationId }] });
|
|
76
|
-
}),
|
|
77
|
-
capabilities: () => withContext((context_) => {
|
|
78
|
-
const ids = new Set((context_.options.plugins ?? []).map((plugin) => plugin.id));
|
|
79
|
-
const has = (id) => ids.has(id);
|
|
80
|
-
return Promise.resolve({
|
|
81
|
-
accounts: features.accounts ?? true,
|
|
82
|
-
admin: features.admin ?? has("admin"),
|
|
83
|
-
organization: features.organization ?? has("organization"),
|
|
84
|
-
passkey: features.passkey ?? has("passkey"),
|
|
85
|
-
twoFactor: features.twoFactor ?? has("two-factor")
|
|
86
|
-
});
|
|
87
|
-
}),
|
|
88
|
-
// The one op that genuinely builds a row rather than mutating one. Replicates
|
|
89
|
-
// the plugin's create-user handler over `internalAdapter` (lowercase + dedupe
|
|
90
|
-
// email, create the row, then link a credential account when a password is given).
|
|
91
|
-
createUser: ({ data, email, name, password, role }) => withContext(async (context_) => {
|
|
92
|
-
const normalizedEmail = email.toLowerCase();
|
|
93
|
-
if (await context_.internalAdapter.findUserByEmail(normalizedEmail)) {
|
|
94
|
-
throw new LunoraAuthAdminError("a user with this email already exists", "USER_ALREADY_EXISTS");
|
|
95
|
-
}
|
|
96
|
-
const user = await context_.internalAdapter.createUser({
|
|
97
|
-
email: normalizedEmail,
|
|
98
|
-
name,
|
|
99
|
-
role: role === void 0 ? void 0 : serializeRole(role),
|
|
100
|
-
...data
|
|
101
|
-
});
|
|
102
|
-
if (password !== void 0 && password !== "") {
|
|
103
|
-
const hashed = await context_.password.hash(password);
|
|
104
|
-
await context_.internalAdapter.linkAccount({
|
|
105
|
-
accountId: user.id,
|
|
106
|
-
password: hashed,
|
|
107
|
-
providerId: "credential",
|
|
108
|
-
userId: user.id
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
return toUser(user);
|
|
112
|
-
}),
|
|
113
|
-
deletePasskey: ({ passkeyId }) => withContext(async (context_) => {
|
|
114
|
-
await context_.adapter.delete({ model: "passkey", where: [{ field: "id", value: passkeyId }] });
|
|
115
|
-
}),
|
|
116
|
-
disableTwoFactor: ({ userId }) => withContext(async (context_) => {
|
|
117
|
-
await context_.adapter.deleteMany({ model: "twoFactor", where: [{ field: "userId", value: userId }] });
|
|
118
|
-
await context_.internalAdapter.updateUser(userId, { twoFactorEnabled: false });
|
|
119
|
-
}),
|
|
120
|
-
impersonateUser: ({ userId }) => withContext(async (context_) => {
|
|
121
|
-
const user = await context_.internalAdapter.findUserById(userId);
|
|
122
|
-
if (!user) {
|
|
123
|
-
throw new LunoraAuthAdminError("user not found", "USER_NOT_FOUND");
|
|
124
|
-
}
|
|
125
|
-
const rawSeconds = options.impersonationSeconds;
|
|
126
|
-
let ttlSeconds = DEFAULT_IMPERSONATION_SECONDS;
|
|
127
|
-
if (rawSeconds !== void 0) {
|
|
128
|
-
if (!Number.isInteger(rawSeconds) || !Number.isFinite(rawSeconds) || rawSeconds <= 0) {
|
|
129
|
-
throw new LunoraAuthAdminError("impersonationSeconds must be a positive finite integer", "INVALID_IMPERSONATION_SECONDS");
|
|
130
|
-
}
|
|
131
|
-
ttlSeconds = Math.min(rawSeconds, MAX_IMPERSONATION_SECONDS);
|
|
132
|
-
}
|
|
133
|
-
const expiresAt = new Date(Date.now() + ttlSeconds * 1e3);
|
|
134
|
-
const session = await context_.internalAdapter.createSession(
|
|
135
|
-
userId,
|
|
136
|
-
true,
|
|
137
|
-
{ expiresAt, impersonatedBy: options.impersonatedBy ?? userId },
|
|
138
|
-
true
|
|
139
|
-
);
|
|
140
|
-
return {
|
|
141
|
-
expiresAt: session.expiresAt instanceof Date ? session.expiresAt.getTime() : expiresAt.getTime(),
|
|
142
|
-
token: session.token,
|
|
143
|
-
user: toUser(user)
|
|
144
|
-
};
|
|
145
|
-
}),
|
|
146
|
-
listAccounts: ({ userId }) => withContext(async (context_) => {
|
|
147
|
-
const rows = await context_.adapter.findMany({ model: "account", where: [{ field: "userId", value: userId }] });
|
|
148
|
-
return rows.map((row) => normalizeRow(row));
|
|
149
|
-
}),
|
|
150
|
-
listInvitations: ({ limit, offset, organizationId }) => withContext(
|
|
151
|
-
(context_) => page(context_, "invitation", {
|
|
152
|
-
limit,
|
|
153
|
-
offset,
|
|
154
|
-
where: [{ field: "organizationId", value: organizationId }]
|
|
155
|
-
})
|
|
156
|
-
),
|
|
157
|
-
listMembers: ({ limit, offset, organizationId }) => withContext(
|
|
158
|
-
(context_) => page(context_, "member", {
|
|
159
|
-
limit,
|
|
160
|
-
offset,
|
|
161
|
-
sortBy: { direction: "desc", field: "createdAt" },
|
|
162
|
-
where: [{ field: "organizationId", value: organizationId }]
|
|
163
|
-
})
|
|
164
|
-
),
|
|
165
|
-
listOrganizations: ({ limit, offset }) => withContext((context_) => page(context_, "organization", { limit, offset, sortBy: { direction: "desc", field: "createdAt" } })),
|
|
166
|
-
listPasskeys: ({ userId }) => withContext(async (context_) => {
|
|
167
|
-
const rows = await context_.adapter.findMany({ model: "passkey", where: [{ field: "userId", value: userId }] });
|
|
168
|
-
return rows.map((row) => normalizeRow(row));
|
|
169
|
-
}),
|
|
170
|
-
listSessions: ({ limit, offset, userId }) => withContext(
|
|
171
|
-
(context_) => page(context_, "session", {
|
|
172
|
-
limit,
|
|
173
|
-
offset,
|
|
174
|
-
sortBy: { direction: "desc", field: "createdAt" },
|
|
175
|
-
where: userId === void 0 || userId === "" ? void 0 : [{ field: "userId", value: userId }]
|
|
176
|
-
})
|
|
177
|
-
),
|
|
178
|
-
listUsers: ({ filterField, filterValue, limit, offset, search, searchField, sortBy, sortDirection }) => withContext((context_) => {
|
|
179
|
-
const where = [];
|
|
180
|
-
if (search !== void 0 && search !== "") {
|
|
181
|
-
where.push({ field: searchField ?? "email", operator: "contains", value: search });
|
|
182
|
-
}
|
|
183
|
-
if (filterValue !== void 0) {
|
|
184
|
-
where.push({ field: filterField ?? "email", operator: "eq", value: filterValue });
|
|
185
|
-
}
|
|
186
|
-
return page(context_, "user", {
|
|
187
|
-
limit,
|
|
188
|
-
offset,
|
|
189
|
-
sortBy: { direction: sortDirection ?? "desc", field: sortBy ?? "createdAt" },
|
|
190
|
-
where
|
|
191
|
-
});
|
|
192
|
-
}),
|
|
193
|
-
removeMember: ({ memberId }) => withContext(async (context_) => {
|
|
194
|
-
await context_.adapter.delete({ model: "member", where: [{ field: "id", value: memberId }] });
|
|
195
|
-
}),
|
|
196
|
-
removeUser: ({ userId }) => withContext(async (context_) => {
|
|
197
|
-
await context_.internalAdapter.deleteUserSessions(userId);
|
|
198
|
-
await context_.internalAdapter.deleteUser(userId);
|
|
199
|
-
}),
|
|
200
|
-
// Keyed on the session *id*, not its token: tokens are bearer credentials we
|
|
201
|
-
// deliberately never surface to the studio. Resolve the row to recover its
|
|
202
|
-
// token, then delete via `internalAdapter.deleteSession` — which also clears
|
|
203
|
-
// secondary (KV) storage, unlike a raw `adapter.delete` on the DB row.
|
|
204
|
-
revokeUserSession: ({ sessionId }) => withContext(async (context_) => {
|
|
205
|
-
const session = await context_.adapter.findOne({ model: "session", where: [{ field: "id", value: sessionId }] });
|
|
206
|
-
if (session?.token) {
|
|
207
|
-
await context_.internalAdapter.deleteSession(session.token);
|
|
208
|
-
}
|
|
209
|
-
}),
|
|
210
|
-
revokeUserSessions: ({ userId }) => withContext(async (context_) => {
|
|
211
|
-
await context_.internalAdapter.deleteUserSessions(userId);
|
|
212
|
-
}),
|
|
213
|
-
setRole: ({ role, userId }) => withContext(async (context_) => {
|
|
214
|
-
const user = await context_.internalAdapter.updateUser(userId, { role: serializeRole(role) });
|
|
215
|
-
return toUser(user);
|
|
216
|
-
}),
|
|
217
|
-
setUserPassword: ({ newPassword, userId }) => withContext(async (context_) => {
|
|
218
|
-
const min = context_.password.config.minPasswordLength;
|
|
219
|
-
const max = context_.password.config.maxPasswordLength;
|
|
220
|
-
if (newPassword.length < min) {
|
|
221
|
-
throw new LunoraAuthAdminError(`password must be at least ${min.toString()} characters`, "PASSWORD_TOO_SHORT");
|
|
222
|
-
}
|
|
223
|
-
if (newPassword.length > max) {
|
|
224
|
-
throw new LunoraAuthAdminError(`password must be at most ${max.toString()} characters`, "PASSWORD_TOO_LONG");
|
|
225
|
-
}
|
|
226
|
-
const hashed = await context_.password.hash(newPassword);
|
|
227
|
-
await context_.internalAdapter.updatePassword(userId, hashed);
|
|
228
|
-
}),
|
|
229
|
-
unbanUser: ({ userId }) => withContext(async (context_) => {
|
|
230
|
-
const user = await context_.internalAdapter.updateUser(userId, { banExpires: null, banned: false, banReason: null });
|
|
231
|
-
return toUser(user);
|
|
232
|
-
}),
|
|
233
|
-
unlinkAccount: ({ accountId, userId }) => withContext(async (context_) => {
|
|
234
|
-
await context_.adapter.delete({
|
|
235
|
-
model: "account",
|
|
236
|
-
where: [
|
|
237
|
-
{ field: "id", value: accountId },
|
|
238
|
-
{ connector: "AND", field: "userId", value: userId }
|
|
239
|
-
]
|
|
240
|
-
});
|
|
241
|
-
}),
|
|
242
|
-
updateUser: ({ data, userId }) => withContext(async (context_) => {
|
|
243
|
-
const user = await context_.internalAdapter.updateUser(userId, data);
|
|
244
|
-
return toUser(user);
|
|
245
|
-
})
|
|
246
|
-
};
|
|
247
|
-
};
|
|
248
|
-
|
|
249
|
-
export { LunoraAuthAdminError, createAuthAdmin };
|