@lunora/auth 1.0.0-alpha.35 → 1.0.0-alpha.36

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/README.md CHANGED
@@ -88,6 +88,61 @@ better-auth's plugin factories are re-exported from `@lunora/auth/plugins` (so y
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
@@ -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,111 @@
1
+ import { redact, standardRules, piiRules } from '@visulima/redact';
2
+
3
+ const AUTH_AUDIT_TABLE = "__lunora_auth_audit__";
4
+ const AUDIT_REDACT_RULES = [...standardRules, ...piiRules];
5
+ const DEFAULT_READ_LIMIT = 1e3;
6
+ const MAX_READ_LIMIT = 1e4;
7
+ const SQL_NULL = null;
8
+ const text = (value) => {
9
+ if (typeof value === "string") {
10
+ return value;
11
+ }
12
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
13
+ return String(value);
14
+ }
15
+ return void 0;
16
+ };
17
+ const ensureAuthAuditTable = async (executor) => {
18
+ await executor.run(
19
+ `CREATE TABLE IF NOT EXISTS "${AUTH_AUDIT_TABLE}" (
20
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ ts REAL NOT NULL,
22
+ event TEXT NOT NULL,
23
+ outcome TEXT NOT NULL,
24
+ actor_id TEXT,
25
+ actor_email TEXT,
26
+ ip TEXT,
27
+ user_agent TEXT,
28
+ detail TEXT
29
+ )`,
30
+ []
31
+ );
32
+ };
33
+ const appendAuthAuditEntry = async (executor, entry, options = {}) => {
34
+ await ensureAuthAuditTable(executor);
35
+ let detail;
36
+ if (entry.detail !== void 0) {
37
+ detail = options.redactDetail === false ? entry.detail : redact(entry.detail, AUDIT_REDACT_RULES);
38
+ }
39
+ await executor.run(
40
+ `INSERT INTO "${AUTH_AUDIT_TABLE}" (ts, event, outcome, actor_id, actor_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
41
+ [
42
+ entry.ts,
43
+ entry.event,
44
+ entry.outcome,
45
+ entry.actorId ?? SQL_NULL,
46
+ entry.actorEmail ?? SQL_NULL,
47
+ entry.ip ?? SQL_NULL,
48
+ entry.userAgent ?? SQL_NULL,
49
+ detail === void 0 ? SQL_NULL : JSON.stringify(detail)
50
+ ]
51
+ );
52
+ if (typeof options.retention === "number" && options.retention > 0) {
53
+ await executor.run(`DELETE FROM "${AUTH_AUDIT_TABLE}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${AUTH_AUDIT_TABLE}")`, [options.retention]);
54
+ }
55
+ return { ...entry, detail };
56
+ };
57
+ const readAuthAuditLog = async (executor, options = {}) => {
58
+ await ensureAuthAuditTable(executor);
59
+ const limit = Math.max(1, Math.min(options.limit ?? DEFAULT_READ_LIMIT, MAX_READ_LIMIT));
60
+ const clauses = ["seq > ?"];
61
+ const parameters = [options.sinceSeq ?? 0];
62
+ if (options.actorId !== void 0) {
63
+ clauses.push("actor_id = ?");
64
+ parameters.push(options.actorId);
65
+ }
66
+ if (options.event !== void 0) {
67
+ clauses.push("event = ?");
68
+ parameters.push(options.event);
69
+ }
70
+ parameters.push(limit);
71
+ const rows = await executor.all(
72
+ `SELECT seq, ts, event, outcome, actor_id, actor_email, ip, user_agent, detail FROM "${AUTH_AUDIT_TABLE}" WHERE ${clauses.join(" AND ")} ORDER BY seq DESC LIMIT ?`,
73
+ parameters
74
+ );
75
+ return rows.map((row) => {
76
+ const base = {
77
+ event: text(row["event"]) ?? "",
78
+ outcome: row["outcome"] === "failure" ? "failure" : "success",
79
+ seq: Number(row["seq"]),
80
+ ts: Number(row["ts"])
81
+ };
82
+ const actorId = text(row["actor_id"]);
83
+ const actorEmail = text(row["actor_email"]);
84
+ const ip = text(row["ip"]);
85
+ const userAgent = text(row["user_agent"]);
86
+ const detail = text(row["detail"]);
87
+ if (actorId !== void 0) {
88
+ base.actorId = actorId;
89
+ }
90
+ if (actorEmail !== void 0) {
91
+ base.actorEmail = actorEmail;
92
+ }
93
+ if (ip !== void 0) {
94
+ base.ip = ip;
95
+ }
96
+ if (userAgent !== void 0) {
97
+ base.userAgent = userAgent;
98
+ }
99
+ if (detail !== void 0) {
100
+ base.detail = JSON.parse(detail);
101
+ }
102
+ return base;
103
+ });
104
+ };
105
+ const createAuthAuditReader = (executor) => {
106
+ return {
107
+ read: (options) => readAuthAuditLog(executor, options)
108
+ };
109
+ };
110
+
111
+ export { AUTH_AUDIT_TABLE, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, 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 };
@@ -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 };
@@ -0,0 +1,71 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { isDisposableDomain, setDomains } from '@visulima/disposable-email-domains';
3
+ import { extractDomain, isFreeDomain, setDomains as setDomains$1 } from '@visulima/free-email-domains';
4
+
5
+ const listFromModule = (module) => {
6
+ const value = module.default ?? module;
7
+ return Array.isArray(value) ? value : [];
8
+ };
9
+ let listsPromise;
10
+ const loadEmailDomainLists = async () => {
11
+ listsPromise ??= (async () => {
12
+ const [disposable, free] = await Promise.all([import('@visulima/disposable-email-domains/domains'), import('@visulima/free-email-domains/domains')]);
13
+ setDomains(listFromModule(disposable));
14
+ setDomains$1(listFromModule(free));
15
+ })();
16
+ return listsPromise;
17
+ };
18
+ const toDomainSet = (domains) => domains && domains.length > 0 ? new Set(domains.map((domain) => domain.toLowerCase())) : void 0;
19
+ const classifyEmail = (email, config = {}) => {
20
+ const domain = extractDomain(email);
21
+ if (domain === void 0) {
22
+ return { domain: void 0, emailClass: "business" };
23
+ }
24
+ const allowDomains = toDomainSet(config.allowDomains);
25
+ if (isDisposableDomain(domain, { allowDomains, customDomains: toDomainSet(config.denyDomains) })) {
26
+ return { domain, emailClass: "disposable" };
27
+ }
28
+ if (isFreeDomain(domain, { allowDomains })) {
29
+ return { domain, emailClass: "free" };
30
+ }
31
+ return { domain, emailClass: "business" };
32
+ };
33
+ const verifyMx = async (domain) => {
34
+ const { checkMxRecords } = await import('@visulima/email-verifier/checks/mx');
35
+ const result = await checkMxRecords(domain);
36
+ return result.valid;
37
+ };
38
+ const assertEmailAllowed = async (email, config = {}) => {
39
+ if (config.requireValidSyntax !== false) {
40
+ const { validateSyntax } = await import('@visulima/email-verifier/checks/syntax');
41
+ if (!validateSyntax(email)) {
42
+ throw new LunoraError("VALIDATION_ERROR", `@lunora/auth: "${email}" is not a valid email address.`);
43
+ }
44
+ }
45
+ await loadEmailDomainLists();
46
+ const classification = classifyEmail(email, config);
47
+ if (classification.emailClass === "disposable" && config.blockDisposable !== false) {
48
+ throw new LunoraError(
49
+ "EMAIL_DOMAIN_BLOCKED",
50
+ `@lunora/auth: signups from the disposable/throwaway domain "${classification.domain ?? email}" are not allowed.`
51
+ );
52
+ }
53
+ if (config.mx === true && classification.domain !== void 0 && !await verifyMx(classification.domain)) {
54
+ throw new LunoraError(
55
+ "EMAIL_UNDELIVERABLE",
56
+ `@lunora/auth: the domain "${classification.domain}" publishes no MX records, so mail to it cannot be delivered.`
57
+ );
58
+ }
59
+ return classification;
60
+ };
61
+ const emailGateMiddleware = (options) => async ({ ctx, next }) => {
62
+ const email = options.email(ctx);
63
+ if (email === void 0 || email === "") {
64
+ throw new LunoraError("VALIDATION_ERROR", "@lunora/auth: emailGateMiddleware received no email to check.");
65
+ }
66
+ const classification = await assertEmailAllowed(email, options);
67
+ options.onClassify?.(classification, ctx);
68
+ return next();
69
+ };
70
+
71
+ export { assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists };
package/dist/index.d.mts CHANGED
@@ -2,10 +2,16 @@ export { lunoraAuthAdapter, lunoraD1Adapter } from "./adapter.mjs";
2
2
  import { LunoraError } from '@lunora/errors';
3
3
  import { L as LunoraAuth, a as LunoraAuthOptions } from "./packem_shared/create-auth.d-COcIS_KU.mjs";
4
4
  export { c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-COcIS_KU.mjs";
5
+ import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
6
+ export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
7
+ import { createAuthMiddleware } from 'better-auth/api';
8
+ import { SqlExecutor } from "./sql-store.mjs";
9
+ export { createSqlAuthStore, d1Executor } from "./sql-store.mjs";
10
+ import { BetterAuthOptions } from 'better-auth';
11
+ import { EmailClassification, EmailGateConfig } from "./email-guard.mjs";
12
+ export { type EmailClass, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists } from "./email-guard.mjs";
5
13
  export { type LunoraAuthApiContext, LunoraAuthHeadersError, type WithAuthPluginsMiddleware, type WithAuthPluginsOptions, withAuthPlugins } from "./middleware.mjs";
6
14
  export { default as authTables } from "./schema.mjs";
7
- import { BetterAuthOptions } from 'better-auth';
8
- export { type SqlExecutor, createSqlAuthStore, d1Executor } from "./sql-store.mjs";
9
15
  export { type AuthQuery, type AuthRow, type AuthStore, type AuthWhereClause, createMemoryAuthStore, matchesWhere } from "./store.mjs";
10
16
  export { type FetchLike, TURNSTILE_VERIFY_ENDPOINT, type TurnstileVerifyResult, type VerifyTurnstileOptions, verifyTurnstile } from "./turnstile.mjs";
11
17
  export { type VerifyTurnstileMiddlewareOptions, verifyTurnstileMiddleware } from "./turnstile-middleware.mjs";
@@ -480,6 +486,121 @@ declare class LunoraAuthAdminError extends LunoraError {
480
486
  * config, etc. lazily); we memoize it so the first call pays the cost once.
481
487
  */
482
488
  declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
489
+ /** Configuration for {@link authAuditHook}. */
490
+ interface AuthAuditHookConfig extends AppendAuthAuditOptions {
491
+ /**
492
+ * Where to persist the trail — the same {@link SqlExecutor} seam better-auth's
493
+ * store rides (`d1Executor(env.DB)`), so events land in the auth D1 database.
494
+ */
495
+ executor: SqlExecutor;
496
+ /**
497
+ * Optional export tap (pairs with SIEM forwarding): called with each redacted
498
+ * entry right after it is persisted, so a deployment can fan events out to an
499
+ * external sink. Rejections/throws are swallowed so forwarding can't break an
500
+ * auth request.
501
+ */
502
+ onRecord?: (entry: AppendAuthAuditEntry) => Promise<void> | void;
503
+ }
504
+ /** Structural view of the fields we read off better-auth's after-hook context — kept loose to avoid coupling to internal types. */
505
+ interface AuditHookContext {
506
+ context?: {
507
+ newSession?: {
508
+ session?: {
509
+ userId?: string;
510
+ };
511
+ user?: {
512
+ email?: string;
513
+ id?: string;
514
+ };
515
+ } | null;
516
+ returned?: unknown;
517
+ session?: {
518
+ session?: {
519
+ userId?: string;
520
+ };
521
+ user?: {
522
+ email?: string;
523
+ id?: string;
524
+ };
525
+ } | null;
526
+ };
527
+ headers?: Headers;
528
+ path?: string;
529
+ request?: Request;
530
+ }
531
+ /**
532
+ * Map a better-auth endpoint path to the security event it represents, or
533
+ * `undefined` for endpoints not worth auditing (session reads, config, …). Match
534
+ * is by suffix so a caller `basePath` prefix (`/api/auth`) never affects it.
535
+ */
536
+ declare const eventForPath: (path: string) => AuthAuditEvent | undefined;
537
+ /**
538
+ * Build the entry a given after-hook context should record, or `undefined` when
539
+ * the path is not an audited security event. Exported for direct unit testing of
540
+ * the classification/extraction without spinning up better-auth.
541
+ */
542
+ declare const buildAuditEntry: (context: AuditHookContext, now?: number) => AppendAuthAuditEntry | undefined;
543
+ /**
544
+ * Create the better-auth `hooks.after` middleware that records the auth/security
545
+ * audit trail. Assign it to `hooks.after` (or compose via {@link withAuthAudit}).
546
+ *
547
+ * ```ts
548
+ * const auth = createAuth({
549
+ * secret: env.AUTH_SECRET,
550
+ * database: lunoraD1Adapter(env.DB),
551
+ * hooks: { after: authAuditHook({ executor: d1Executor(env.DB), retention: 100_000 }) },
552
+ * });
553
+ * ```
554
+ */
555
+ declare const authAuditHook: (config: AuthAuditHookConfig) => ReturnType<typeof createAuthMiddleware>;
556
+ /**
557
+ * Merge the audit `hooks.after` middleware into a better-auth options object,
558
+ * composing with any `hooks.after` the caller already set (theirs runs first,
559
+ * then the audit record). Returns a new options object.
560
+ */
561
+ declare const withAuthAudit: <Options extends {
562
+ hooks?: {
563
+ after?: unknown;
564
+ };
565
+ }>(options: Options, config: AuthAuditHookConfig) => Options;
566
+ /** better-auth's `databaseHooks` shape, derived so a rename upstream fails to compile rather than silently mis-hooking. */
567
+ type DatabaseHooks = NonNullable<BetterAuthOptions["databaseHooks"]>;
568
+ /** Config for the signup gate hooks: the base {@link EmailGateConfig} plus an optional classification tap. */
569
+ interface EmailGateHookConfig extends EmailGateConfig {
570
+ /**
571
+ * Called with the resolved classification once the gate passes, so app policy
572
+ * can react to `free` vs `business` at signup (e.g. tag the account). Never
573
+ * fires when the gate rejects. `context` is better-auth's endpoint context
574
+ * (`null` outside a request, e.g. an internal create).
575
+ */
576
+ onClassify?: (classification: EmailClassification, user: Record<string, unknown>, context: unknown) => void;
577
+ }
578
+ /**
579
+ * Produce a `databaseHooks` fragment that gates better-auth's native signup on
580
+ * the email-domain policy. Spread it into `createAuth({ databaseHooks: … })`, or
581
+ * use {@link withEmailGate} to merge it (composing with any existing
582
+ * `user.create.before`).
583
+ *
584
+ * ```ts
585
+ * const auth = createAuth({
586
+ * secret: env.AUTH_SECRET,
587
+ * database: lunoraD1Adapter(env.DB),
588
+ * databaseHooks: emailGateDatabaseHooks({ blockDisposable: true }),
589
+ * });
590
+ * ```
591
+ */
592
+ declare const emailGateDatabaseHooks: (config?: EmailGateHookConfig) => DatabaseHooks;
593
+ /**
594
+ * Merge the email-domain signup gate into an existing better-auth options object,
595
+ * preserving any `databaseHooks` the caller already set. If they already declared
596
+ * a `user.create.before`, the gate runs first (rejecting disposable signups
597
+ * before their hook sees them), then theirs runs on the (possibly rewritten) user.
598
+ *
599
+ * ```ts
600
+ * const auth = createAuth(withEmailGate({ secret, database }, { blockDisposable: true }));
601
+ * ```
602
+ */
603
+ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHookConfig) => BetterAuthOptions;
483
604
  /**
484
605
  * Default basePath used by better-auth's client + handler. Override via the
485
606
  * second argument if you mount the auth routes somewhere else.
@@ -576,4 +697,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
576
697
  * with the same 60s cookie cache as `rolling`.
577
698
  */
578
699
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
579
- export { type AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthCapabilities, type AuthConfigInfo, type AuthInvitation, type AuthMember, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, type LunoraAuthOptions, type SessionPolicy, compileMigrationsSql, createAuthAdmin, ensureMigrated, handleAuthRequest, sessionPresets, validateSessionPolicy };
700
+ export { type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthCapabilities, type AuthConfigInfo, type AuthInvitation, type AuthMember, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, buildAuditEntry, compileMigrationsSql, createAuthAdmin, emailGateDatabaseHooks, ensureMigrated, eventForPath, handleAuthRequest, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.d.ts CHANGED
@@ -2,10 +2,16 @@ export { lunoraAuthAdapter, lunoraD1Adapter } from "./adapter.js";
2
2
  import { LunoraError } from '@lunora/errors';
3
3
  import { L as LunoraAuth, a as LunoraAuthOptions } from "./packem_shared/create-auth.d-COcIS_KU.js";
4
4
  export { c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-COcIS_KU.js";
5
+ import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
6
+ export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
7
+ import { createAuthMiddleware } from 'better-auth/api';
8
+ import { SqlExecutor } from "./sql-store.js";
9
+ export { createSqlAuthStore, d1Executor } from "./sql-store.js";
10
+ import { BetterAuthOptions } from 'better-auth';
11
+ import { EmailClassification, EmailGateConfig } from "./email-guard.js";
12
+ export { type EmailClass, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists } from "./email-guard.js";
5
13
  export { type LunoraAuthApiContext, LunoraAuthHeadersError, type WithAuthPluginsMiddleware, type WithAuthPluginsOptions, withAuthPlugins } from "./middleware.js";
6
14
  export { default as authTables } from "./schema.js";
7
- import { BetterAuthOptions } from 'better-auth';
8
- export { type SqlExecutor, createSqlAuthStore, d1Executor } from "./sql-store.js";
9
15
  export { type AuthQuery, type AuthRow, type AuthStore, type AuthWhereClause, createMemoryAuthStore, matchesWhere } from "./store.js";
10
16
  export { type FetchLike, TURNSTILE_VERIFY_ENDPOINT, type TurnstileVerifyResult, type VerifyTurnstileOptions, verifyTurnstile } from "./turnstile.js";
11
17
  export { type VerifyTurnstileMiddlewareOptions, verifyTurnstileMiddleware } from "./turnstile-middleware.js";
@@ -480,6 +486,121 @@ declare class LunoraAuthAdminError extends LunoraError {
480
486
  * config, etc. lazily); we memoize it so the first call pays the cost once.
481
487
  */
482
488
  declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
489
+ /** Configuration for {@link authAuditHook}. */
490
+ interface AuthAuditHookConfig extends AppendAuthAuditOptions {
491
+ /**
492
+ * Where to persist the trail — the same {@link SqlExecutor} seam better-auth's
493
+ * store rides (`d1Executor(env.DB)`), so events land in the auth D1 database.
494
+ */
495
+ executor: SqlExecutor;
496
+ /**
497
+ * Optional export tap (pairs with SIEM forwarding): called with each redacted
498
+ * entry right after it is persisted, so a deployment can fan events out to an
499
+ * external sink. Rejections/throws are swallowed so forwarding can't break an
500
+ * auth request.
501
+ */
502
+ onRecord?: (entry: AppendAuthAuditEntry) => Promise<void> | void;
503
+ }
504
+ /** Structural view of the fields we read off better-auth's after-hook context — kept loose to avoid coupling to internal types. */
505
+ interface AuditHookContext {
506
+ context?: {
507
+ newSession?: {
508
+ session?: {
509
+ userId?: string;
510
+ };
511
+ user?: {
512
+ email?: string;
513
+ id?: string;
514
+ };
515
+ } | null;
516
+ returned?: unknown;
517
+ session?: {
518
+ session?: {
519
+ userId?: string;
520
+ };
521
+ user?: {
522
+ email?: string;
523
+ id?: string;
524
+ };
525
+ } | null;
526
+ };
527
+ headers?: Headers;
528
+ path?: string;
529
+ request?: Request;
530
+ }
531
+ /**
532
+ * Map a better-auth endpoint path to the security event it represents, or
533
+ * `undefined` for endpoints not worth auditing (session reads, config, …). Match
534
+ * is by suffix so a caller `basePath` prefix (`/api/auth`) never affects it.
535
+ */
536
+ declare const eventForPath: (path: string) => AuthAuditEvent | undefined;
537
+ /**
538
+ * Build the entry a given after-hook context should record, or `undefined` when
539
+ * the path is not an audited security event. Exported for direct unit testing of
540
+ * the classification/extraction without spinning up better-auth.
541
+ */
542
+ declare const buildAuditEntry: (context: AuditHookContext, now?: number) => AppendAuthAuditEntry | undefined;
543
+ /**
544
+ * Create the better-auth `hooks.after` middleware that records the auth/security
545
+ * audit trail. Assign it to `hooks.after` (or compose via {@link withAuthAudit}).
546
+ *
547
+ * ```ts
548
+ * const auth = createAuth({
549
+ * secret: env.AUTH_SECRET,
550
+ * database: lunoraD1Adapter(env.DB),
551
+ * hooks: { after: authAuditHook({ executor: d1Executor(env.DB), retention: 100_000 }) },
552
+ * });
553
+ * ```
554
+ */
555
+ declare const authAuditHook: (config: AuthAuditHookConfig) => ReturnType<typeof createAuthMiddleware>;
556
+ /**
557
+ * Merge the audit `hooks.after` middleware into a better-auth options object,
558
+ * composing with any `hooks.after` the caller already set (theirs runs first,
559
+ * then the audit record). Returns a new options object.
560
+ */
561
+ declare const withAuthAudit: <Options extends {
562
+ hooks?: {
563
+ after?: unknown;
564
+ };
565
+ }>(options: Options, config: AuthAuditHookConfig) => Options;
566
+ /** better-auth's `databaseHooks` shape, derived so a rename upstream fails to compile rather than silently mis-hooking. */
567
+ type DatabaseHooks = NonNullable<BetterAuthOptions["databaseHooks"]>;
568
+ /** Config for the signup gate hooks: the base {@link EmailGateConfig} plus an optional classification tap. */
569
+ interface EmailGateHookConfig extends EmailGateConfig {
570
+ /**
571
+ * Called with the resolved classification once the gate passes, so app policy
572
+ * can react to `free` vs `business` at signup (e.g. tag the account). Never
573
+ * fires when the gate rejects. `context` is better-auth's endpoint context
574
+ * (`null` outside a request, e.g. an internal create).
575
+ */
576
+ onClassify?: (classification: EmailClassification, user: Record<string, unknown>, context: unknown) => void;
577
+ }
578
+ /**
579
+ * Produce a `databaseHooks` fragment that gates better-auth's native signup on
580
+ * the email-domain policy. Spread it into `createAuth({ databaseHooks: … })`, or
581
+ * use {@link withEmailGate} to merge it (composing with any existing
582
+ * `user.create.before`).
583
+ *
584
+ * ```ts
585
+ * const auth = createAuth({
586
+ * secret: env.AUTH_SECRET,
587
+ * database: lunoraD1Adapter(env.DB),
588
+ * databaseHooks: emailGateDatabaseHooks({ blockDisposable: true }),
589
+ * });
590
+ * ```
591
+ */
592
+ declare const emailGateDatabaseHooks: (config?: EmailGateHookConfig) => DatabaseHooks;
593
+ /**
594
+ * Merge the email-domain signup gate into an existing better-auth options object,
595
+ * preserving any `databaseHooks` the caller already set. If they already declared
596
+ * a `user.create.before`, the gate runs first (rejecting disposable signups
597
+ * before their hook sees them), then theirs runs on the (possibly rewritten) user.
598
+ *
599
+ * ```ts
600
+ * const auth = createAuth(withEmailGate({ secret, database }, { blockDisposable: true }));
601
+ * ```
602
+ */
603
+ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHookConfig) => BetterAuthOptions;
483
604
  /**
484
605
  * Default basePath used by better-auth's client + handler. Override via the
485
606
  * second argument if you mount the auth routes somewhere else.
@@ -576,4 +697,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
576
697
  * with the same 60s cookie cache as `rolling`.
577
698
  */
578
699
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
579
- export { type AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthCapabilities, type AuthConfigInfo, type AuthInvitation, type AuthMember, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, type LunoraAuthOptions, type SessionPolicy, compileMigrationsSql, createAuthAdmin, ensureMigrated, handleAuthRequest, sessionPresets, validateSessionPolicy };
700
+ export { type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthCapabilities, type AuthConfigInfo, type AuthInvitation, type AuthMember, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, buildAuditEntry, compileMigrationsSql, createAuthAdmin, emailGateDatabaseHooks, ensureMigrated, eventForPath, handleAuthRequest, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.mjs CHANGED
@@ -1,6 +1,10 @@
1
1
  export { lunoraAuthAdapter, lunoraD1Adapter } from './adapter.mjs';
2
2
  export { LunoraAuthAdminError, createAuthAdmin } from './packem_shared/LunoraAuthAdminError-CReJPMkx.mjs';
3
+ export { AUTH_AUDIT_TABLE, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from './audit.mjs';
4
+ export { authAuditHook, buildAuditEntry, eventForPath, withAuthAudit } from './packem_shared/authAuditHook-3OJKhpQV.mjs';
3
5
  export { createAuth, resolveAuthOptions } from './packem_shared/createAuth-s4i7WhAh.mjs';
6
+ export { emailGateDatabaseHooks, withEmailGate } from './packem_shared/emailGateDatabaseHooks-BGS4uJM9.mjs';
7
+ export { assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists } from './email-guard.mjs';
4
8
  export { DEFAULT_AUTH_BASE_PATH, handleAuthRequest } from './packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs';
5
9
  export { LunoraAuthHeadersError, withAuthPlugins } from './middleware.mjs';
6
10
  export { compileMigrationsSql, ensureMigrated } from './packem_shared/compileMigrationsSql-Dl5N8z5q.mjs';
@@ -0,0 +1,119 @@
1
+ import { createAuthMiddleware } from 'better-auth/api';
2
+ import { appendAuthAuditEntry } from '../audit.mjs';
3
+
4
+ const eventForPath = (path) => {
5
+ const normalized = path.toLowerCase();
6
+ const ends = (suffix) => normalized === suffix || normalized.endsWith(suffix);
7
+ if (ends("/sign-up/email") || ends("/sign-up")) {
8
+ return "sign-up";
9
+ }
10
+ if (normalized.includes("/sign-in/")) {
11
+ return "sign-in";
12
+ }
13
+ if (ends("/sign-out")) {
14
+ return "sign-out";
15
+ }
16
+ if (ends("/change-password") || ends("/set-password")) {
17
+ return "password-change";
18
+ }
19
+ if (ends("/reset-password") || ends("/request-password-reset") || ends("/forget-password")) {
20
+ return "password-reset";
21
+ }
22
+ if (ends("/verify-email")) {
23
+ return "email-verification";
24
+ }
25
+ if (normalized.includes("/two-factor/enable") || normalized.includes("/totp/enable")) {
26
+ return "mfa-enable";
27
+ }
28
+ if (normalized.includes("/two-factor/disable") || normalized.includes("/totp/disable")) {
29
+ return "mfa-disable";
30
+ }
31
+ if (ends("/refresh-token") || ends("/token")) {
32
+ return "token-refresh";
33
+ }
34
+ if (ends("/revoke-session") || ends("/revoke-sessions") || ends("/revoke-other-sessions")) {
35
+ return "session-revoke";
36
+ }
37
+ if (ends("/link-social")) {
38
+ return "account-link";
39
+ }
40
+ if (ends("/unlink-account")) {
41
+ return "account-unlink";
42
+ }
43
+ return void 0;
44
+ };
45
+ const header = (context, name) => {
46
+ const value = context.headers?.get(name) ?? context.request?.headers.get(name);
47
+ return value ?? void 0;
48
+ };
49
+ const resolveIp = (context) => {
50
+ const forwarded = header(context, "x-forwarded-for");
51
+ return header(context, "cf-connecting-ip") ?? (forwarded === void 0 ? void 0 : forwarded.split(",")[0]?.trim()) ?? header(context, "x-real-ip");
52
+ };
53
+ const resolveActor = (context) => {
54
+ const source = context.context?.newSession ?? context.context?.session;
55
+ const actorId = source?.user?.id ?? source?.session?.userId;
56
+ const actorEmail = source?.user?.email;
57
+ return {
58
+ ...actorId === void 0 ? {} : { actorId },
59
+ ...actorEmail === void 0 ? {} : { actorEmail }
60
+ };
61
+ };
62
+ const resolveOutcome = (context) => {
63
+ const returned = context.context?.returned;
64
+ if (returned instanceof Error) {
65
+ return "failure";
66
+ }
67
+ if (typeof returned === "object" && returned !== null && "status" in returned) {
68
+ const status = Number(returned.status);
69
+ if (Number.isFinite(status) && status >= 400) {
70
+ return "failure";
71
+ }
72
+ }
73
+ return "success";
74
+ };
75
+ const buildAuditEntry = (context, now = Date.now()) => {
76
+ const event = context.path === void 0 ? void 0 : eventForPath(context.path);
77
+ if (event === void 0) {
78
+ return void 0;
79
+ }
80
+ const ip = resolveIp(context);
81
+ const userAgent = header(context, "user-agent");
82
+ return {
83
+ ...resolveActor(context),
84
+ event,
85
+ outcome: resolveOutcome(context),
86
+ ts: now,
87
+ ...ip === void 0 ? {} : { ip },
88
+ ...userAgent === void 0 ? {} : { userAgent },
89
+ detail: { path: context.path }
90
+ };
91
+ };
92
+ const authAuditHook = (config) => createAuthMiddleware(async (context) => {
93
+ try {
94
+ const entry = buildAuditEntry(context);
95
+ if (entry !== void 0) {
96
+ const persisted = await appendAuthAuditEntry(config.executor, entry, {
97
+ redactDetail: config.redactDetail,
98
+ retention: config.retention
99
+ });
100
+ if (config.onRecord !== void 0) {
101
+ await config.onRecord(persisted);
102
+ }
103
+ }
104
+ } catch (error) {
105
+ console.error("@lunora/auth: audit hook failed to record event", error);
106
+ }
107
+ return {};
108
+ });
109
+ const withAuthAudit = (options, config) => {
110
+ const audit = authAuditHook(config);
111
+ const existing = options.hooks?.after;
112
+ const after = existing ? async (context) => {
113
+ await existing(context);
114
+ return audit(context);
115
+ } : audit;
116
+ return { ...options, hooks: { ...options.hooks, after } };
117
+ };
118
+
119
+ export { authAuditHook, buildAuditEntry, eventForPath, withAuthAudit };
@@ -0,0 +1,64 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { APIError } from 'better-auth/api';
3
+ import { assertEmailAllowed } from '../email-guard.mjs';
4
+
5
+ const statusString = (status) => {
6
+ switch (status) {
7
+ case 400: {
8
+ return "BAD_REQUEST";
9
+ }
10
+ case 422: {
11
+ return "UNPROCESSABLE_ENTITY";
12
+ }
13
+ case 429: {
14
+ return "TOO_MANY_REQUESTS";
15
+ }
16
+ default: {
17
+ return "INTERNAL_SERVER_ERROR";
18
+ }
19
+ }
20
+ };
21
+ const buildBeforeHook = (config) => async (user, context) => {
22
+ const email = typeof user.email === "string" ? user.email : void 0;
23
+ if (email === void 0 || email === "") {
24
+ return;
25
+ }
26
+ let classification;
27
+ try {
28
+ classification = await assertEmailAllowed(email, config);
29
+ } catch (error) {
30
+ if (error instanceof LunoraError) {
31
+ throw new APIError(statusString(error.status), { code: error.code, message: error.message });
32
+ }
33
+ throw error;
34
+ }
35
+ config.onClassify?.(classification, user, context);
36
+ };
37
+ const emailGateDatabaseHooks = (config = {}) => {
38
+ return {
39
+ user: { create: { before: buildBeforeHook(config) } }
40
+ };
41
+ };
42
+ const withEmailGate = (options, config = {}) => {
43
+ const gate = buildBeforeHook(config);
44
+ const existing = options.databaseHooks?.user?.create?.before;
45
+ const before = existing ? async (user, context) => {
46
+ await gate(user, context);
47
+ return existing(user, context);
48
+ } : gate;
49
+ return {
50
+ ...options,
51
+ databaseHooks: {
52
+ ...options.databaseHooks,
53
+ user: {
54
+ ...options.databaseHooks?.user,
55
+ create: {
56
+ ...options.databaseHooks?.user?.create,
57
+ before
58
+ }
59
+ }
60
+ }
61
+ };
62
+ };
63
+
64
+ export { emailGateDatabaseHooks, withEmailGate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.35",
3
+ "version": "1.0.0-alpha.36",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -52,6 +52,14 @@
52
52
  "types": "./dist/middleware.d.ts",
53
53
  "import": "./dist/middleware.mjs"
54
54
  },
55
+ "./audit": {
56
+ "types": "./dist/audit.d.ts",
57
+ "import": "./dist/audit.mjs"
58
+ },
59
+ "./email-guard": {
60
+ "types": "./dist/email-guard.d.ts",
61
+ "import": "./dist/email-guard.mjs"
62
+ },
55
63
  "./turnstile": {
56
64
  "types": "./dist/turnstile.d.ts",
57
65
  "import": "./dist/turnstile.mjs"
@@ -83,9 +91,13 @@
83
91
  },
84
92
  "dependencies": {
85
93
  "@better-auth/passkey": "^1.6.23",
86
- "@lunora/errors": "1.0.0-alpha.6",
87
- "@lunora/server": "1.0.0-alpha.29",
88
- "@lunora/values": "1.0.0-alpha.9",
94
+ "@lunora/errors": "1.0.0-alpha.7",
95
+ "@lunora/server": "1.0.0-alpha.30",
96
+ "@lunora/values": "1.0.0-alpha.10",
97
+ "@visulima/disposable-email-domains": "1.0.1",
98
+ "@visulima/email-verifier": "1.0.1",
99
+ "@visulima/free-email-domains": "1.0.0",
100
+ "@visulima/redact": "3.0.0",
89
101
  "better-auth": "^1.6.23"
90
102
  },
91
103
  "engines": {