@lunora/auth 1.0.0-alpha.6 → 1.0.0-alpha.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE.md +38 -0
  2. package/README.md +56 -1
  3. package/dist/adapter.d.mts +4 -43
  4. package/dist/adapter.d.ts +4 -43
  5. package/dist/adapter.mjs +1 -47
  6. package/dist/audit.d.mts +114 -0
  7. package/dist/audit.d.ts +114 -0
  8. package/dist/audit.mjs +11 -0
  9. package/dist/email-guard.d.mts +122 -0
  10. package/dist/email-guard.d.ts +122 -0
  11. package/dist/email-guard.mjs +1 -0
  12. package/dist/index.d.mts +630 -147
  13. package/dist/index.d.ts +630 -147
  14. package/dist/index.mjs +1 -12
  15. package/dist/middleware.d.mts +156 -155
  16. package/dist/middleware.d.ts +156 -155
  17. package/dist/middleware.mjs +1 -53
  18. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-DkkUg061.mjs +1 -0
  19. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-kIwlEt8i.mjs +1 -0
  20. package/dist/packem_shared/LunoraAuthAdminError-CiHsF1qZ.mjs +1 -0
  21. package/dist/packem_shared/adapter-RvDcm0Zy.mjs +1 -0
  22. package/dist/packem_shared/adapter.d-2a61HAY2.d.ts +76 -0
  23. package/dist/packem_shared/adapter.d-DrD3bb1u.d.mts +76 -0
  24. package/dist/packem_shared/authAuditHook-Dx3sqf3G.mjs +1 -0
  25. package/dist/packem_shared/authDoColumnAdditions-B8BRbdzn.mjs +1 -0
  26. package/dist/packem_shared/compileMigrationsSql-BcvcHAqo.mjs +1 -0
  27. package/dist/packem_shared/create-auth.d-De6IOirt.d.mts +128 -0
  28. package/dist/packem_shared/create-auth.d-De6IOirt.d.ts +128 -0
  29. package/dist/packem_shared/createAuth-DRtd4q6u.mjs +1 -0
  30. package/dist/packem_shared/createDoAuthWiring-DlOR_nIq.mjs +1 -0
  31. package/dist/packem_shared/createLunoraAuthClient-CedinxXU.mjs +1 -0
  32. package/dist/packem_shared/emailGateDatabaseHooks-DzBD1Qoq.mjs +1 -0
  33. package/dist/packem_shared/sessionPresets-DpEFjXKV.mjs +1 -0
  34. package/dist/packem_shared/uiConfig-BrYEFK3O.mjs +1 -0
  35. package/dist/plugins-client.d.mts +68 -1
  36. package/dist/plugins-client.d.ts +68 -1
  37. package/dist/plugins-client.mjs +1 -2
  38. package/dist/plugins-enterprise-client.d.mts +9 -0
  39. package/dist/plugins-enterprise-client.d.ts +9 -0
  40. package/dist/plugins-enterprise-client.mjs +1 -0
  41. package/dist/plugins-enterprise.d.mts +1576 -0
  42. package/dist/plugins-enterprise.d.ts +1576 -0
  43. package/dist/plugins-enterprise.mjs +1 -0
  44. package/dist/plugins.d.mts +83 -2
  45. package/dist/plugins.d.ts +83 -2
  46. package/dist/plugins.mjs +1 -22
  47. package/dist/schema.d.mts +39 -39
  48. package/dist/schema.d.ts +39 -39
  49. package/dist/schema.mjs +1 -62
  50. package/dist/sql-store.d.mts +28 -28
  51. package/dist/sql-store.d.ts +28 -28
  52. package/dist/sql-store.mjs +1 -162
  53. package/dist/store.d.mts +49 -31
  54. package/dist/store.d.ts +49 -31
  55. package/dist/store.mjs +1 -170
  56. package/dist/turnstile-middleware.d.mts +55 -55
  57. package/dist/turnstile-middleware.d.ts +55 -55
  58. package/dist/turnstile-middleware.mjs +1 -45
  59. package/dist/turnstile.d.mts +42 -59
  60. package/dist/turnstile.d.ts +42 -59
  61. package/dist/turnstile.mjs +1 -61
  62. package/package.json +38 -5
  63. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  64. package/dist/packem_shared/LunoraAuthAdminError-BxrfEeA_.mjs +0 -249
  65. package/dist/packem_shared/compileMigrationsSql-wZH3oXDu.mjs +0 -28
  66. package/dist/packem_shared/create-auth.d-M36jwG_Y.d.mts +0 -58
  67. package/dist/packem_shared/create-auth.d-M36jwG_Y.d.ts +0 -58
  68. package/dist/packem_shared/createAuth-B-tvsvQU.mjs +0 -56
  69. package/dist/packem_shared/sessionPresets-B95rXrd8.mjs +0 -35
package/LICENSE.md CHANGED
@@ -103,3 +103,41 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+
112
+ # Licenses of bundled types
113
+ The published @lunora/auth artifact additionally contains code with the following licenses:
114
+ MIT
115
+
116
+ # Bundled types:
117
+ ## @better-auth/sso
118
+ License: MIT
119
+ By: Bereket Engida
120
+ Repository: git+https://github.com/better-auth/better-auth.git
121
+
122
+ > The MIT License (MIT)
123
+ > Copyright (c) 2024 - present, Bereket Engida
124
+ >
125
+ > Permission is hereby granted, free of charge, to any person obtaining a copy of
126
+ > this software and associated documentation files (the “Software”), to deal in
127
+ > the Software without restriction, including without limitation the rights to
128
+ > use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
129
+ > the Software, and to permit persons to whom the Software is furnished to do so,
130
+ > subject to the following conditions:
131
+ >
132
+ > The above copyright notice and this permission notice shall be included in all
133
+ > copies or substantial portions of the Software.
134
+ >
135
+ > THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
136
+ > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
137
+ > FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
138
+ > IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
139
+ > DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
140
+ > ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
141
+ > DEALINGS IN THE SOFTWARE.
142
+
143
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -84,10 +84,65 @@ The runtime resolves the inbound session and stamps `ctx.auth` on every `query`
84
84
 
85
85
  ### Plugins & CAPTCHA
86
86
 
87
- better-auth's plugin factories are re-exported from `@lunora/auth/plugins` (so you don't need better-auth's deep import paths): `admin`, `anonymous`, `bearer`, `captcha`, `createAccessControl`, `customSession`, `deviceAuthorization`, `emailOTP`, `genericOAuth`, `haveIBeenPwned`, `jwt`, `magicLink`, `mcp`, `multiSession`, `oAuthProxy`, `oidcProvider`, `oneTimeToken`, `organization`, `passkey`, `phoneNumber`, `siwe`, `twoFactor`, `username`, and `withMcpAuth`.
87
+ better-auth's plugin factories are re-exported from `@lunora/auth/plugins` (so you don't need better-auth's deep import paths): `admin`, `anonymous`, `bearer`, `captcha`, `createAccessControl`, `customSession`, `deviceAuthorization`, `emailOTP`, `genericOAuth`, `haveIBeenPwned`, `jwt`, `magicLink`, `mcp`, `mcpHandler`, `multiSession`, `oAuthProxy`, `oauthProvider`, `oneTimeToken`, `organization`, `passkey`, `phoneNumber`, `requireMcpAuth`, `scim`, `siwe`, `twoFactor`, and `username`. Enterprise SSO ships separately as `sso` from `@lunora/auth/plugins/enterprise` (an optional peer — see the docs).
88
88
 
89
89
  For Cloudflare Turnstile on the **auth flow**, use the `captcha` plugin (`captcha({ provider: "cloudflare-turnstile", secretKey: env.TURNSTILE_SECRET_KEY })`); it reads the token from the `x-captcha-response` header. For **non-auth** procedures, the package root also exports standalone helpers — `verifyTurnstile` (pure `siteverify`) and `verifyTurnstileMiddleware` (a `.use()` middleware that takes the token from the function args).
90
90
 
91
+ ### Disposable / free-email gating
92
+
93
+ Reject throwaway/disposable signups (and branch on free-vs-business email) by reusing the visulima email lists — pure-data and **edge-safe on the default path** (no DNS). Wire it into better-auth's native signup with `withEmailGate` (or `emailGateDatabaseHooks`):
94
+
95
+ ```ts
96
+ import { createAuth, withEmailGate, lunoraD1Adapter } from "@lunora/auth";
97
+
98
+ const auth = createAuth(
99
+ withEmailGate(
100
+ { secret: env.AUTH_SECRET, database: lunoraD1Adapter(env.DB), emailAndPassword: { enabled: true } },
101
+ {
102
+ blockDisposable: true, // default — reject disposable domains with `EMAIL_DOMAIN_BLOCKED`
103
+ allowDomains: ["your-company.com"], // never blocked; always classified `business`
104
+ denyDomains: [], // extra domains to treat as disposable
105
+ // mx: true, // OPT-IN deliverability check — needs DNS (node:dns), so keep it OFF on the edge path
106
+ onClassify: (c, user) => console.log(`signup ${user.email as string}: ${c.emailClass}`),
107
+ },
108
+ ),
109
+ );
110
+ ```
111
+
112
+ A blocked signup fails with the coded error `EMAIL_DOMAIN_BLOCKED` (HTTP 400); a business/free email passes and its `emailClass` (`disposable | free | business`) is surfaced via `onClassify`. Everything is config-gated and defaults sensibly.
113
+
114
+ - **Programmatic / non-auth use:** `classifyEmail(email, config)` (sync, pure-data) and `assertEmailAllowed(email, config)` (async; throws the coded error) come from `@lunora/auth/email-guard`, plus `emailGateMiddleware({ email: (ctx) => ctx.args.email })` for a `.use()` gate on your own signup mutations.
115
+ - **Edge-safety:** on workerd, `await loadEmailDomainLists()` once at worker init (the gate helpers do this for you). The optional `mx: true` deliverability check is loaded via a dynamic import so `node:dns` never enters the default bundle — enable it only with `nodejs_compat` (or a DNS-over-HTTPS shim).
116
+
117
+ ### Security / audit trail
118
+
119
+ Record authentication & security events (sign-in, sign-up, password change, MFA enable/disable, token refresh, session revoke, …) to a durable, queryable audit trail. Install the better-auth `hooks.after` recorder with `authAuditHook` (or compose via `withAuthAudit`), backed by the same D1 database as the auth tables:
120
+
121
+ ```ts
122
+ import { authAuditHook, createAuth, d1Executor, lunoraD1Adapter, readAuthAuditLog } from "@lunora/auth";
123
+
124
+ const executor = d1Executor(env.DB);
125
+
126
+ const auth = createAuth({
127
+ secret: env.AUTH_SECRET,
128
+ database: lunoraD1Adapter(env.DB),
129
+ hooks: {
130
+ after: authAuditHook({
131
+ executor,
132
+ // retention is CONFIGURABLE and NOT capped — omit it for an unbounded, compliance-grade trail
133
+ retention: 100_000,
134
+ // optional export tap for SIEM forwarding (receives each redacted entry)
135
+ onRecord: (entry) => forwardToSiem(entry),
136
+ }),
137
+ },
138
+ });
139
+
140
+ // Query the trail (RLS/admin-gate this in your own read):
141
+ const recent = await readAuthAuditLog(executor, { event: "sign-in", limit: 100 });
142
+ ```
143
+
144
+ The free-form `detail` payload is scrubbed with `@visulima/redact` before it is persisted, so a token/password that leaks into an event's context never reaches the durable table. Retention defaults to unbounded (set `retention` to bound it). The store lives in the reserved `__lunora_auth_audit__` table (auto-hidden from the data browser).
145
+
91
146
  > This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/packages/auth)**.
92
147
 
93
148
  ## Related
@@ -1,43 +1,4 @@
1
- import { createAdapterFactory } from 'better-auth/adapters';
2
- import { d1Executor } from "./sql-store.mjs";
3
- import { AuthStore } from "./store.mjs";
4
- /**
5
- * A better-auth database adapter backed by an {@link AuthStore} — the bridge
6
- * that routes better-auth's reads and writes through Lunora's data layer
7
- * instead of better-auth's built-in D1/Kysely adapter. Pass the result as
8
- * `createAuth({ database: lunoraAuthAdapter(store) })`; better-auth's
9
- * `createAdapterFactory` handles id generation, default values, field-name
10
- * mapping and output shaping, so this only translates the cleaned CRUD calls
11
- * onto the store.
12
- *
13
- * ```ts
14
- * const auth = createAuth({
15
- * secret: env.AUTH_SECRET,
16
- * emailAndPassword: { enabled: true },
17
- * database: lunoraAuthAdapter(lunoraStore), // lunoraStore writes via ctx.db
18
- * });
19
- * ```
20
- *
21
- * Scope: the {@link AuthStore} interface is single-table CRUD. better-auth's
22
- * relational `join` reads (an advanced opt-in) are not handled — pair the
23
- * adapter with `disableJoins` or let better-auth fall back to per-table reads.
24
- */
25
- declare const lunoraAuthAdapter: (store: AuthStore) => ReturnType<typeof createAdapterFactory>;
26
- /**
27
- * One-liner for the common case: a better-auth `database` backed by a Cloudflare
28
- * D1 binding, via Lunora's SQL store — equivalent to
29
- * `lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)))`.
30
- *
31
- * Prefer this over passing the raw `env.DB` as `database`. With raw D1,
32
- * better-auth resolves its Kysely adapter through a runtime `await import(...)`
33
- * inside `auth.$context`, and that dynamic import never settles under
34
- * `@cloudflare/vite-plugin`'s worker runner — so it hangs *every* auth request
35
- * in `pnpm dev` (a standalone `wrangler dev` or a deployed worker bundle it
36
- * up-front, so they're unaffected — which makes the hang baffling to debug).
37
- * This explicit adapter skips that import entirely, so dev and prod behave the
38
- * same. The migration instance is the one exception — it wants raw `env.DB` so
39
- * `ensureMigrated`'s Kysely migrator can create the tables (its `$context` is
40
- * never resolved, so the hang doesn't apply there).
41
- */
42
- declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
43
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import 'better-auth/adapters';
2
+ export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-DrD3bb1u.mjs";
3
+ import "./sql-store.mjs";
4
+ import "./store.mjs";
package/dist/adapter.d.ts CHANGED
@@ -1,43 +1,4 @@
1
- import { createAdapterFactory } from 'better-auth/adapters';
2
- import { d1Executor } from "./sql-store.js";
3
- import { AuthStore } from "./store.js";
4
- /**
5
- * A better-auth database adapter backed by an {@link AuthStore} — the bridge
6
- * that routes better-auth's reads and writes through Lunora's data layer
7
- * instead of better-auth's built-in D1/Kysely adapter. Pass the result as
8
- * `createAuth({ database: lunoraAuthAdapter(store) })`; better-auth's
9
- * `createAdapterFactory` handles id generation, default values, field-name
10
- * mapping and output shaping, so this only translates the cleaned CRUD calls
11
- * onto the store.
12
- *
13
- * ```ts
14
- * const auth = createAuth({
15
- * secret: env.AUTH_SECRET,
16
- * emailAndPassword: { enabled: true },
17
- * database: lunoraAuthAdapter(lunoraStore), // lunoraStore writes via ctx.db
18
- * });
19
- * ```
20
- *
21
- * Scope: the {@link AuthStore} interface is single-table CRUD. better-auth's
22
- * relational `join` reads (an advanced opt-in) are not handled — pair the
23
- * adapter with `disableJoins` or let better-auth fall back to per-table reads.
24
- */
25
- declare const lunoraAuthAdapter: (store: AuthStore) => ReturnType<typeof createAdapterFactory>;
26
- /**
27
- * One-liner for the common case: a better-auth `database` backed by a Cloudflare
28
- * D1 binding, via Lunora's SQL store — equivalent to
29
- * `lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)))`.
30
- *
31
- * Prefer this over passing the raw `env.DB` as `database`. With raw D1,
32
- * better-auth resolves its Kysely adapter through a runtime `await import(...)`
33
- * inside `auth.$context`, and that dynamic import never settles under
34
- * `@cloudflare/vite-plugin`'s worker runner — so it hangs *every* auth request
35
- * in `pnpm dev` (a standalone `wrangler dev` or a deployed worker bundle it
36
- * up-front, so they're unaffected — which makes the hang baffling to debug).
37
- * This explicit adapter skips that import entirely, so dev and prod behave the
38
- * same. The migration instance is the one exception — it wants raw `env.DB` so
39
- * `ensureMigrated`'s Kysely migrator can create the tables (its `$context` is
40
- * never resolved, so the hang doesn't apply there).
41
- */
42
- declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
43
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import 'better-auth/adapters';
2
+ export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-2a61HAY2.js";
3
+ import "./sql-store.js";
4
+ import "./store.js";
package/dist/adapter.mjs CHANGED
@@ -1,47 +1 @@
1
- import { createAdapterFactory } from 'better-auth/adapters';
2
- import { createSqlAuthStore, d1Executor } from './sql-store.mjs';
3
-
4
- const asRow = (row) => row;
5
- const asRowOrNull = (row) => row ?? null;
6
- const asRows = (rows) => rows;
7
- const lunoraAuthAdapter = (store) => createAdapterFactory({
8
- adapter: () => {
9
- return {
10
- consumeOne: async ({ model, where }) => asRowOrNull(await store.consumeOne(model, where)),
11
- count: async ({ model, where }) => store.count(model, where ?? []),
12
- create: async ({ data, model }) => asRow(await store.create(model, data)),
13
- delete: async ({ model, where }) => {
14
- await store.remove(model, where);
15
- },
16
- deleteMany: async ({ model, where }) => store.remove(model, where),
17
- findMany: async ({ limit, model, offset, sortBy, where }) => asRows(await store.read(model, { limit, offset, sortBy, where: where ?? [] })),
18
- findOne: async ({ model, where }) => {
19
- const [row] = await store.read(model, { limit: 1, where });
20
- return asRowOrNull(row);
21
- },
22
- update: async ({ model, update, where }) => {
23
- const [row] = await store.update(model, where, update);
24
- return asRowOrNull(row);
25
- },
26
- updateMany: async ({ model, update, where }) => {
27
- const updated = await store.update(model, where, update);
28
- return updated.length;
29
- }
30
- };
31
- },
32
- config: {
33
- adapterId: "lunora",
34
- adapterName: "Lunora Adapter",
35
- // Conservative flags so the adapter is store-agnostic: better-auth
36
- // serializes dates/booleans/json to primitives (string/number) before a
37
- // write and parses them back after a read, so a store — in-memory or
38
- // SQL — only ever handles primitives, never schema-aware codecs.
39
- supportsBooleans: false,
40
- supportsDates: false,
41
- supportsJSON: false,
42
- supportsNumericIds: false
43
- }
44
- });
45
- const lunoraD1Adapter = (d1) => lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)));
46
-
47
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import"better-auth/adapters";import{s as p,l as e,w as l}from"./packem_shared/adapter-RvDcm0Zy.mjs";import"./sql-store.mjs";export{p as lunoraAuthAdapter,e as lunoraD1Adapter,l as lunoraDoAdapter};
@@ -0,0 +1,114 @@
1
+ import { SqlExecutor } from "./sql-store.mjs";
2
+ import "./store.mjs";
3
+ import 'better-auth/adapters';
4
+ /** Reserved append-only table backing the Studio "Security / audit" page. Auto-hidden from the data browser by the `__lunora` prefix. */
5
+ declare const AUTH_AUDIT_TABLE = "__lunora_auth_audit__";
6
+ /**
7
+ * Well-known auth/security event types. A plain `string` is also accepted so
8
+ * plugins can record their own events without a union change — the union just
9
+ * gives autocomplete for the common ones.
10
+ */
11
+ type AuthAuditEvent = "account-link" | "account-unlink" | "email-verification" | "mfa-disable" | "mfa-enable" | "password-change" | "password-reset" | "session-revoke" | "sign-in" | "sign-out" | "sign-up" | "token-refresh" | (string & {});
12
+ /** Whether the recorded operation succeeded or failed (e.g. a rejected sign-in). */
13
+ type AuthAuditOutcome = "failure" | "success";
14
+ /** One recorded auth/security event, in monotonic `seq` order. */
15
+ interface AuthAuditEntry {
16
+ /** Redaction is applied to `detail`, not this — the actor's email is intentional forensic data. Absent for anonymous/pre-auth events. */
17
+ actorEmail?: string;
18
+ /** The acting user's id, when known. */
19
+ actorId?: string;
20
+ /** JSON-decoded extra context, with secrets/PII redacted at write time; absent when none was recorded. */
21
+ detail?: Record<string, unknown>;
22
+ /** Auth event type, e.g. `sign-in` / `password-change`. */
23
+ event: string;
24
+ /** Client IP the event originated from, when resolvable. */
25
+ ip?: string;
26
+ /** Whether the operation succeeded or failed. */
27
+ outcome: AuthAuditOutcome;
28
+ /** Monotonic per-database cursor — strictly increasing, never reused. */
29
+ seq: number;
30
+ /** Wall-clock millis when the event was recorded. */
31
+ ts: number;
32
+ /** Client User-Agent, when present on the request. */
33
+ userAgent?: string;
34
+ }
35
+ /** Fields accepted when appending one event; `seq` is assigned by the table. */
36
+ interface AppendAuthAuditEntry {
37
+ actorEmail?: string;
38
+ actorId?: string;
39
+ detail?: Record<string, unknown>;
40
+ event: string;
41
+ ip?: string;
42
+ outcome: AuthAuditOutcome;
43
+ ts: number;
44
+ userAgent?: string;
45
+ }
46
+ /** Options for {@link appendAuthAuditEntry}. */
47
+ interface AppendAuthAuditOptions {
48
+ /**
49
+ * Redact secrets/PII in the `detail` payload before persisting. Defaults to
50
+ * `true`. Set `false` only for a trusted, pre-scrubbed payload.
51
+ */
52
+ redactDetail?: boolean;
53
+ /**
54
+ * Keep only the most recent `retention` rows (trimmed after each append),
55
+ * mirroring the admin audit log's bounded retention. Omit for an unbounded
56
+ * trail (the compliance default) — deliberately NOT capped at 1000.
57
+ */
58
+ retention?: number;
59
+ }
60
+ /** Options for {@link readAuthAuditLog}. */
61
+ interface ReadAuthAuditOptions {
62
+ /** Return only events for this actor id. */
63
+ actorId?: string;
64
+ /** Return only events of this type. */
65
+ event?: string;
66
+ /** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
67
+ limit?: number;
68
+ /** Return only events with `seq` strictly greater than this (forward paging). */
69
+ sinceSeq?: number;
70
+ }
71
+ /**
72
+ * Create the `__lunora_auth_audit__` table. `seq` is an `AUTOINCREMENT` primary
73
+ * key giving the database a monotonic cursor the Security page pages through.
74
+ * Idempotent, so read and write paths can call it defensively.
75
+ */
76
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
77
+ /**
78
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
79
+ * when `retention` is set — trimming the log back to the most recent rows.
80
+ * Creates the table first so callers needn't. Returns the redacted, persisted
81
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
82
+ */
83
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
84
+ /**
85
+ * Read audit events newest-first, optionally filtered by `actorId` / `event` and
86
+ * paged past `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's
87
+ * `detail` JSON back into an object. Creates the table first so reads on a
88
+ * never-audited database return `[]` instead of throwing.
89
+ */
90
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
91
+ /**
92
+ * The auth/security audit read plane the runtime's `authAuditReader` option
93
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
94
+ * its admin gate to back the studio's "Security / audit" page
95
+ * (`__lunora_admin__:getAuthAuditLog`).
96
+ */
97
+ interface AuthAuditReader {
98
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
99
+ }
100
+ /**
101
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
102
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
103
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
104
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
105
+ *
106
+ * ```ts
107
+ * export default createWorker({
108
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
109
+ * // …
110
+ * });
111
+ * ```
112
+ */
113
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
114
+ export { AUTH_AUDIT_TABLE, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEntry, type AuthAuditEvent, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog };
@@ -0,0 +1,114 @@
1
+ import { SqlExecutor } from "./sql-store.js";
2
+ import "./store.js";
3
+ import 'better-auth/adapters';
4
+ /** Reserved append-only table backing the Studio "Security / audit" page. Auto-hidden from the data browser by the `__lunora` prefix. */
5
+ declare const AUTH_AUDIT_TABLE = "__lunora_auth_audit__";
6
+ /**
7
+ * Well-known auth/security event types. A plain `string` is also accepted so
8
+ * plugins can record their own events without a union change — the union just
9
+ * gives autocomplete for the common ones.
10
+ */
11
+ type AuthAuditEvent = "account-link" | "account-unlink" | "email-verification" | "mfa-disable" | "mfa-enable" | "password-change" | "password-reset" | "session-revoke" | "sign-in" | "sign-out" | "sign-up" | "token-refresh" | (string & {});
12
+ /** Whether the recorded operation succeeded or failed (e.g. a rejected sign-in). */
13
+ type AuthAuditOutcome = "failure" | "success";
14
+ /** One recorded auth/security event, in monotonic `seq` order. */
15
+ interface AuthAuditEntry {
16
+ /** Redaction is applied to `detail`, not this — the actor's email is intentional forensic data. Absent for anonymous/pre-auth events. */
17
+ actorEmail?: string;
18
+ /** The acting user's id, when known. */
19
+ actorId?: string;
20
+ /** JSON-decoded extra context, with secrets/PII redacted at write time; absent when none was recorded. */
21
+ detail?: Record<string, unknown>;
22
+ /** Auth event type, e.g. `sign-in` / `password-change`. */
23
+ event: string;
24
+ /** Client IP the event originated from, when resolvable. */
25
+ ip?: string;
26
+ /** Whether the operation succeeded or failed. */
27
+ outcome: AuthAuditOutcome;
28
+ /** Monotonic per-database cursor — strictly increasing, never reused. */
29
+ seq: number;
30
+ /** Wall-clock millis when the event was recorded. */
31
+ ts: number;
32
+ /** Client User-Agent, when present on the request. */
33
+ userAgent?: string;
34
+ }
35
+ /** Fields accepted when appending one event; `seq` is assigned by the table. */
36
+ interface AppendAuthAuditEntry {
37
+ actorEmail?: string;
38
+ actorId?: string;
39
+ detail?: Record<string, unknown>;
40
+ event: string;
41
+ ip?: string;
42
+ outcome: AuthAuditOutcome;
43
+ ts: number;
44
+ userAgent?: string;
45
+ }
46
+ /** Options for {@link appendAuthAuditEntry}. */
47
+ interface AppendAuthAuditOptions {
48
+ /**
49
+ * Redact secrets/PII in the `detail` payload before persisting. Defaults to
50
+ * `true`. Set `false` only for a trusted, pre-scrubbed payload.
51
+ */
52
+ redactDetail?: boolean;
53
+ /**
54
+ * Keep only the most recent `retention` rows (trimmed after each append),
55
+ * mirroring the admin audit log's bounded retention. Omit for an unbounded
56
+ * trail (the compliance default) — deliberately NOT capped at 1000.
57
+ */
58
+ retention?: number;
59
+ }
60
+ /** Options for {@link readAuthAuditLog}. */
61
+ interface ReadAuthAuditOptions {
62
+ /** Return only events for this actor id. */
63
+ actorId?: string;
64
+ /** Return only events of this type. */
65
+ event?: string;
66
+ /** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
67
+ limit?: number;
68
+ /** Return only events with `seq` strictly greater than this (forward paging). */
69
+ sinceSeq?: number;
70
+ }
71
+ /**
72
+ * Create the `__lunora_auth_audit__` table. `seq` is an `AUTOINCREMENT` primary
73
+ * key giving the database a monotonic cursor the Security page pages through.
74
+ * Idempotent, so read and write paths can call it defensively.
75
+ */
76
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
77
+ /**
78
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
79
+ * when `retention` is set — trimming the log back to the most recent rows.
80
+ * Creates the table first so callers needn't. Returns the redacted, persisted
81
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
82
+ */
83
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
84
+ /**
85
+ * Read audit events newest-first, optionally filtered by `actorId` / `event` and
86
+ * paged past `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's
87
+ * `detail` JSON back into an object. Creates the table first so reads on a
88
+ * never-audited database return `[]` instead of throwing.
89
+ */
90
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
91
+ /**
92
+ * The auth/security audit read plane the runtime's `authAuditReader` option
93
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
94
+ * its admin gate to back the studio's "Security / audit" page
95
+ * (`__lunora_admin__:getAuthAuditLog`).
96
+ */
97
+ interface AuthAuditReader {
98
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
99
+ }
100
+ /**
101
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
102
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
103
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
104
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
105
+ *
106
+ * ```ts
107
+ * export default createWorker({
108
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
109
+ * // …
110
+ * });
111
+ * ```
112
+ */
113
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
114
+ export { AUTH_AUDIT_TABLE, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEntry, type AuthAuditEvent, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog };
package/dist/audit.mjs ADDED
@@ -0,0 +1,11 @@
1
+ import{redact as A,standardRules as _,piiRules as v}from"@visulima/redact";const n="__lunora_auth_audit__",R=[..._,...v],N=1e3,L=1e4,u=null,s=t=>{if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean")return String(t)},m=async t=>{await t.run(`CREATE TABLE IF NOT EXISTS "${n}" (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ event TEXT NOT NULL,
5
+ outcome TEXT NOT NULL,
6
+ actor_id TEXT,
7
+ actor_email TEXT,
8
+ ip TEXT,
9
+ user_agent TEXT,
10
+ detail TEXT
11
+ )`,[])},O=async(t,e,r={})=>{await m(t);let i;return e.detail!==void 0&&(i=r.redactDetail===!1?e.detail:A(e.detail,R)),await t.run(`INSERT INTO "${n}" (ts, event, outcome, actor_id, actor_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[e.ts,e.event,e.outcome,e.actorId??u,e.actorEmail??u,e.ip??u,e.userAgent??u,i===void 0?u:JSON.stringify(i)]),typeof r.retention=="number"&&r.retention>0&&await t.run(`DELETE FROM "${n}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${n}")`,[r.retention]),{...e,detail:i}},I=async(t,e={})=>{await m(t);const r=Math.max(1,Math.min(e.limit??N,L)),i=["seq > ?"],d=[e.sinceSeq??0];return e.actorId!==void 0&&(i.push("actor_id = ?"),d.push(e.actorId)),e.event!==void 0&&(i.push("event = ?"),d.push(e.event)),d.push(r),(await t.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, ip, user_agent, detail FROM "${n}" WHERE ${i.join(" AND ")} ORDER BY seq DESC LIMIT ?`,d)).map(a=>{const o={event:s(a.event)??"",outcome:a.outcome==="failure"?"failure":"success",seq:Number(a.seq),ts:Number(a.ts)},E=s(a.actor_id),c=s(a.actor_email),T=s(a.ip),l=s(a.user_agent),p=s(a.detail);return E!==void 0&&(o.actorId=E),c!==void 0&&(o.actorEmail=c),T!==void 0&&(o.ip=T),l!==void 0&&(o.userAgent=l),p!==void 0&&(o.detail=JSON.parse(p)),o})},h=t=>({read:e=>I(t,e)});export{n as AUTH_AUDIT_TABLE,O as appendAuthAuditEntry,h as createAuthAuditReader,m as ensureAuthAuditTable,I as readAuthAuditLog};
@@ -0,0 +1,122 @@
1
+ import { Middleware } from '@lunora/server';
2
+ /**
3
+ * The resolved trust class of an email address' domain: `disposable` (a
4
+ * throwaway/temporary provider, or a caller `denyDomains` hit), `free` (a free
5
+ * consumer provider like Gmail — deliverable but not B2B), or `business`
6
+ * (anything else — a custom/company domain, or an `allowDomains` hit).
7
+ */
8
+ type EmailClass = "business" | "disposable" | "free";
9
+ /** Result of {@link classifyEmail} — the resolved class plus the normalized domain. */
10
+ interface EmailClassification {
11
+ /** The normalized (lowercased, trimmed) domain, or `undefined` for a structurally invalid address. */
12
+ domain: string | undefined;
13
+ /** The resolved trust class. A structurally invalid address resolves to `business` with `domain: undefined`. */
14
+ emailClass: EmailClass;
15
+ }
16
+ /** Configuration for {@link classifyEmail} / {@link assertEmailAllowed} / {@link emailGateMiddleware}. */
17
+ interface EmailGateConfig {
18
+ /**
19
+ * Domains that are always allowed and always classified `business`, even if
20
+ * they appear on the disposable or free lists. Wildcard/subdomain aware
21
+ * (`example.com` also allows `mail.example.com`). Your own hosted domains go
22
+ * here.
23
+ */
24
+ allowDomains?: ReadonlyArray<string>;
25
+ /**
26
+ * Reject disposable/throwaway signups. Defaults to `true` — the whole point
27
+ * of the gate. Set `false` to classify-only (surface `emailClass` without
28
+ * blocking).
29
+ */
30
+ blockDisposable?: boolean;
31
+ /**
32
+ * Extra domains to treat as disposable (blocked when `blockDisposable`), on
33
+ * top of the built-in list. Wildcard/subdomain aware.
34
+ */
35
+ denyDomains?: ReadonlyArray<string>;
36
+ /**
37
+ * Reserved for callers that branch on free-vs-business (e.g. gate a feature
38
+ * behind a business email). Purely advisory — {@link EmailClassification}'s
39
+ * `emailClass` already reports `free`, so this flag exists for symmetry/intent
40
+ * and never blocks. Defaults to `false`.
41
+ */
42
+ flagFreeEmail?: boolean;
43
+ /**
44
+ * Opt-in MX deliverability verification. Off by default because it needs DNS
45
+ * (`@visulima/email-verifier/checks/mx` → `node:dns`), which is not available
46
+ * on the default workerd path. When `true`, {@link assertEmailAllowed} rejects
47
+ * an address whose domain publishes no MX (or fallback A/AAAA) records with
48
+ * `EMAIL_UNDELIVERABLE`. The check is loaded via a dynamic import, so leaving
49
+ * this off keeps the DNS module out of the bundle entirely.
50
+ */
51
+ mx?: boolean;
52
+ /**
53
+ * Reject structurally invalid addresses up front (via
54
+ * `@visulima/email-verifier/checks/syntax`, pure-data/edge-safe). Defaults to
55
+ * `true`. When `false`, an unparseable address classifies as `business` with
56
+ * `domain: undefined` and is not rejected on syntax alone.
57
+ */
58
+ requireValidSyntax?: boolean;
59
+ }
60
+ /** Options for {@link emailGateMiddleware}: the base gate config plus how to read the email from `ctx`. */
61
+ interface EmailGateMiddlewareOptions<Context> extends EmailGateConfig {
62
+ /**
63
+ * Selector that pulls the signup email from `ctx`. The procedure context
64
+ * carries only the resolved identity, not the raw request body, so route the
65
+ * email through the function `args` and read it out here (mirrors
66
+ * `verifyTurnstileMiddleware`'s `token` selector).
67
+ */
68
+ email: (context: Context) => string | undefined;
69
+ /**
70
+ * Called with the resolved classification once the gate passes, so app policy
71
+ * can branch on `free` vs `business` (e.g. gate a plan behind a business
72
+ * email). Never fires when the gate rejects.
73
+ */
74
+ onClassify?: (classification: EmailClassification, context: Context) => void;
75
+ }
76
+ /**
77
+ * Inject the built-in disposable + free domain lists into the lookup packages,
78
+ * once. Call this at worker init on workerd (where the packages' `node:fs`
79
+ * loader is unavailable) so {@link classifyEmail} has data to match against;
80
+ * {@link assertEmailAllowed} / {@link emailGateMiddleware} await it for you, so
81
+ * the gating path is always edge-safe. Idempotent — repeat calls share one load.
82
+ */
83
+ declare const loadEmailDomainLists: () => Promise<void>;
84
+ /**
85
+ * Classify an email address' domain as `disposable` / `free` / `business`,
86
+ * pure-data and edge-safe (no DNS, no filesystem). A structurally invalid
87
+ * address resolves to `{ domain: undefined, emailClass: "business" }` — use
88
+ * {@link assertEmailAllowed} (which can reject on syntax) for the gating path.
89
+ * `allowDomains` wins over both lists; `denyDomains` adds to the disposable list.
90
+ *
91
+ * The lookup relies on the built-in domain lists being loaded. On Node they
92
+ * auto-load from disk; on workerd, `await loadEmailDomainLists()` first (or use
93
+ * {@link assertEmailAllowed} / {@link emailGateMiddleware}, which await it).
94
+ */
95
+ declare const classifyEmail: (email: string, config?: EmailGateConfig) => EmailClassification;
96
+ /**
97
+ * Classify `email` and enforce the gate, throwing a coded {@link LunoraError}
98
+ * when it fails: `VALIDATION_ERROR` (structurally invalid, only when
99
+ * `requireValidSyntax`, the default), `EMAIL_DOMAIN_BLOCKED` (disposable or
100
+ * deny-listed, only when `blockDisposable`, the default), or `EMAIL_UNDELIVERABLE`
101
+ * (no MX records, only when `mx: true`).
102
+ *
103
+ * Returns the {@link EmailClassification} on success so callers can branch on
104
+ * `free` vs `business`. Async only because of the opt-in MX step; with `mx` off
105
+ * it resolves without any network I/O.
106
+ */
107
+ declare const assertEmailAllowed: (email: string, config?: EmailGateConfig) => Promise<EmailClassification>;
108
+ /**
109
+ * Lunora procedure middleware that gates a non-auth, signup-shaped
110
+ * `mutation`/`action` on the email-domain policy. Attach it with `.use()`; it
111
+ * reads the email from `ctx` via the `email` selector (route it through `args`)
112
+ * and runs {@link assertEmailAllowed}, which throws a coded {@link LunoraError}
113
+ * (`EMAIL_DOMAIN_BLOCKED` / `EMAIL_UNDELIVERABLE` / `VALIDATION_ERROR`) the
114
+ * runtime maps to the matching status.
115
+ *
116
+ * To gate better-auth's native `/sign-up/email` endpoint instead, use
117
+ * `emailGateDatabaseHooks` / `withEmailGate` from `@lunora/auth` — those hook
118
+ * better-auth's own user-create path. The `Middleware` import is type-only, so
119
+ * this stays free of any runtime `@lunora/server` dependency.
120
+ */
121
+ declare const emailGateMiddleware: <Context>(options: EmailGateMiddlewareOptions<Context>) => Middleware<Context, Context>;
122
+ export { type EmailClass, type EmailClassification, type EmailGateConfig, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists };