@lunora/auth 1.0.0-alpha.1 → 1.0.0-alpha.100

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 (70) hide show
  1. package/LICENSE.md +38 -0
  2. package/README.md +56 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/adapter.d.mts +4 -43
  5. package/dist/adapter.d.ts +4 -43
  6. package/dist/adapter.mjs +1 -47
  7. package/dist/audit.d.mts +131 -0
  8. package/dist/audit.d.ts +131 -0
  9. package/dist/audit.mjs +12 -0
  10. package/dist/email-guard.d.mts +125 -0
  11. package/dist/email-guard.d.ts +125 -0
  12. package/dist/email-guard.mjs +1 -0
  13. package/dist/index.d.mts +713 -147
  14. package/dist/index.d.ts +713 -147
  15. package/dist/index.mjs +1 -12
  16. package/dist/middleware.d.mts +157 -156
  17. package/dist/middleware.d.ts +157 -156
  18. package/dist/middleware.mjs +1 -53
  19. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-D-RB2XYs.mjs +1 -0
  20. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs +1 -0
  21. package/dist/packem_shared/LunoraAuthAdminError-DtAKa22S.mjs +1 -0
  22. package/dist/packem_shared/adapter-DA8DdALX.mjs +1 -0
  23. package/dist/packem_shared/adapter.d-2a61HAY2.d.ts +76 -0
  24. package/dist/packem_shared/adapter.d-DrD3bb1u.d.mts +76 -0
  25. package/dist/packem_shared/authAuditHook-tG8gdR77.mjs +1 -0
  26. package/dist/packem_shared/authDoColumnAdditions-BCSs7qaN.mjs +1 -0
  27. package/dist/packem_shared/compileMigrationsSql-Y1YB3maO.mjs +1 -0
  28. package/dist/packem_shared/create-auth.d-De6IOirt.d.mts +128 -0
  29. package/dist/packem_shared/create-auth.d-De6IOirt.d.ts +128 -0
  30. package/dist/packem_shared/createAuth-DYFhkI1U.mjs +1 -0
  31. package/dist/packem_shared/createDoAuthWiring-C8H_SGCq.mjs +1 -0
  32. package/dist/packem_shared/createLunoraAuthClient-DhjhCwmM.mjs +1 -0
  33. package/dist/packem_shared/emailGateDatabaseHooks-CAygR3iq.mjs +1 -0
  34. package/dist/packem_shared/sessionPresets-C867Mlo4.mjs +1 -0
  35. package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
  36. package/dist/plugins-client.d.mts +165 -1
  37. package/dist/plugins-client.d.ts +165 -1
  38. package/dist/plugins-client.mjs +1 -2
  39. package/dist/plugins-enterprise-client.d.mts +15 -0
  40. package/dist/plugins-enterprise-client.d.ts +15 -0
  41. package/dist/plugins-enterprise-client.mjs +1 -0
  42. package/dist/plugins-enterprise.d.mts +1670 -0
  43. package/dist/plugins-enterprise.d.ts +1670 -0
  44. package/dist/plugins-enterprise.mjs +1 -0
  45. package/dist/plugins.d.mts +102 -2
  46. package/dist/plugins.d.ts +102 -2
  47. package/dist/plugins.mjs +1 -22
  48. package/dist/schema.d.mts +39 -39
  49. package/dist/schema.d.ts +39 -39
  50. package/dist/schema.mjs +1 -62
  51. package/dist/sql-store.d.mts +28 -28
  52. package/dist/sql-store.d.ts +28 -28
  53. package/dist/sql-store.mjs +1 -162
  54. package/dist/store.d.mts +49 -31
  55. package/dist/store.d.ts +49 -31
  56. package/dist/store.mjs +1 -170
  57. package/dist/turnstile-middleware.d.mts +55 -55
  58. package/dist/turnstile-middleware.d.ts +55 -55
  59. package/dist/turnstile-middleware.mjs +1 -45
  60. package/dist/turnstile.d.mts +42 -59
  61. package/dist/turnstile.d.ts +42 -59
  62. package/dist/turnstile.mjs +1 -61
  63. package/package.json +40 -6
  64. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  65. package/dist/packem_shared/create-auth.d-M36jwG_Y.d.mts +0 -58
  66. package/dist/packem_shared/create-auth.d-M36jwG_Y.d.ts +0 -58
  67. package/dist/packem_shared/createAuth-B-tvsvQU.mjs +0 -56
  68. package/dist/packem_shared/createAuthAdmin-BxrfEeA_.mjs +0 -249
  69. package/dist/packem_shared/ensureMigrated-wZH3oXDu.mjs +0 -28
  70. package/dist/packem_shared/sessionPresets-B95rXrd8.mjs +0 -35
@@ -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{l as t,a as p,b as e}from"./packem_shared/adapter-DA8DdALX.mjs";import"./sql-store.mjs";export{t as lunoraAuthAdapter,p as lunoraD1Adapter,e as lunoraDoAdapter};
@@ -0,0 +1,131 @@
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-in-initiated" | "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
+ /**
31
+ * The identifier (email or username) a sign-in-family request ATTEMPTED,
32
+ * read from the request body. Present for both successful and failed
33
+ * attempts — unlike `actorEmail` (which requires an authenticated
34
+ * session), this is what lets a FAILED credential-stuffing attempt be
35
+ * grouped by target. Same redaction exemption as `actorEmail`: a
36
+ * top-level column, not a `detail` key, because `AUDIT_REDACT_RULES`
37
+ * scrubs email-shaped values inside `detail` regardless of key name —
38
+ * putting it there would erase exactly this datum. Length-capped to 320
39
+ * chars (RFC 5321) since it carries attacker-controlled request-body text.
40
+ */
41
+ targetEmail?: string;
42
+ /** Wall-clock millis when the event was recorded. */
43
+ ts: number;
44
+ /** Client User-Agent, when present on the request. */
45
+ userAgent?: string;
46
+ }
47
+ /** Fields accepted when appending one event; `seq` is assigned by the table. */
48
+ interface AppendAuthAuditEntry {
49
+ actorEmail?: string;
50
+ actorId?: string;
51
+ detail?: Record<string, unknown>;
52
+ event: string;
53
+ ip?: string;
54
+ outcome: AuthAuditOutcome;
55
+ /** See {@link AuthAuditEntry.targetEmail}. */
56
+ targetEmail?: string;
57
+ ts: number;
58
+ userAgent?: string;
59
+ }
60
+ /** Options for {@link appendAuthAuditEntry}. */
61
+ interface AppendAuthAuditOptions {
62
+ /**
63
+ * Redact secrets/PII in the `detail` payload before persisting. Defaults to
64
+ * `true`. Set `false` only for a trusted, pre-scrubbed payload.
65
+ */
66
+ redactDetail?: boolean;
67
+ /**
68
+ * Keep only the most recent `retention` rows (trimmed after each append),
69
+ * mirroring the admin audit log's bounded retention. Omit for an unbounded
70
+ * trail (the compliance default) — deliberately NOT capped at 1000.
71
+ */
72
+ retention?: number;
73
+ }
74
+ /** Options for {@link readAuthAuditLog}. */
75
+ interface ReadAuthAuditOptions {
76
+ /** Return only events for this actor id. */
77
+ actorId?: string;
78
+ /** Return only events of this type. */
79
+ event?: string;
80
+ /** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
81
+ limit?: number;
82
+ /** Return only events with `seq` strictly greater than this (forward paging). */
83
+ sinceSeq?: number;
84
+ }
85
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
86
+ /**
87
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
88
+ * when `retention` is set — trimming the log back to the most recent rows.
89
+ * Creates the table first so callers needn't. Returns the redacted, persisted
90
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
91
+ */
92
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
93
+ /**
94
+ * Read audit events newest-first, optionally filtered by `actorId` / `event` and
95
+ * paged past `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's
96
+ * `detail` JSON back into an object. Creates the table first so reads on a
97
+ * never-audited database return `[]` instead of throwing.
98
+ *
99
+ * `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
100
+ * `Number.NaN`, or an upstream boundary that failed to reject one) falls back
101
+ * to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
102
+ * which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
103
+ * parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
104
+ * rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
105
+ * safety net for every OTHER caller of this function too.
106
+ */
107
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
108
+ /**
109
+ * The auth/security audit read plane the runtime's `authAuditReader` option
110
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
111
+ * its admin gate to back the studio's "Security / audit" page
112
+ * (`__lunora_admin__:getAuthAuditLog`).
113
+ */
114
+ interface AuthAuditReader {
115
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
116
+ }
117
+ /**
118
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
119
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
120
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
121
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
122
+ *
123
+ * ```ts
124
+ * export default createWorker({
125
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
126
+ * // …
127
+ * });
128
+ * ```
129
+ */
130
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
131
+ 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,131 @@
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-in-initiated" | "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
+ /**
31
+ * The identifier (email or username) a sign-in-family request ATTEMPTED,
32
+ * read from the request body. Present for both successful and failed
33
+ * attempts — unlike `actorEmail` (which requires an authenticated
34
+ * session), this is what lets a FAILED credential-stuffing attempt be
35
+ * grouped by target. Same redaction exemption as `actorEmail`: a
36
+ * top-level column, not a `detail` key, because `AUDIT_REDACT_RULES`
37
+ * scrubs email-shaped values inside `detail` regardless of key name —
38
+ * putting it there would erase exactly this datum. Length-capped to 320
39
+ * chars (RFC 5321) since it carries attacker-controlled request-body text.
40
+ */
41
+ targetEmail?: string;
42
+ /** Wall-clock millis when the event was recorded. */
43
+ ts: number;
44
+ /** Client User-Agent, when present on the request. */
45
+ userAgent?: string;
46
+ }
47
+ /** Fields accepted when appending one event; `seq` is assigned by the table. */
48
+ interface AppendAuthAuditEntry {
49
+ actorEmail?: string;
50
+ actorId?: string;
51
+ detail?: Record<string, unknown>;
52
+ event: string;
53
+ ip?: string;
54
+ outcome: AuthAuditOutcome;
55
+ /** See {@link AuthAuditEntry.targetEmail}. */
56
+ targetEmail?: string;
57
+ ts: number;
58
+ userAgent?: string;
59
+ }
60
+ /** Options for {@link appendAuthAuditEntry}. */
61
+ interface AppendAuthAuditOptions {
62
+ /**
63
+ * Redact secrets/PII in the `detail` payload before persisting. Defaults to
64
+ * `true`. Set `false` only for a trusted, pre-scrubbed payload.
65
+ */
66
+ redactDetail?: boolean;
67
+ /**
68
+ * Keep only the most recent `retention` rows (trimmed after each append),
69
+ * mirroring the admin audit log's bounded retention. Omit for an unbounded
70
+ * trail (the compliance default) — deliberately NOT capped at 1000.
71
+ */
72
+ retention?: number;
73
+ }
74
+ /** Options for {@link readAuthAuditLog}. */
75
+ interface ReadAuthAuditOptions {
76
+ /** Return only events for this actor id. */
77
+ actorId?: string;
78
+ /** Return only events of this type. */
79
+ event?: string;
80
+ /** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
81
+ limit?: number;
82
+ /** Return only events with `seq` strictly greater than this (forward paging). */
83
+ sinceSeq?: number;
84
+ }
85
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
86
+ /**
87
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
88
+ * when `retention` is set — trimming the log back to the most recent rows.
89
+ * Creates the table first so callers needn't. Returns the redacted, persisted
90
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
91
+ */
92
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
93
+ /**
94
+ * Read audit events newest-first, optionally filtered by `actorId` / `event` and
95
+ * paged past `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's
96
+ * `detail` JSON back into an object. Creates the table first so reads on a
97
+ * never-audited database return `[]` instead of throwing.
98
+ *
99
+ * `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
100
+ * `Number.NaN`, or an upstream boundary that failed to reject one) falls back
101
+ * to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
102
+ * which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
103
+ * parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
104
+ * rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
105
+ * safety net for every OTHER caller of this function too.
106
+ */
107
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
108
+ /**
109
+ * The auth/security audit read plane the runtime's `authAuditReader` option
110
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
111
+ * its admin gate to back the studio's "Security / audit" page
112
+ * (`__lunora_admin__:getAuthAuditLog`).
113
+ */
114
+ interface AuthAuditReader {
115
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
116
+ }
117
+ /**
118
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
119
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
120
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
121
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
122
+ *
123
+ * ```ts
124
+ * export default createWorker({
125
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
126
+ * // …
127
+ * });
128
+ * ```
129
+ */
130
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
131
+ 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,12 @@
1
+ import{standardRules as L,piiRules as f,redact as g}from"@visulima/redact";const o="__lunora_auth_audit__",R=[...L,...f],p=1e3,N=1e4,n=null,l=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},h=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${o}" (
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
+ target_email TEXT,
9
+ ip TEXT,
10
+ user_agent TEXT,
11
+ detail TEXT
12
+ )`,[]);try{await e.run(`ALTER TABLE "${o}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},E=new WeakMap,m=e=>{const t=E.get(e);if(t)return t;const a=h(e);return E.set(e,a),a.catch(()=>E.delete(e)),a},D=async(e,t,a={})=>{await m(e);let i;return t.detail!==void 0&&(i=a.redactDetail===!1?t.detail:g(t.detail,R)),await e.run(`INSERT INTO "${o}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??n,t.actorEmail??n,t.targetEmail??n,t.ip??n,t.userAgent??n,i===void 0?n:JSON.stringify(i)]),typeof a.retention=="number"&&a.retention>0&&await e.run(`DELETE FROM "${o}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${o}")`,[a.retention]),{...t,detail:i}},I=async(e,t={})=>{await m(e);const a=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,N)):p,i=["seq > ?"],c=[t.sinceSeq??0];return t.actorId!==void 0&&(i.push("actor_id = ?"),c.push(t.actorId)),t.event!==void 0&&(i.push("event = ?"),c.push(t.event)),c.push(a),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${o}" WHERE ${i.join(" AND ")} ORDER BY seq DESC LIMIT ?`,c)).map(r=>{const u={event:l(r.event)??"",outcome:r.outcome==="failure"?"failure":"success",seq:Number(r.seq),ts:Number(r.ts)},A=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[s,_]of A){const T=l(r[_]);T!==void 0&&(u[s]=T)}const d=l(r.detail);if(d!==void 0)try{const s=JSON.parse(d);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(u.detail=s)}catch{}return u})},O=e=>({read:t=>I(e,t)});export{o as AUTH_AUDIT_TABLE,D as appendAuthAuditEntry,O as createAuthAuditReader,m as ensureAuthAuditTable,I as readAuthAuditLog};
@@ -0,0 +1,125 @@
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
+ * The returned/compared domain is IDNA-normalized (see {@link toAsciiDomain}) so
96
+ * a Unicode-form internationalized domain matches its `xn--` blocklist entry.
97
+ */
98
+ declare const classifyEmail: (email: string, config?: EmailGateConfig) => EmailClassification;
99
+ /**
100
+ * Classify `email` and enforce the gate, throwing a coded {@link LunoraError}
101
+ * when it fails: `VALIDATION_ERROR` (structurally invalid, only when
102
+ * `requireValidSyntax`, the default), `EMAIL_DOMAIN_BLOCKED` (disposable or
103
+ * deny-listed, only when `blockDisposable`, the default), or `EMAIL_UNDELIVERABLE`
104
+ * (no MX records, only when `mx: true`).
105
+ *
106
+ * Returns the {@link EmailClassification} on success so callers can branch on
107
+ * `free` vs `business`. Async only because of the opt-in MX step; with `mx` off
108
+ * it resolves without any network I/O.
109
+ */
110
+ declare const assertEmailAllowed: (email: string, config?: EmailGateConfig) => Promise<EmailClassification>;
111
+ /**
112
+ * Lunora procedure middleware that gates a non-auth, signup-shaped
113
+ * `mutation`/`action` on the email-domain policy. Attach it with `.use()`; it
114
+ * reads the email from `ctx` via the `email` selector (route it through `args`)
115
+ * and runs {@link assertEmailAllowed}, which throws a coded {@link LunoraError}
116
+ * (`EMAIL_DOMAIN_BLOCKED` / `EMAIL_UNDELIVERABLE` / `VALIDATION_ERROR`) the
117
+ * runtime maps to the matching status.
118
+ *
119
+ * To gate better-auth's native `/sign-up/email` endpoint instead, use
120
+ * `emailGateDatabaseHooks` / `withEmailGate` from `@lunora/auth` — those hook
121
+ * better-auth's own user-create path. The `Middleware` import is type-only, so
122
+ * this stays free of any runtime `@lunora/server` dependency.
123
+ */
124
+ declare const emailGateMiddleware: <Context>(options: EmailGateMiddlewareOptions<Context>) => Middleware<Context, Context>;
125
+ export { type EmailClass, type EmailClassification, type EmailGateConfig, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists };