@lunora/auth 1.0.0-alpha.28 → 1.0.0-alpha.281
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 +233 -104
- package/README.md +109 -15
- 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 +177 -0
- package/dist/audit.d.ts +177 -0
- package/dist/audit.mjs +1 -0
- package/dist/cimd-node.d.mts +1 -0
- package/dist/cimd-node.d.ts +1 -0
- package/dist/cimd-node.mjs +1 -0
- package/dist/cimd-workers.d.mts +64 -0
- package/dist/cimd-workers.d.ts +64 -0
- package/dist/cimd-workers.mjs +1 -0
- package/dist/email-guard.d.mts +143 -0
- package/dist/email-guard.d.ts +143 -0
- package/dist/email-guard.mjs +1 -0
- package/dist/index.d.mts +620 -541
- package/dist/index.d.ts +620 -541
- package/dist/index.mjs +1 -12
- package/dist/middleware.d.mts +165 -155
- package/dist/middleware.d.ts +165 -155
- package/dist/middleware.mjs +1 -56
- package/dist/migrate.d.mts +62 -0
- package/dist/migrate.d.ts +62 -0
- package/dist/migrate.mjs +1 -0
- package/dist/packem_shared/AUTH_DO_AUDIT_PATH-CrHU1RMO.mjs +1 -0
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs +1 -0
- package/dist/packem_shared/LunoraAuthAdminError-Cg94b5lr.mjs +1 -0
- package/dist/packem_shared/adapter-L3XvHnkW.mjs +2 -0
- package/dist/packem_shared/adapter.d-BEvPbvSs.d.ts +110 -0
- package/dist/packem_shared/adapter.d-RQVSeO5T.d.mts +110 -0
- package/dist/packem_shared/api-key-storage-D15k9_CF.mjs +1 -0
- package/dist/packem_shared/apiKey-B9uGt5Nc.mjs +1 -0
- package/dist/packem_shared/audit-4B6wftJ8.mjs +12 -0
- package/dist/packem_shared/auth-do-uwp9VIYJ.mjs +1 -0
- package/dist/packem_shared/authAuditBeforeHook-DHiP1Yjf.mjs +1 -0
- package/dist/packem_shared/authBackfillStatus-ZDUCk4U6.mjs +1 -0
- package/dist/packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs +1 -0
- package/dist/packem_shared/authCredentialColumns-EKQdB258.mjs +1 -0
- package/dist/packem_shared/authDiscoveryPaths-BtKCs_3V.mjs +1 -0
- package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
- package/dist/packem_shared/convertAuthDatesOnce-DE_O-bpx.mjs +1 -0
- package/dist/packem_shared/create-auth.d-B8S7aw9O.d.mts +153 -0
- package/dist/packem_shared/create-auth.d-B8S7aw9O.d.ts +153 -0
- package/dist/packem_shared/createAuth-DFkaeVge.mjs +1 -0
- package/dist/packem_shared/createDoAuthWiring-C_ZTB1au.mjs +1 -0
- package/dist/packem_shared/createLunoraAuthClient-wzZk9E0m.mjs +1 -0
- package/dist/packem_shared/createSignUpInvitation-miwkunlA.mjs +1 -0
- package/dist/packem_shared/effectiveCookieCache-JvL6i6YO.mjs +1 -0
- package/dist/packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs +1 -0
- package/dist/packem_shared/handleAuthRequest-Id9Vv_Tk.mjs +1 -0
- package/dist/packem_shared/identity-claims-hAvIl2wm.mjs +1 -0
- package/dist/packem_shared/invitation-email-backfill-DUwurNbV.mjs +1 -0
- package/dist/packem_shared/invite-only.d-CsBPLsY1.d.mts +126 -0
- package/dist/packem_shared/invite-only.d-JdPDmy_a.d.ts +126 -0
- package/dist/packem_shared/isDevEnvironment-yLbPngwn.mjs +1 -0
- package/dist/packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs +1 -0
- package/dist/packem_shared/mcp-CK5XkDFp.mjs +1 -0
- package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
- package/dist/packem_shared/prepareAuthData-CP4M7zk1.mjs +1 -0
- package/dist/packem_shared/provision-DWGVCbQD.mjs +1 -0
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
- package/dist/packem_shared/resolveSessionIdentity-EBhckRBW.mjs +1 -0
- package/dist/packem_shared/sessionPresets-DQQYAOER.mjs +1 -0
- package/dist/packem_shared/sql-store-CFeVqF0V.mjs +1 -0
- package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
- package/dist/packem_shared/worker.d-CDnMrB5s.d.mts +912 -0
- package/dist/packem_shared/worker.d-CVuhZPM3.d.ts +912 -0
- package/dist/plugins-client.d.mts +251 -1
- package/dist/plugins-client.d.ts +251 -1
- package/dist/plugins-client.mjs +1 -2
- package/dist/plugins-enterprise-client.d.mts +13 -0
- package/dist/plugins-enterprise-client.d.ts +13 -0
- package/dist/plugins-enterprise-client.mjs +1 -0
- package/dist/plugins-enterprise.d.mts +1659 -0
- package/dist/plugins-enterprise.d.ts +1659 -0
- package/dist/plugins-enterprise.mjs +1 -0
- package/dist/plugins.d.mts +180 -2
- package/dist/plugins.d.ts +180 -2
- package/dist/plugins.mjs +1 -22
- package/dist/schema.d.mts +47 -39
- package/dist/schema.d.ts +47 -39
- package/dist/schema.mjs +1 -62
- package/dist/sql-store.d.mts +48 -29
- package/dist/sql-store.d.ts +48 -29
- 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 +73 -55
- package/dist/turnstile-middleware.d.ts +73 -55
- package/dist/turnstile-middleware.mjs +1 -34
- package/dist/turnstile.d.mts +42 -49
- package/dist/turnstile.d.ts +42 -49
- package/dist/turnstile.mjs +1 -54
- package/dist/worker.d.mts +9 -0
- package/dist/worker.d.ts +9 -0
- package/dist/worker.mjs +1 -0
- package/package.json +58 -7
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
- package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
- package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.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-BVMMllTm.mjs +0 -87
- package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
|
@@ -0,0 +1,153 @@
|
|
|
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
|
+
* `databaseHooks` never receives a Lunora `MutationCtx` — the hook runs inside
|
|
45
|
+
* better-auth's own write path. A side effect on an app table is therefore a
|
|
46
|
+
* separate write and has to be idempotent; see `concepts/authentication`.
|
|
47
|
+
*/
|
|
48
|
+
type LunoraAuthOptions = BetterAuthOptions;
|
|
49
|
+
/**
|
|
50
|
+
* The full better-auth instance: `auth.handler` accepts a `Request` and
|
|
51
|
+
* returns a `Response` (used by `handleAuthRequest`); `auth.api`
|
|
52
|
+
* exposes the typed endpoint surface for server-side calls (e.g.
|
|
53
|
+
* `auth.api.getSession({ headers })` inside a query/mutation).
|
|
54
|
+
*/
|
|
55
|
+
type LunoraAuth = ReturnType<typeof betterAuth>;
|
|
56
|
+
/**
|
|
57
|
+
* Resolve the caller's options into the exact shape `createAuth` hands to
|
|
58
|
+
* `betterAuth` — the hardened, default-filled options the running worker uses.
|
|
59
|
+
* Exported (and pure) so the migration path can compile the schema from the
|
|
60
|
+
* same resolved options: `compileMigrationsSql` routes through here, so the
|
|
61
|
+
* `rateLimit` table the worker's durable limiter writes to is included in the
|
|
62
|
+
* migration rather than silently omitted (it would be, if migrations saw the
|
|
63
|
+
* raw options while the worker ran the resolved ones).
|
|
64
|
+
*
|
|
65
|
+
* ## What it fills (each gated independently on caller silence)
|
|
66
|
+
*
|
|
67
|
+
* Secure-by-default cookies + secret-strength warning via {@link hardenAuthOptions},
|
|
68
|
+
* applied first so all hardening composes onto one options object.
|
|
69
|
+
*
|
|
70
|
+
* Rate limiting is ON by default for `/api/auth/*`.
|
|
71
|
+
*
|
|
72
|
+
* better-auth's own default is `rateLimit.enabled ?? isProduction`, and its
|
|
73
|
+
* `isProduction` is `"production" === "production"` resolved at
|
|
74
|
+
* module-load time. On Cloudflare Workers that check is unreliable: the
|
|
75
|
+
* runtime has no Node `process.env` (absent entirely without
|
|
76
|
+
* `nodejs_compat`, and even with it `NODE_ENV` is rarely `"production"` at
|
|
77
|
+
* request time). So better-auth would silently leave auth endpoints
|
|
78
|
+
* _unthrottled_ on a real deployment — the surprise we refuse to ship.
|
|
79
|
+
*
|
|
80
|
+
* We therefore default `enabled: true` whenever the caller hasn't made an
|
|
81
|
+
* explicit choice. We only fill the `enabled` flag and otherwise forward
|
|
82
|
+
* the caller's `rateLimit` verbatim, so better-auth's `window` (10s) / `max`
|
|
83
|
+
* (100) defaults and any custom rules still apply. Callers who genuinely
|
|
84
|
+
* want it off can pass `rateLimit: { enabled: false }` (e.g. when fronting
|
|
85
|
+
* auth with their own limiter), and any explicit `enabled` value wins.
|
|
86
|
+
*
|
|
87
|
+
* We also default `storage: "database"` — but only when rate limiting is not
|
|
88
|
+
* explicitly disabled (`enabled !== false`). Filling storage under a disabled
|
|
89
|
+
* limiter is harmless at runtime but makes `getAuthTables` emit an unused
|
|
90
|
+
* `rateLimit` table, so we skip it there.
|
|
91
|
+
*
|
|
92
|
+
* better-auth's own default is `storage: "memory"` — a per-isolate,
|
|
93
|
+
* non-durable counter. On Cloudflare Workers that means each isolate keeps
|
|
94
|
+
* its own tally, counters vanish on isolate recycle, and traffic spread
|
|
95
|
+
* across isolates never sums to the configured `max` — a limiter that
|
|
96
|
+
* reports "enabled" while never enforcing a global limit (the exact
|
|
97
|
+
* brute-force / credential-stuffing protection on `/sign-in`, OTP, and
|
|
98
|
+
* password-reset it is meant to buy). `storage: "database"` rides the counter
|
|
99
|
+
* through the configured `database` adapter — Lunora's store over the D1 auth
|
|
100
|
+
* tables — so the limit is durable *and* atomic (the store's native
|
|
101
|
+
* `incrementOne` gives a one-winner guarantee across isolates). Callers with
|
|
102
|
+
* their own durable store can pass an explicit `rateLimit: { storage: … }`
|
|
103
|
+
* (or `customStorage`), and any explicit value wins.
|
|
104
|
+
*
|
|
105
|
+
* The limiter's *bucket key* is filled here too, and it is the half that makes
|
|
106
|
+
* the rest of the paragraph above true. A limit is only brute-force protection
|
|
107
|
+
* if the key identifies the client, so {@link defaultIpAddressHeaders} points
|
|
108
|
+
* better-auth at `cf-connecting-ip` instead of its own `x-forwarded-for`
|
|
109
|
+
* default, and {@link UNRESOLVED_IP_BUCKET_FACTOR} re-sizes the shared bucket
|
|
110
|
+
* for the deployments where no client IP can be resolved at all. Both are read
|
|
111
|
+
* off `advanced.ipAddress`, so a caller who configures that keeps their own
|
|
112
|
+
* policy end to end. The catch-all `customRules` entry is merged *after* the
|
|
113
|
+
* caller's own rules so theirs match first.
|
|
114
|
+
*
|
|
115
|
+
* Session cookie cache is ON by default too.
|
|
116
|
+
*
|
|
117
|
+
* Every authenticated call resolves identity through better-auth's
|
|
118
|
+
* `getSession`, which — without a cache — is a DB (D1) read on the hot path
|
|
119
|
+
* of every query/mutation/action that reads `ctx.auth` and of the WebSocket
|
|
120
|
+
* upgrade. better-auth's `session.cookieCache` carries the session payload in
|
|
121
|
+
* a short-lived signed cookie so `getSession` can answer without hitting the
|
|
122
|
+
* database until the cache window elapses. We default it on with a
|
|
123
|
+
* deliberately short 60s `maxAge` (better-auth's own default is 300s): long
|
|
124
|
+
* enough to erase the per-request read for a burst of calls, short enough
|
|
125
|
+
* that a revoked or role-changed session self-corrects within a minute.
|
|
126
|
+
* The one tradeoff — a revoked session stays valid until the cache expires —
|
|
127
|
+
* is bounded by that TTL; callers who need immediate revocation opt out with
|
|
128
|
+
* `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
|
|
129
|
+
* With better-auth's `admin()` plugin installed the default is OFF instead, so
|
|
130
|
+
* a ban holds from the user's next request; the cost is one session read per
|
|
131
|
+
* resolution. An explicit `cookieCache` still wins.
|
|
132
|
+
* With the organization plugin on, a small plugin re-issues that cache cookie
|
|
133
|
+
* whenever an `/organization/*` endpoint moved the caller's active organization
|
|
134
|
+
* or team (see `org-session-refresh.ts`), so a membership change is not hidden
|
|
135
|
+
* behind the cache window.
|
|
136
|
+
*
|
|
137
|
+
* A `user.emailCanonical` column is declared and filled on every user write (see
|
|
138
|
+
* `canonical-email.ts`): the uniquely indexed, Unicode-folded address that makes
|
|
139
|
+
* duplicate detection exact and indexed.
|
|
140
|
+
*
|
|
141
|
+
* Every explicit caller value is forwarded verbatim. The `rateLimit` fills all
|
|
142
|
+
* merge into a single `rateLimit` object so none clobbers the others.
|
|
143
|
+
*/
|
|
144
|
+
declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
|
|
145
|
+
/**
|
|
146
|
+
* Create the auth instance. Thin wrapper around `betterAuth` that enforces
|
|
147
|
+
* the `secret` requirement at construction time so misconfigured deployments
|
|
148
|
+
* fail loudly at the first fetch rather than the first sign-in attempt, then
|
|
149
|
+
* hands {@link resolveAuthOptions}'s hardened, default-filled options to
|
|
150
|
+
* better-auth.
|
|
151
|
+
*/
|
|
152
|
+
declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
|
|
153
|
+
export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as p}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{withCanonicalEmail as g}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{effectiveCookieCache as A}from"./effectiveCookieCache-JvL6i6YO.mjs";import{authDiscoveryPaths as E}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as w}from"better-auth/cookies";import{validateSessionPolicy as C}from"./sessionPresets-DQQYAOER.mjs";const d="lunora-org-session-refresh",S=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),v=new Set(["/organization/get-full-organization","/organization/get-organization"]),L=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await w(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return S.has(e.path)&&!t||v.has(e.path)&&t}}]},id:d}),T=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,L()]}},i="cf-connecting-ip",_=e=>{const t=e!==void 0&&e.length>0;return p()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",R=100,k=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*R,window:o.window}:o}},l=32,b=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,O=new Set(["127.0.0.1","localhost"]),y=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!O.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},I=e=>{const t=y(e.baseURL)??e.baseURL;if(b(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:_(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},N=e=>{const t=I(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:k(t)}};return g(T({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:A(t)}}:{}}))},H=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@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`.');return e.session&&C(e.session),E(e),N(e)},$=e=>{const t=H(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{$ as createAuth,H as prepareAuthOptions,N as resolveAuthOptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{I as h,a as O,c as S,M as j,R as T}from"./auth-do-uwp9VIYJ.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-EKQdB258.mjs";import{isDiscoveryRequest as _,unlessNotFound as D}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as U}from"./resolveSessionIdentity-EBhckRBW.mjs";import{DEFAULT_AUTH_BASE_PATH as H}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const L=(o,t,u)=>{const d={};for(const s of u){const a=t[s];Object.hasOwn(o,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(o,d)},q=o=>{const{internalSecret:t,jurisdiction:u,objectName:d="auth"}=o,s=U(o.claims),a=new Set(o.discoveryPaths),A=o.namespace;let{namespace:r}=o;if(r&&u!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(u)}const p=()=>{if(r)return r.get(r.idFromName(d))},E=async(e,n,i)=>{if(!t)return;const f=p();if(!f)return;const m=await f.fetch(new Request(new URL(e,n),{body:JSON.stringify(i),headers:{"content-type":"application/json",[h]:t},method:"POST"}));return m.ok?m:void 0},l=r,b=A&&l&&u!==void 0?S(async(e,n)=>{if(!t)throw new N("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?A:l;return i.get(i.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[h]:t},method:"POST"}))}):void 0,R=t&&l?P(async e=>l.get(l.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(e),headers:{"content-type":"application/json",[h]:t},method:"POST"}))):void 0;return{...R===void 0?{}:{dataPort:R},...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const n=await E(T,"https://auth-do.invalid",e);return n?(await n.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,H))return p()?.fetch(e)},discoveryHandler:async e=>{if(_(e,a))return D(await p()?.fetch(e))},resolveIdentity:async e=>{if(!t)return null;const n=p();if(!n)return null;const i=new Headers(e.headers);i.set(h,t);const f=new URL(O,e.url);s.length>0&&f.searchParams.set("claims",s.join(","));const m=await n.fetch(new Request(f,{headers:i}));if(!m.ok)return null;const c=await m.json(),y=c?.userId;if(!c||typeof y!="string"||y.length===0)return null;const v={userId:y};for(const g of["email","name","orgId","role","teamId"]){const w=c[g];typeof w=="string"&&w.length>0&&(v[g]=w)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(v.expiresAtMs=c.expiresAtMs),L(v,c,s)}}};export{q as createDoAuthWiring};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{apiKeyClient as m}from"@better-auth/api-key/client";import{oauthProviderClient as g}from"@better-auth/oauth-provider/client";import{passkeyClient as p}from"@better-auth/passkey/client";import{oneTapClient as C,lastLoginMethodClient as y,deviceAuthorizationClient as f,anonymousClient as S,multiSessionClient as b,phoneNumberClient as T,usernameClient as L,adminClient as v,emailOTPClient as w,magicLinkClient as A,twoFactorClient as P,organizationClient as k}from"better-auth/client/plugins";const i=Symbol.for("lunora:session-change"),E="lunora:session-change",s=()=>{const n=globalThis;let e=n[i];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[i]=e),e},r=()=>"document"in globalThis,N=async()=>{const n=[];for(const e of s().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},M=()=>{r()&&(s().sourceDeclared=!0)},c=async()=>{if(r()&&typeof BroadcastChannel=="function")try{const n=new BroadcastChannel(E);n.postMessage({tab:s().tab,type:"lunora:session-change"}),n.close()}catch{}await N()},a={organization:k,twoFactor:P,passkey:p,magicLink:A,emailOtp:w,admin:v,username:L,phoneNumber:T,multiSession:b,anonymous:S,deviceAuthorization:f,lastLoginMethod:y,oauthProvider:g,apiKey:m},O=(n={})=>{const e=[];for(const o of Object.keys(a))n[o]&&e.push(a[o]());return e},z=()=>globalThis.location?.origin,K=async()=>c(),I=()=>(M(),{fetchPlugins:[{hooks:{onSuccess:n=>{(n.request.method??"GET").toUpperCase()!=="GET"&&c().catch(()=>{})}},id:"lunora-session-sync",name:"lunora-session-sync"}],id:"lunora-session-sync"}),R=(n,e={})=>{const{baseURL:o,extraPlugins:l=[],oneTapClientId:t,plugins:u,...h}=e,d=t===void 0||t===""?[]:[C({clientId:t})];return n({...h,baseURL:o??z(),plugins:[I(),...O(u),...d,...l]})};export{R as createLunoraAuthClient,O as lunoraAuthPlugins,I as lunoraSessionSync,K as notifyLunoraSessionChange};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineErrorCodes as _}from"@better-auth/core/utils/error-codes";import{LunoraError as w}from"@lunora/errors";import{createAuthMiddleware as D,APIError as g}from"better-auth/api";import{canonicalEmail as p}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";const u="signUpInvitation",O=10080*60,v=365*24*60*60,y=500,A=_({SIGN_UP_INVITE_INVALID:"That sign-up invitation is not valid. Ask an administrator for a new invitation link.",SIGN_UP_INVITE_REQUIRED:"Sign-up is invite-only — ask an administrator for an invitation."}),x=32,N=new Set(["/admin/create-user","/sign-up/email"]),R=(e,t)=>e.emailVerified===!0||!t||N.has(t.path),U=/^[^\s@]+@[^\s@]+$/,b=e=>{if(!U.test(e))return!1;const t=e.slice(e.indexOf("@")+1);return t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")},m=e=>({acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:null,createdAt:e.createdAt,email:String(e.email),expiresAt:e.expiresAt,id:String(e.id),invitedBy:typeof e.invitedBy=="string"?e.invitedBy:null}),k=()=>btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(x)))).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),S=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(a=>a.toString(16).padStart(2,"0")).join("")},P=(e,t)=>{if(e.length!==t.length)return!1;let a=0;for(let o=0;o<e.length;o+=1)a|=(e.codePointAt(o)??0)^(t.codePointAt(o)??0);return a===0},I=e=>{if(typeof e.email!="string")return;const t=p(e.email);return t===""?void 0:t},V="anonymous",L=e=>(e.plugins??[]).some(t=>t.id===V),E=e=>e.isAnonymous===!0,T=e=>e===null||e.acceptedAt instanceof Date?!1:e.expiresAt instanceof Date&&e.expiresAt.getTime()>Date.now(),B=async(e,t)=>T(await e.findOne({model:u,where:[{field:"email",value:t}]})),q=e=>{e.emailAndPassword?.enabled!==!0||e.emailAndPassword.requireEmailVerification===!0||console.warn("@lunora/auth: inviteOnly() is installed with password sign-up but without `emailAndPassword: { requireEmailVerification: true }`. The invitation link is a bearer credential, so anyone it reaches — a forwarded mail, a shared inbox — can sign up as that address, and without verification they hold a session the moment they do.")},W=(e={})=>{let t=e.allowFirstUser??!1,a=!1;const o=async i=>{if(!t)return!1;const n=await i.count({model:"user"}),d=a&&n>0?await i.count({model:"user",where:[{field:"isAnonymous",value:!0}]}):0;return n-d<=0?!0:(t=!1,!1)};return{$ERROR_CODES:A,hooks:{before:[{handler:D(async i=>{const n=i.body??{},d=typeof n.email=="string"?p(n.email):"",f=typeof n.inviteToken=="string"?n.inviteToken:"",r=()=>{throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_INVALID)};if(d===""&&r(),await o(i.context.adapter))return;f===""&&r();const s=await i.context.adapter.findOne({model:u,where:[{field:"email",value:d}]}),l=s===null?void 0:s.tokenHash,c=await S(f);(typeof l!="string"||!P(l,c)||!T(s))&&r()}),matcher:i=>i.path==="/sign-up/email"}]},id:"lunora-invite-only",init:i=>{q(i.options);const{adapter:n}=i;return a=L(i.options),{options:{databaseHooks:{user:{create:{after:async r=>{const s=I(r);s===void 0||a&&E(r)||await n.update({model:u,update:{acceptedAt:new Date},where:[{field:"email",value:s}]})},before:async(r,s)=>{if(a&&E(r))return;const l=I(r);if(!(l!==void 0&&R(r,s)&&await B(n,l))&&!await o(n))throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_REQUIRED)}}}}}}},schema:{[u]:{fields:{acceptedAt:{required:!1,type:"date"},tokenHash:{required:!1,type:"string"},createdAt:{defaultValue:()=>new Date,required:!0,type:"date"},email:{required:!0,type:"string",unique:!0},expiresAt:{required:!0,type:"date"},invitedBy:{required:!1,type:"string"}}}}}},F=async(e,t)=>{const a=p(t.email);if(!b(a))throw new w("VALIDATION_ERROR",`not an email address to invite: ${JSON.stringify(t.email)}`);const{expiresInSeconds:o=O}=t;if(!Number.isInteger(o)||o<=0||o>v)throw new w("VALIDATION_ERROR",`expiresInSeconds must be a positive integer no greater than ${String(v)}`);const i=new Date(Date.now()+o*1e3),n=k(),d=await S(n),f=t.invitedBy??null,r=await e.$context,s=[{field:"email",value:a}],l=async()=>r.adapter.update({model:u,update:{acceptedAt:null,expiresAt:i,invitedBy:f,tokenHash:d},where:s});if(await r.adapter.findOne({model:u,where:s})){const c=await l();if(c)return{...m(c),token:n}}try{const c=await r.adapter.create({data:{createdAt:new Date,email:a,expiresAt:i,invitedBy:f,tokenHash:d},model:u});return{...m(c),token:n}}catch(c){const h=await l();if(h===null)throw c;return{...m(h),token:n}}},X=async(e,t={})=>{const i=(await(await e.$context).adapter.findMany({limit:y,model:u,sortBy:{direction:"desc",field:"createdAt"}})).map(n=>m(n));return t.pendingOnly===!0?i.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()>Date.now()):i},Y=async(e,t)=>{await(await e.$context).adapter.delete({model:u,where:[{field:"email",value:p(t.email)}]})},M=100,H=async(e,t,a,o)=>{const i=t.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()<=a).slice(0,o);for(const n of i)await e.delete({model:u,where:[{field:"id",value:n.id}]});return i.length},j=async(e,t={})=>{const a=t.limit??y;if(!Number.isInteger(a)||a<=0)throw new w("VALIDATION_ERROR","limit must be a positive integer");const o=Math.min(a,y),i=await e.$context,n=Date.now();let d=0,f=0;for(;d<o;){const r=await i.adapter.findMany({limit:M,model:u,offset:f,sortBy:{direction:"asc",field:"expiresAt"}});if(r.length===0)break;const s=r.map(c=>m(c)),l=await H(i.adapter,s,n,o-d);if(d+=l,s.some(c=>c.expiresAt.getTime()>n))break;f+=r.length-l}return d};export{u as INVITATION_MODEL,F as createSignUpInvitation,W as inviteOnly,X as listSignUpInvitations,j as pruneSignUpInvitations,Y as revokeSignUpInvitation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=e=>e.session?.cookieCache!==void 0?e.session.cookieCache:(e.plugins??[]).some(i=>i.id==="admin")?{enabled:!1}:{enabled:!0,maxAge:60};export{a as effectiveCookieCache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{APIError as l}from"better-auth/api";import{assertEmailAllowed as R}from"../email-guard.mjs";const y=e=>{switch(e){case 400:return"BAD_REQUEST";case 422:return"UNPROCESSABLE_ENTITY";case 429:return"TOO_MANY_REQUESTS";default:return"INTERNAL_SERVER_ERROR"}},f=async(e,a,r)=>{try{return await R(e,{...a,lists:r})}catch(t){throw t instanceof k?new l(y(t.status),{code:t.code,message:t.message}):t}},u=e=>async(a,r)=>{const t=typeof a.email=="string"?a.email:void 0;if(t===void 0||t==="")return;const o=e.onClassify!==void 0,i=await f(t,e,{disposable:e.blockDisposable!==!1||o,free:o});e.onClassify?.(i,a,r)},b=e=>async a=>{if(a.email!==void 0){if(typeof a.email!="string"||a.email==="")throw new l("BAD_REQUEST",{code:"VALIDATION_ERROR",message:"email must be a non-empty string"});await f(a.email,e,{disposable:e.blockDisposable!==!1,free:!1})}},A=(e,a)=>typeof e=="object"&&e!==null&&"data"in e?{...a,...e.data}:a,T=(e={})=>({user:{create:{before:u(e)},update:{before:b(e)}}}),U=(e,a={})=>{const r=u(a),t=b(a),o=e.databaseHooks?.user?.create?.before,i=e.databaseHooks?.user?.update?.before,m=o?async(s,n)=>(await r(s,n),o(s,n)):r,E=i?async(s,n)=>{await t(s);const w=s.email,c=await i(s,n),d=A(c,s);return d.email!==w&&await t(d),c}:t;return{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...e.databaseHooks?.user?.create,before:m},update:{...e.databaseHooks?.user?.update,before:E}}}}};export{T as emailGateDatabaseHooks,U as withEmailGate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DEFAULT_AUTH_BASE_PATH as o}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const s=(n,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;return n===r||n.startsWith(`${r}/`)},i=async(n,t,r=o)=>{const e=new URL(t.url);if(s(e.pathname,r))return n.handler(t)};export{o as DEFAULT_AUTH_BASE_PATH,i as handleAuthRequest,s as isAuthRoutePath};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),s=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),o=32,t=/^[A-Z_]\w{0,63}$/i;export{t as C,o as M,s as R,e as S};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getAuthTables as $}from"better-auth/db";import{runBackfillSync as v,BACKFILL_MAX_PAGES_SYNC as y,runBackfill as w,BACKFILL_MAX_PAGES as O,readBackfillState as R,BACKFILL_PAGE_ROWS as u,writeBackfillState as A,quote as h,aliasBeside as p,canonicalEmail as S}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{INVITATION_MODEL as m}from"./createSignUpInvitation-miwkunlA.mjs";const B=i=>{const t=$(i)[m];if(t!==void 0)return{createdAt:t.fields.createdAt?.fieldName??"createdAt",email:t.fields.email?.fieldName??"email",table:t.modelName}},T=i=>{const t=h(i.table),e=h(i.email),n=h(i.createdAt),a=p(i.table,"v"),o=p(i.table,"held");return{holders:`SELECT ${e} AS "email" FROM ${t} WHERE ${e} IN (SELECT "value" FROM json_each(?))`,read:d=>`SELECT rowid AS "rid", "id", ${e} AS "email", ${n} AS "createdAt" FROM ${t} WHERE (${e} GLOB '*[^ -~]*' OR ${e} <> LOWER(TRIM(${e})))${d?` AND (${n}, rowid) < (?, ?)`:""} ORDER BY ${n} DESC, rowid DESC LIMIT ?`,rows:`SELECT rowid AS "rid", ${e} AS "email" FROM ${t} WHERE rowid IN (SELECT "value" FROM json_each(?))`,update:`UPDATE ${t} SET ${e} = ${a}."folded" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "folded" FROM json_each(?)) AS ${a} WHERE ${t}.rowid = ${a}."rid" AND ${t}.${e} = ${a}."email" AND NOT EXISTS (SELECT 1 FROM ${t} AS ${o} WHERE ${o}.${e} = ${a}."folded") RETURNING rowid AS "rid"`}},L=(i,t)=>{const e=new Map;for(const n of i){const{email:a}=n;if(typeof a!="string")continue;const o=S(a);o!==a&&(e.has(o)?t.push(String(n.id)):e.set(o,n))}return e},N=function*(t,e,n){if(e.size===0)return;const a=yield{params:[JSON.stringify([...e.keys()])],sql:t.holders};for(const r of a){const l=String(r.email);n.push(String(e.get(l)?.id)),e.delete(l)}if(e.size===0)return;const o=yield{params:[JSON.stringify([...e].map(([r,l])=>[l.rid,l.email,r]))],sql:t.update},d=new Set(o.map(r=>r.rid)),c=[...e.values()].filter(r=>!d.has(r.rid));if(c.length===0)return;const s=yield{params:[JSON.stringify(c.map(r=>r.rid))],sql:t.rows},f=new Set(s.map(r=>`${String(r.rid)}\0${String(r.email)}`));for(const r of c)f.has(`${String(r.rid)}\0${String(r.email)}`)&&n.push(String(r.id))},E=function*(t,e,n){const a=T(t),{unchanged:o}=n,d=`${t.table}.${t.email}`,c=yield*R(d);let s=Array.isArray(c)?c:[];for(let f=0;f<e;f+=1){const r=yield{params:[...s,u],sql:a.read(s.length>0)};yield*N(a,L(r,o),o);const l=r.at(-1);if(r.length<u||l===void 0){s.length>0&&(yield*A(d,void 0)),n.done();return}s=[l.createdAt,l.rid],yield*A(d,s)}},g=i=>{i.length>0&&console.warn(`@lunora/auth: ${String(i.length)} sign-up invitation(s) fold to an address another invitation holds once case and Unicode form are ignored, so they were left unchanged and cannot be matched: ${i.join(", ")}. Delete those rows by id: revoking their address removes the invitation that holds it instead.`)},k=async(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{await w(E(t,O,n),i)}finally{g(e.unchanged)}return e},F=(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{v(E(t,y,n),i)}finally{g(e.unchanged)}return e},b=async(i,t,e)=>{if(typeof t.email!="string"||S(t.email)===t.email)return;const n=S(t.email);await i.findOne({model:m,where:[{field:"email",value:n}]})===null?await i.update({model:m,update:{email:n},where:[{field:"id",value:t.id},{field:"email",value:t.email}]}):e.push(t.id)},I=(i,t)=>{const e=t.at(-1);if(e===void 0)return i;const n=t.filter(a=>String(a.createdAt)===String(e.createdAt)).map(a=>a.id);return{createdAt:e.createdAt,ids:i!==void 0&&String(i.createdAt)===String(e.createdAt)?[...i.ids,...n]:n}},j=async i=>{const t={complete:!1,unchanged:[]};let e;try{for(;;){const n=await i.findMany({limit:u,model:m,sortBy:{direction:"desc",field:"createdAt"},where:e===void 0?[]:[{field:"createdAt",operator:"lte",value:e.createdAt},...e.ids.length>0?[{field:"id",operator:"not_in",value:e.ids}]:[]]});for(const a of n)await b(i,a,t.unchanged);if(n.length<u)return t.complete=!0,t;e=I(e,n)}}finally{g(t.unchanged)}};export{j as a,k as b,F as c,B as i};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { BetterAuthPlugin } from 'better-auth';
|
|
2
|
+
import { L as LunoraAuth } from "./create-auth.d-B8S7aw9O.mjs";
|
|
3
|
+
/** One pending or spent sign-up invitation. */
|
|
4
|
+
interface SignUpInvitation {
|
|
5
|
+
/** When an account was created for this address; `null` while the invitation is unspent. */
|
|
6
|
+
acceptedAt: Date | null;
|
|
7
|
+
createdAt: Date;
|
|
8
|
+
/** The invited address in canonical form (`canonicalEmail`) — the only thing an invitation is matched on. */
|
|
9
|
+
email: string;
|
|
10
|
+
expiresAt: Date;
|
|
11
|
+
id: string;
|
|
12
|
+
/** Free-form attribution (a user id, an operator name); never read by the gate. */
|
|
13
|
+
invitedBy: null | string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* What {@link createSignUpInvitation} hands back: the stored row plus the one
|
|
17
|
+
* and only sight of the plaintext `token`. Nothing reads it back afterwards —
|
|
18
|
+
* the database holds a SHA-256 of it — so an invitation link that is lost is
|
|
19
|
+
* reissued, not recovered.
|
|
20
|
+
*/
|
|
21
|
+
interface IssuedSignUpInvitation extends SignUpInvitation {
|
|
22
|
+
/** Put this in the sign-up link as `?invite=…`. Never stored, never logged, never listed. */
|
|
23
|
+
token: string;
|
|
24
|
+
}
|
|
25
|
+
/** Options for {@link inviteOnly}. */
|
|
26
|
+
interface InviteOnlyOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Let the very first account through uninvited, so a fresh deployment can be
|
|
29
|
+
* bootstrapped without seeding a row.
|
|
30
|
+
*
|
|
31
|
+
* **Off by default.** The check is "the `user` table is empty", which two
|
|
32
|
+
* concurrent sign-ups can both observe, and the window it opens is the gap
|
|
33
|
+
* between deploying and the owner signing up — whoever finds the URL first
|
|
34
|
+
* gets an account on a deployment whose whole point is that nobody does. Seed
|
|
35
|
+
* the first invitation with {@link createSignUpInvitation} instead (a one-off
|
|
36
|
+
* call at worker init, or an internal mutation you run once).
|
|
37
|
+
* @default false
|
|
38
|
+
*/
|
|
39
|
+
allowFirstUser?: boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A better-auth server plugin that refuses to create an account for an address
|
|
43
|
+
* with no unspent invitation, and the `signUpInvitation` table those live in.
|
|
44
|
+
*
|
|
45
|
+
* Issue invitations with {@link createSignUpInvitation}; there is no HTTP
|
|
46
|
+
* endpoint for it on purpose. Who counts as an administrator is your
|
|
47
|
+
* application's question — call it from a mutation you already authorize, the
|
|
48
|
+
* same trust model `createAuthAdmin` documents.
|
|
49
|
+
*
|
|
50
|
+
* The return type is better-auth's own `BetterAuthPlugin` rather than the
|
|
51
|
+
* precise shape of the schema map, for the reason `./ui-config.ts` spells out:
|
|
52
|
+
* an anonymous inferred type is the difference between a build that emits
|
|
53
|
+
* declarations and one that fails in the bundler alone.
|
|
54
|
+
*/
|
|
55
|
+
declare const inviteOnly: (options?: InviteOnlyOptions) => BetterAuthPlugin;
|
|
56
|
+
/**
|
|
57
|
+
* Invite `email` to sign up, or refresh an existing invitation for it.
|
|
58
|
+
*
|
|
59
|
+
* Re-inviting an address updates the row in place — a new expiry, and `acceptedAt`
|
|
60
|
+
* cleared — because `email` is unique. That is also how you re-open a seat after
|
|
61
|
+
* deleting the account that took it.
|
|
62
|
+
*
|
|
63
|
+
* This is a trusted server-side call with no authorization of its own; gate it
|
|
64
|
+
* the way you gate any other administrative action. Delivering the invitation is
|
|
65
|
+
* yours too: nothing here sends mail, so the returned row is the whole handoff.
|
|
66
|
+
*
|
|
67
|
+
* Nothing prunes the table — a spent or expired row stays until you delete it with
|
|
68
|
+
* {@link revokeSignUpInvitation}, which is also what keeps it a record of who was
|
|
69
|
+
* let in.
|
|
70
|
+
*
|
|
71
|
+
* Each call mints a **new token** and returns it in the clear, once. Only its
|
|
72
|
+
* SHA-256 is stored, so re-inviting an address invalidates the previous link, and
|
|
73
|
+
* a link that was never delivered is reissued rather than looked up.
|
|
74
|
+
*/
|
|
75
|
+
declare const createSignUpInvitation: (auth: LunoraAuth, input: {
|
|
76
|
+
email: string;
|
|
77
|
+
expiresInSeconds?: number;
|
|
78
|
+
invitedBy?: string;
|
|
79
|
+
}) => Promise<IssuedSignUpInvitation>;
|
|
80
|
+
/**
|
|
81
|
+
* The most recent invitations, newest first, up to a fixed ceiling of
|
|
82
|
+
* {@link MAX_LISTED}. `pendingOnly` drops the spent and the expired, which is the
|
|
83
|
+
* list an operator usually wants; the unfiltered form doubles as the record of who
|
|
84
|
+
* was let in.
|
|
85
|
+
*
|
|
86
|
+
* Deliberately not paged. "Pending" is two conditions, one of them a comparison
|
|
87
|
+
* against `now`, and filtering those after a page would let page 1 come back empty
|
|
88
|
+
* while pending invitations sat on page 2. An operator list that outgrows the
|
|
89
|
+
* ceiling wants a query against the `signUpInvitation` table, not an offset.
|
|
90
|
+
*/
|
|
91
|
+
declare const listSignUpInvitations: (auth: LunoraAuth, options?: {
|
|
92
|
+
pendingOnly?: boolean;
|
|
93
|
+
}) => Promise<SignUpInvitation[]>;
|
|
94
|
+
/**
|
|
95
|
+
* Withdraw the invitation for `email`. Deletes the row, so it also forgets a spent
|
|
96
|
+
* one — the account it created is untouched, and removing that is
|
|
97
|
+
* `AuthAdmin.removeUser`'s job.
|
|
98
|
+
*
|
|
99
|
+
* Not retroactive, and not atomic against a sign-up already in flight: better-auth
|
|
100
|
+
* creates the user without wrapping the `before` hook and the insert in one
|
|
101
|
+
* transaction, so a revoke landing between the two lets that one account through.
|
|
102
|
+
* There is no conditional consume in the adapter contract to close it with. Treat
|
|
103
|
+
* revocation as "no further sign-ups", and `AuthAdmin.removeUser` as the way to
|
|
104
|
+
* undo one that already happened.
|
|
105
|
+
*/
|
|
106
|
+
declare const revokeSignUpInvitation: (auth: LunoraAuth, input: {
|
|
107
|
+
email: string;
|
|
108
|
+
}) => Promise<void>;
|
|
109
|
+
/**
|
|
110
|
+
* Delete invitations that expired without being used, and report how many went.
|
|
111
|
+
*
|
|
112
|
+
* Only the dead ones: a spent invitation is the record of who was let in, and an
|
|
113
|
+
* unexpired one is still live, so both stay. Nothing calls this for you — an app
|
|
114
|
+
* that invites at any volume should put it on a cron; one that doesn't can leave
|
|
115
|
+
* the rows.
|
|
116
|
+
*
|
|
117
|
+
* Bounded by `limit` and therefore incremental: a backlog larger than one pass
|
|
118
|
+
* takes several. It reads a page and deletes row by row rather than issuing one
|
|
119
|
+
* ranged `deleteMany`, because a `lt` comparison against a `date` column is the
|
|
120
|
+
* kind of thing that behaves differently on each of the three adapters this
|
|
121
|
+
* package ships, and a prune job is not where that should be discovered.
|
|
122
|
+
*/
|
|
123
|
+
declare const pruneSignUpInvitations: (auth: LunoraAuth, options?: {
|
|
124
|
+
limit?: number;
|
|
125
|
+
}) => Promise<number>;
|
|
126
|
+
export { InviteOnlyOptions as I, SignUpInvitation as S, IssuedSignUpInvitation as a, createSignUpInvitation as c, inviteOnly as i, listSignUpInvitations as l, pruneSignUpInvitations as p, revokeSignUpInvitation as r };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { BetterAuthPlugin } from 'better-auth';
|
|
2
|
+
import { L as LunoraAuth } from "./create-auth.d-B8S7aw9O.js";
|
|
3
|
+
/** One pending or spent sign-up invitation. */
|
|
4
|
+
interface SignUpInvitation {
|
|
5
|
+
/** When an account was created for this address; `null` while the invitation is unspent. */
|
|
6
|
+
acceptedAt: Date | null;
|
|
7
|
+
createdAt: Date;
|
|
8
|
+
/** The invited address in canonical form (`canonicalEmail`) — the only thing an invitation is matched on. */
|
|
9
|
+
email: string;
|
|
10
|
+
expiresAt: Date;
|
|
11
|
+
id: string;
|
|
12
|
+
/** Free-form attribution (a user id, an operator name); never read by the gate. */
|
|
13
|
+
invitedBy: null | string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* What {@link createSignUpInvitation} hands back: the stored row plus the one
|
|
17
|
+
* and only sight of the plaintext `token`. Nothing reads it back afterwards —
|
|
18
|
+
* the database holds a SHA-256 of it — so an invitation link that is lost is
|
|
19
|
+
* reissued, not recovered.
|
|
20
|
+
*/
|
|
21
|
+
interface IssuedSignUpInvitation extends SignUpInvitation {
|
|
22
|
+
/** Put this in the sign-up link as `?invite=…`. Never stored, never logged, never listed. */
|
|
23
|
+
token: string;
|
|
24
|
+
}
|
|
25
|
+
/** Options for {@link inviteOnly}. */
|
|
26
|
+
interface InviteOnlyOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Let the very first account through uninvited, so a fresh deployment can be
|
|
29
|
+
* bootstrapped without seeding a row.
|
|
30
|
+
*
|
|
31
|
+
* **Off by default.** The check is "the `user` table is empty", which two
|
|
32
|
+
* concurrent sign-ups can both observe, and the window it opens is the gap
|
|
33
|
+
* between deploying and the owner signing up — whoever finds the URL first
|
|
34
|
+
* gets an account on a deployment whose whole point is that nobody does. Seed
|
|
35
|
+
* the first invitation with {@link createSignUpInvitation} instead (a one-off
|
|
36
|
+
* call at worker init, or an internal mutation you run once).
|
|
37
|
+
* @default false
|
|
38
|
+
*/
|
|
39
|
+
allowFirstUser?: boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A better-auth server plugin that refuses to create an account for an address
|
|
43
|
+
* with no unspent invitation, and the `signUpInvitation` table those live in.
|
|
44
|
+
*
|
|
45
|
+
* Issue invitations with {@link createSignUpInvitation}; there is no HTTP
|
|
46
|
+
* endpoint for it on purpose. Who counts as an administrator is your
|
|
47
|
+
* application's question — call it from a mutation you already authorize, the
|
|
48
|
+
* same trust model `createAuthAdmin` documents.
|
|
49
|
+
*
|
|
50
|
+
* The return type is better-auth's own `BetterAuthPlugin` rather than the
|
|
51
|
+
* precise shape of the schema map, for the reason `./ui-config.ts` spells out:
|
|
52
|
+
* an anonymous inferred type is the difference between a build that emits
|
|
53
|
+
* declarations and one that fails in the bundler alone.
|
|
54
|
+
*/
|
|
55
|
+
declare const inviteOnly: (options?: InviteOnlyOptions) => BetterAuthPlugin;
|
|
56
|
+
/**
|
|
57
|
+
* Invite `email` to sign up, or refresh an existing invitation for it.
|
|
58
|
+
*
|
|
59
|
+
* Re-inviting an address updates the row in place — a new expiry, and `acceptedAt`
|
|
60
|
+
* cleared — because `email` is unique. That is also how you re-open a seat after
|
|
61
|
+
* deleting the account that took it.
|
|
62
|
+
*
|
|
63
|
+
* This is a trusted server-side call with no authorization of its own; gate it
|
|
64
|
+
* the way you gate any other administrative action. Delivering the invitation is
|
|
65
|
+
* yours too: nothing here sends mail, so the returned row is the whole handoff.
|
|
66
|
+
*
|
|
67
|
+
* Nothing prunes the table — a spent or expired row stays until you delete it with
|
|
68
|
+
* {@link revokeSignUpInvitation}, which is also what keeps it a record of who was
|
|
69
|
+
* let in.
|
|
70
|
+
*
|
|
71
|
+
* Each call mints a **new token** and returns it in the clear, once. Only its
|
|
72
|
+
* SHA-256 is stored, so re-inviting an address invalidates the previous link, and
|
|
73
|
+
* a link that was never delivered is reissued rather than looked up.
|
|
74
|
+
*/
|
|
75
|
+
declare const createSignUpInvitation: (auth: LunoraAuth, input: {
|
|
76
|
+
email: string;
|
|
77
|
+
expiresInSeconds?: number;
|
|
78
|
+
invitedBy?: string;
|
|
79
|
+
}) => Promise<IssuedSignUpInvitation>;
|
|
80
|
+
/**
|
|
81
|
+
* The most recent invitations, newest first, up to a fixed ceiling of
|
|
82
|
+
* {@link MAX_LISTED}. `pendingOnly` drops the spent and the expired, which is the
|
|
83
|
+
* list an operator usually wants; the unfiltered form doubles as the record of who
|
|
84
|
+
* was let in.
|
|
85
|
+
*
|
|
86
|
+
* Deliberately not paged. "Pending" is two conditions, one of them a comparison
|
|
87
|
+
* against `now`, and filtering those after a page would let page 1 come back empty
|
|
88
|
+
* while pending invitations sat on page 2. An operator list that outgrows the
|
|
89
|
+
* ceiling wants a query against the `signUpInvitation` table, not an offset.
|
|
90
|
+
*/
|
|
91
|
+
declare const listSignUpInvitations: (auth: LunoraAuth, options?: {
|
|
92
|
+
pendingOnly?: boolean;
|
|
93
|
+
}) => Promise<SignUpInvitation[]>;
|
|
94
|
+
/**
|
|
95
|
+
* Withdraw the invitation for `email`. Deletes the row, so it also forgets a spent
|
|
96
|
+
* one — the account it created is untouched, and removing that is
|
|
97
|
+
* `AuthAdmin.removeUser`'s job.
|
|
98
|
+
*
|
|
99
|
+
* Not retroactive, and not atomic against a sign-up already in flight: better-auth
|
|
100
|
+
* creates the user without wrapping the `before` hook and the insert in one
|
|
101
|
+
* transaction, so a revoke landing between the two lets that one account through.
|
|
102
|
+
* There is no conditional consume in the adapter contract to close it with. Treat
|
|
103
|
+
* revocation as "no further sign-ups", and `AuthAdmin.removeUser` as the way to
|
|
104
|
+
* undo one that already happened.
|
|
105
|
+
*/
|
|
106
|
+
declare const revokeSignUpInvitation: (auth: LunoraAuth, input: {
|
|
107
|
+
email: string;
|
|
108
|
+
}) => Promise<void>;
|
|
109
|
+
/**
|
|
110
|
+
* Delete invitations that expired without being used, and report how many went.
|
|
111
|
+
*
|
|
112
|
+
* Only the dead ones: a spent invitation is the record of who was let in, and an
|
|
113
|
+
* unexpired one is still live, so both stay. Nothing calls this for you — an app
|
|
114
|
+
* that invites at any volume should put it on a cron; one that doesn't can leave
|
|
115
|
+
* the rows.
|
|
116
|
+
*
|
|
117
|
+
* Bounded by `limit` and therefore incremental: a backlog larger than one pass
|
|
118
|
+
* takes several. It reads a page and deletes row by row rather than issuing one
|
|
119
|
+
* ranged `deleteMany`, because a `lt` comparison against a `date` column is the
|
|
120
|
+
* kind of thing that behaves differently on each of the three adapters this
|
|
121
|
+
* package ships, and a prune job is not where that should be discovered.
|
|
122
|
+
*/
|
|
123
|
+
declare const pruneSignUpInvitations: (auth: LunoraAuth, options?: {
|
|
124
|
+
limit?: number;
|
|
125
|
+
}) => Promise<number>;
|
|
126
|
+
export { InviteOnlyOptions as I, SignUpInvitation as S, IssuedSignUpInvitation as a, createSignUpInvitation as c, inviteOnly as i, listSignUpInvitations as l, pruneSignUpInvitations as p, revokeSignUpInvitation as r };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const N=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,n=["CF_ENV","ENVIRONMENT","NODE_ENV","WORKER_ENV"],o=E=>{const e=n.map(t=>E[t]).filter(t=>t!==void 0);return e.length>0&&e.every(t=>typeof t=="string"&&N.test(t))};export{o as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{q as r}from"./quote-identifier-CGiYFBvY.mjs";const o="issuer",c=new RegExp(String.raw`\b${o}\b`,"iu"),a=s=>{const e=s.indexOf("(");if(e===-1)return"";let t=0;for(let n=e;n<s.length;n+=1){const i=s[n];if(i==="(")t+=1;else if(i===")"&&(t-=1,t===0))return s.slice(e+1,n)}return""},f=s=>[...s].some(e=>e.replaceAll(/[A-Z]/gu,t=>t.toLowerCase())===o),l=s=>[...s].filter(e=>c.test(a(e.sql??""))).map(e=>e.name),p=(s="account",e=[])=>[...[...e].map(t=>`DROP INDEX IF EXISTS ${r(t)}`),`ALTER TABLE ${r(s)} DROP COLUMN ${r(o)}`];export{l as indexesReferencingIssuer,p as legacyIssuerCleanupStatements,f as schemaDeclaresIssuer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mcp as o,requireMcpAuth as s}from"@better-auth/mcp";import{LunoraError as c}from"@lunora/errors";import{MCP_RESOURCE_KEY as u,protectedResourcePath as i,authorizationServerPath as n}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const a=e=>{if(!(typeof e=="string"&&URL.canParse(e)))throw new c("AUTH_MCP_RESOURCE_INVALID",`requireMcpAuth needs \`resource\` set to the absolute URL passed to mcp({ resource }), got ${JSON.stringify(e)}. Without it no issued token's audience matches and every request is refused.`)},d=e=>{const r=o(e);return Object.defineProperty(r,u,{value:e.resource}),r},E=(e,r,t)=>(a(t.resource),s(e,r,t)),P=(e,r=p)=>[i(e),n(r)];export{d as mcp,P as mcpDiscoveryPaths,E as requireMcpAuth};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers";export{o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{invalidateSchemaChecks as w,getAuthTablesWithResolvedIndexes as E}from"@better-auth/core/db/internal";import{q as l}from"./quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as y,backfillCanonicalEmails as g}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as C}from"./createAuth-DFkaeVge.mjs";import{convertAuthDatesOnce as k}from"./convertAuthDatesOnce-DE_O-bpx.mjs";import{i as I,b as S}from"./invitation-email-backfill-DUwurNbV.mjs";import{schemaDeclaresIssuer as m,legacyIssuerCleanupStatements as A,indexesReferencingIssuer as M}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{e as W,p as D}from"./provision-DWGVCbQD.mjs";const O=async(t,i)=>{const e=l("t");try{return await t.all(`SELECT ${e}.${l("issuer")} FROM ${l(i)} AS ${e} LIMIT 0`,[]),!0}catch{return!1}},N=t=>i=>{const e=t.tables[i]?.shape;return e===void 0?void 0:Object.keys(e)},$=async(t,i,e)=>{const{account:a}=E(i).tables;if(a===void 0)return!1;const n=Object.entries(a.fields).map(([o,r])=>r.fieldName??o),s=e===void 0?n:e(a.modelName);if(m(n)||s!==void 0&&m(s)||!await O(t,a.modelName))return!1;if(s===void 0)return console.warn(`@lunora/auth: "${a.modelName}" has an \`issuer\` column that the auth options do not declare. If it is the one better-auth 1.7.0-1.7.2 added, sign-ups fail until it is removed; it is left in place because no schema given to \`prepareAuthData\` declares the "${a.modelName}" table, so it may be the app's. Pass the schema that declares it as \`{ schema }\` to have the column dropped when that schema leaves it out, or run \`legacyIssuerCleanupStatements()\` by hand.`),!1;if(t.batch===void 0)return console.error("@lunora/auth: the reverted `account.issuer` column is present, but this executor has no `batch`, so it cannot be dropped atomically with its indexes; sign-ups fail until it is removed (`legacyIssuerCleanupStatements()`)."),!1;try{const o=await t.all("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",[a.modelName]);return await t.batch(A(a.modelName,M(o)).map(r=>({params:[],sql:r}))),!0}catch(o){return console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o),!1}},h=new WeakMap,b=(t,i)=>{let e=h.get(t);e===void 0&&(e=new WeakMap,h.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},c=new WeakMap,L=async(t,i,e,a)=>{const n=b(t,i);let s=c.get(n);s===void 0&&(s=$(i,e,a).then(o=>{const r=W(i);o&&r!==void 0&&w(r)},o=>{c.delete(n),console.error("@lunora/auth: the `account.issuer` cleanup stopped; the next call retries it.",o)}),c.set(n,s)),await s},u=new WeakMap,v=new WeakSet,T=async(t,i)=>{if(v.has(t))return;let e=u.get(t);e===void 0&&(e=i().then(a=>{a&&v.add(t)},a=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next call resumes it.",a)}).finally(()=>u.delete(t)),u.set(t,e)),await e},R=async(t,i,e)=>{const a=e.canonicalEmails?y(i):void 0,n=e.invitationEmails?I(i):void 0,s=a===void 0?void 0:await g(t,a),o=n===void 0?void 0:await S(t,n);return(s?.complete??!0)&&(o?.complete??!0)},d=new WeakMap,f=new WeakSet,q=async(t,i,e)=>{if(f.has(t))return;let a=d.get(t);a===void 0&&(a=k(i,e).then(()=>{},n=>{console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}).finally(()=>{f.add(t),d.delete(t)}),d.set(t,a)),await a},K={canonicalEmails:!0,invitationEmails:!0},p=new WeakMap,P=(t,i)=>{let e=p.get(t);e===void 0&&(e=new Map,p.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},F=async(t,i,e,a=K)=>{const n=b(t,i),s=a.canonicalEmails&&a.invitationEmails?n:P(n,`${String(a.canonicalEmails)}:${String(a.invitationEmails)}`);await L(t,i,e,a.declaredColumns),await T(s,async()=>R(i,e,a)),await q(n,i,e)},J=async(t,i,e={})=>{e.provision!==void 0&&await D(t,e.provision),await F(i,t,C(i),{canonicalEmails:e.canonicalEmailBackfill??!0,declaredColumns:e.schema===void 0?()=>{}:N(e.schema),invitationEmails:e.invitationEmailBackfill??!0})};export{T as backfillPass,L as dropLegacyIssuerOnce,J as prepareAuthData,F as prepareAuthDataFor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{invalidateSchemaChecks as o}from"@better-auth/core/db/internal";const c=new WeakMap,r=a=>c.get(a),v=(a,n)=>{c.set(a,n)},e=new WeakMap,d=async(a,n)=>{let t=e.get(a);t===void 0&&(t=n(a).then(()=>{const s=r(a);s!==void 0&&o(s)}),e.set(a,t),t.catch(()=>e.delete(a))),await t},w=(a,n)=>{const t=async()=>d(a,n);return{all:async(s,i)=>(await t(),a.all(s,i)),...a.batch===void 0?{}:{batch:async s=>{await t(),await a.batch?.(s)}},run:async(s,i)=>{await t(),await a.run(s,i)}}};export{w as a,r as e,d as p,v as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=e=>`"${e.replaceAll('"','""')}"`;export{t as q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isAPIError as I}from"better-auth/api";import{C as p,R as c,S as l,M as g}from"./identity-claims-hAvIl2wm.mjs";const s=e=>typeof e=="string"&&e.length>0?e:void 0,S=(e,t)=>{if(!(c.has(e)||l.has(e))){if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return Number.isNaN(t.getTime())?void 0:t.toISOString()}},b=e=>(e??[]).filter(t=>p.test(t)&&!c.has(t)&&!l.has(t)).slice(0,g),h=e=>e==null||e===""?[]:b(e.split(",").map(t=>t.trim())),N=(e,t)=>{const i={};for(const r of t){const o=S(r,e[r]);o!==void 0&&(i[r]=o)}return i},y=(e,t)=>{if(e.banned!==!0)return!1;const i=e.banExpires;if(i==null)return!0;const r=i instanceof Date?i.getTime():new Date(i).getTime();return Number.isNaN(r)||r>t},E=(e,t=[])=>{const i=s(e?.user.id);if(e==null||i===void 0||y(e.user,Date.now()))return null;const{activeOrganizationId:r,activeTeamId:o,expiresAt:n}=e.session,d=s(e.user.email),a=s(e.user.name),m=s(r),f=s(e.user.role),u=s(o);return{...N(e.user,t),...d===void 0?{}:{email:d},...n instanceof Date?{expiresAtMs:n.getTime()}:{},...a===void 0?{}:{name:a},...m===void 0?{}:{orgId:m},...f===void 0?{}:{role:f},...u===void 0?{}:{teamId:u},userId:i}},M=async(e,t)=>{try{return await e.api.getSession({headers:t})}catch(i){if(I(i)&&(i.statusCode===401||i.statusCode===403))return;throw i}},w=async(e,t,i=[])=>{const r=E(await M(e,t),i);if(r===null||r.orgId===void 0&&r.teamId===void 0)return r;const{orgId:o,teamId:n,...d}=r;if(o===void 0)return d;const{adapter:a}=await e.$context,{userId:m}=r,[f,u,v]=await Promise.all([a.findOne({model:"member",where:[{field:"organizationId",value:o},{field:"userId",value:m}]}),n===void 0?void 0:a.findOne({model:"team",where:[{field:"id",value:n},{field:"organizationId",value:o}]}),n===void 0?void 0:a.findOne({model:"teamMember",where:[{field:"teamId",value:n},{field:"userId",value:m}]})]);return f?{...d,orgId:o,...u&&v?{teamId:n}:{}}:d};export{E as identityFromSession,h as parseClaimNames,w as resolveSessionIdentity,b as validClaimNames};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=s=>{const o=["expiresIn","updateAge","freshAge"];for(const n of o){const e=s[n];if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0))throw new TypeError(`@lunora/auth: \`session.${n}\` must be a non-negative, finite number of seconds`)}return s},i={longLived:{expiresIn:2592e3,freshAge:86400,updateAge:86400},rolling:{expiresIn:604800,freshAge:86400,updateAge:86400},strict:{cookieCache:{enabled:!1},expiresIn:3600,freshAge:300,updateAge:900}};export{i as sessionPresets,t as validateSessionPolicy};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as N}from"./provision-DWGVCbQD.mjs";const T="_creationTime",l=n=>`"${n.replaceAll('"','""')}"`,M=/no such column|column .{0,64}? does not exist/iu,L={params:[],sql:"0"},h=(n,r)=>r?{column:`LOWER(${n})`,placeholder:"LOWER(?)"}:{column:n,placeholder:"?"},S=(n,r,a,o)=>{if(typeof r!="string")return L;const t=h(n,o);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}`}},R=(n,r,a,o)=>{if(r===null)return{params:[],sql:`${n} IS ${o?"NOT ":""}NULL`};const t=h(n,a),s=o?"<>":"=";return{params:[r],sql:`${t.column} ${s} ${t.placeholder}`}},O=(n,r,a,o)=>{const t=Array.isArray(r)?r:[];if(t.length===0)return{params:[],sql:a?"1":"0"};const s=h(n,o),e=t.map(()=>s.placeholder).join(", ");return{params:[...t],sql:`${s.column} ${a?"NOT IN":"IN"} (${e})`}},C=n=>{const r=l(n.field),{mode:a,operator:o,value:t}=n,s=a==="insensitive";switch(o){case"contains":case"ends_with":case"starts_with":return S(r,t,o,s);case"gt":return{params:[t],sql:`${r} > ?`};case"gte":return{params:[t],sql:`${r} >= ?`};case"in":return O(r,t,!1,s);case"lt":return{params:[t],sql:`${r} < ?`};case"lte":return{params:[t],sql:`${r} <= ?`};case"ne":return R(r,t,s,!0);case"not_in":return O(r,t,!0,s);default:return R(r,t,s,!1)}},w=(n,r)=>{if(n.length===0)return;const a=n.map(o=>C(o));return{params:a.flatMap(o=>o.params),sql:a.map(o=>`(${o.sql})`).join(` ${r} `)}},E=n=>{const r=[w(n.filter(a=>a.connector!=="OR"),"AND"),w(n.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 ")}},$=n=>n.sql?` WHERE ${n.sql}`:"",y=n=>{const r=(t,s)=>{const e=E(s);return n.all(`SELECT * FROM ${l(t)}${$(e)}`,e.params)},a=new Map,o=async t=>{const s=a.get(t);if(s!==void 0)return s;try{await n.all(`SELECT ${l(t)}.${l(T)} FROM ${l(t)} LIMIT 0`,[])}catch(e){return M.test(e instanceof Error?e.message:String(e))&&a.set(t,!1),!1}return a.set(t,!0),!0};return{consumeOne:async(t,s)=>{const e=E(s),c=l(t),[i]=await n.all(`DELETE FROM ${c} WHERE rowid IN (SELECT rowid FROM ${c}${$(e)} LIMIT 1) RETURNING *`,e.params);return i},count:async(t,s)=>{const e=E(s),[c]=await n.all(`SELECT COUNT(*) AS __count FROM ${l(t)}${$(e)}`,e.params);return Number(c?.__count??0)},create:async(t,s)=>{const e=T in s||!await o(t)?s:{[T]:Date.now(),...s},c=Object.keys(e),i=c.map(()=>"?").join(", "),u=`INSERT INTO ${l(t)} (${c.map(m=>l(m)).join(", ")}) VALUES (${i})`;return await n.run(u,c.map(m=>e[m])),{...s}},incrementOne:async(t,s,e,c)=>{const i=l(t),u=Object.keys(e),m=c?Object.keys(c):[],f=E(s);if(u.length===0&&m.length===0){const[p]=await n.all(`SELECT * FROM ${i}${$(f)} LIMIT 1`,f.params);return p}const d=[...u.map(p=>`${l(p)} = COALESCE(${l(p)}, 0) + ?`),...m.map(p=>`${l(p)} = ?`)].join(", "),[g]=await n.all(`UPDATE ${i} SET ${d} WHERE rowid IN (SELECT rowid FROM ${i}${$(f)} LIMIT 1) RETURNING *`,[...u.map(p=>e[p]),...m.map(p=>c[p]),...f.params]);return g},read:async(t,s)=>{const e=E(s.where),c=[...e.params];let i=`SELECT * FROM ${l(t)}${$(e)}`;return s.sortBy&&(i+=` ORDER BY ${l(s.sortBy.field)} ${s.sortBy.direction==="asc"?"ASC":"DESC"}`),s.limit!==void 0&&(i+=" LIMIT ?",c.push(Math.trunc(s.limit))),s.offset&&(i+=`${s.limit===void 0?" LIMIT -1":""} OFFSET ?`,c.push(Math.trunc(s.offset))),n.all(i,c)},remove:async(t,s)=>{const e=E(s);return(await n.all(`DELETE FROM ${l(t)}${$(e)} RETURNING *`,e.params)).length},update:async(t,s,e)=>{const c=Object.keys(e);if(c.length===0)return r(t,s);const i=c.map(m=>`${l(m)} = ?`).join(", "),u=E(s);return n.all(`UPDATE ${l(t)} SET ${i}${$(u)} RETURNING *`,[...c.map(m=>e[m]),...u.params])}}},I=new WeakMap,F=n=>{const r=I.get(n);if(r!==void 0)return r;const a={all:async(o,t)=>(await n.prepare(o).bind(...t).all()).results??[],...typeof n.batch=="function"?{batch:async o=>{await n.batch?.(o.map(t=>n.prepare(t.sql).bind(...t.params)))}}:{},run:async(o,t)=>{await n.prepare(o).bind(...t).run()}};return I.set(n,a),N(a,n),a};export{T as C,y as c,F as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAuthEndpoint as c}from"better-auth/api";import{getAuthTables as g}from"better-auth/db";const l=e=>[...e].toSorted((o,i)=>o.localeCompare(i)),m=(e,o={})=>{const i=o.expose??{},a=new Set((e.plugins??[]).map(t=>t.id)),r=e.emailAndPassword?.enabled??!1,s=g(e),n=(e.plugins??[]).find(t=>t.id==="organization")?.options??{},d={allowUserToCreate:typeof n.allowUserToCreateOrganization=="function"?!0:n.allowUserToCreateOrganization!==!1,enabled:a.has("organization"),invitationLimit:n.invitationLimit,limit:n.organizationLimit,membershipLimit:n.membershipLimit,roles:!!s.organizationRole,teams:!!s.team};return{emailAndPassword:r,signUp:r&&e.emailAndPassword?.disableSignUp!==!0,...i.organization===!1?{}:{organization:d},...i.plugins===!1?{}:{plugins:l(a)},...i.socialProviders===!1?{}:{socialProviders:l(new Set([...Object.keys(e.socialProviders??{}),...o.extraProviders??[]]))}}},p=e=>c(e.path??"/ui-config",{metadata:{openapi:{description:"Public description of the enabled auth plugins and social providers.",responses:{200:{description:"The UI configuration."}}}},method:"GET"},o=>{const i=o;return Promise.resolve(i.json(m(i.context.options,e)))}),h=(e={})=>({endpoints:{getUiConfig:p(e)},id:"lunora-ui-config"});export{m as deriveUiConfig,h as uiConfig};
|