@lunora/auth 1.0.0-alpha.8 → 1.0.0-alpha.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE.md +38 -0
  2. package/README.md +56 -1
  3. package/dist/adapter.d.mts +4 -43
  4. package/dist/adapter.d.ts +4 -43
  5. package/dist/adapter.mjs +1 -47
  6. package/dist/audit.d.mts +146 -0
  7. package/dist/audit.d.ts +146 -0
  8. package/dist/audit.mjs +12 -0
  9. package/dist/email-guard.d.mts +125 -0
  10. package/dist/email-guard.d.ts +125 -0
  11. package/dist/email-guard.mjs +1 -0
  12. package/dist/index.d.mts +709 -147
  13. package/dist/index.d.ts +709 -147
  14. package/dist/index.mjs +1 -12
  15. package/dist/middleware.d.mts +157 -156
  16. package/dist/middleware.d.ts +157 -156
  17. package/dist/middleware.mjs +1 -53
  18. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-C4897amZ.mjs +1 -0
  19. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-kIwlEt8i.mjs +1 -0
  20. package/dist/packem_shared/LunoraAuthAdminError-CMUphsi_.mjs +1 -0
  21. package/dist/packem_shared/adapter-RvDcm0Zy.mjs +1 -0
  22. package/dist/packem_shared/adapter.d-2a61HAY2.d.ts +76 -0
  23. package/dist/packem_shared/adapter.d-DrD3bb1u.d.mts +76 -0
  24. package/dist/packem_shared/authAuditHook-CP7kj4Ob.mjs +1 -0
  25. package/dist/packem_shared/authDoColumnAdditions-B8BRbdzn.mjs +1 -0
  26. package/dist/packem_shared/compileMigrationsSql-BcvcHAqo.mjs +1 -0
  27. package/dist/packem_shared/create-auth.d-De6IOirt.d.mts +128 -0
  28. package/dist/packem_shared/create-auth.d-De6IOirt.d.ts +128 -0
  29. package/dist/packem_shared/createAuth-DRtd4q6u.mjs +1 -0
  30. package/dist/packem_shared/createDoAuthWiring-acnXUGZr.mjs +1 -0
  31. package/dist/packem_shared/createLunoraAuthClient-gxLo2pKj.mjs +1 -0
  32. package/dist/packem_shared/emailGateDatabaseHooks-DzBD1Qoq.mjs +1 -0
  33. package/dist/packem_shared/sessionPresets-DpEFjXKV.mjs +1 -0
  34. package/dist/packem_shared/uiConfig-BrYEFK3O.mjs +1 -0
  35. package/dist/plugins-client.d.mts +68 -1
  36. package/dist/plugins-client.d.ts +68 -1
  37. package/dist/plugins-client.mjs +1 -2
  38. package/dist/plugins-enterprise-client.d.mts +9 -0
  39. package/dist/plugins-enterprise-client.d.ts +9 -0
  40. package/dist/plugins-enterprise-client.mjs +1 -0
  41. package/dist/plugins-enterprise.d.mts +1576 -0
  42. package/dist/plugins-enterprise.d.ts +1576 -0
  43. package/dist/plugins-enterprise.mjs +1 -0
  44. package/dist/plugins.d.mts +83 -2
  45. package/dist/plugins.d.ts +83 -2
  46. package/dist/plugins.mjs +1 -22
  47. package/dist/schema.d.mts +39 -39
  48. package/dist/schema.d.ts +39 -39
  49. package/dist/schema.mjs +1 -62
  50. package/dist/sql-store.d.mts +28 -28
  51. package/dist/sql-store.d.ts +28 -28
  52. package/dist/sql-store.mjs +1 -162
  53. package/dist/store.d.mts +49 -31
  54. package/dist/store.d.ts +49 -31
  55. package/dist/store.mjs +1 -170
  56. package/dist/turnstile-middleware.d.mts +55 -55
  57. package/dist/turnstile-middleware.d.ts +55 -55
  58. package/dist/turnstile-middleware.mjs +1 -45
  59. package/dist/turnstile.d.mts +42 -59
  60. package/dist/turnstile.d.ts +42 -59
  61. package/dist/turnstile.mjs +1 -61
  62. package/package.json +38 -5
  63. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  64. package/dist/packem_shared/LunoraAuthAdminError-BxrfEeA_.mjs +0 -249
  65. package/dist/packem_shared/compileMigrationsSql-wZH3oXDu.mjs +0 -28
  66. package/dist/packem_shared/create-auth.d-M36jwG_Y.d.mts +0 -58
  67. package/dist/packem_shared/create-auth.d-M36jwG_Y.d.ts +0 -58
  68. package/dist/packem_shared/createAuth-B-tvsvQU.mjs +0 -56
  69. package/dist/packem_shared/sessionPresets-B95rXrd8.mjs +0 -35
package/LICENSE.md CHANGED
@@ -103,3 +103,41 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+
112
+ # Licenses of bundled types
113
+ The published @lunora/auth artifact additionally contains code with the following licenses:
114
+ MIT
115
+
116
+ # Bundled types:
117
+ ## @better-auth/sso
118
+ License: MIT
119
+ By: Bereket Engida
120
+ Repository: git+https://github.com/better-auth/better-auth.git
121
+
122
+ > The MIT License (MIT)
123
+ > Copyright (c) 2024 - present, Bereket Engida
124
+ >
125
+ > Permission is hereby granted, free of charge, to any person obtaining a copy of
126
+ > this software and associated documentation files (the “Software”), to deal in
127
+ > the Software without restriction, including without limitation the rights to
128
+ > use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
129
+ > the Software, and to permit persons to whom the Software is furnished to do so,
130
+ > subject to the following conditions:
131
+ >
132
+ > The above copyright notice and this permission notice shall be included in all
133
+ > copies or substantial portions of the Software.
134
+ >
135
+ > THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
136
+ > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
137
+ > FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
138
+ > IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
139
+ > DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
140
+ > ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
141
+ > DEALINGS IN THE SOFTWARE.
142
+
143
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -84,10 +84,65 @@ The runtime resolves the inbound session and stamps `ctx.auth` on every `query`
84
84
 
85
85
  ### Plugins & CAPTCHA
86
86
 
87
- better-auth's plugin factories are re-exported from `@lunora/auth/plugins` (so you don't need better-auth's deep import paths): `admin`, `anonymous`, `bearer`, `captcha`, `createAccessControl`, `customSession`, `deviceAuthorization`, `emailOTP`, `genericOAuth`, `haveIBeenPwned`, `jwt`, `magicLink`, `mcp`, `multiSession`, `oAuthProxy`, `oidcProvider`, `oneTimeToken`, `organization`, `passkey`, `phoneNumber`, `siwe`, `twoFactor`, `username`, and `withMcpAuth`.
87
+ better-auth's plugin factories are re-exported from `@lunora/auth/plugins` (so you don't need better-auth's deep import paths): `admin`, `anonymous`, `bearer`, `captcha`, `createAccessControl`, `customSession`, `deviceAuthorization`, `emailOTP`, `genericOAuth`, `haveIBeenPwned`, `jwt`, `magicLink`, `mcp`, `mcpHandler`, `multiSession`, `oAuthProxy`, `oauthProvider`, `oneTimeToken`, `organization`, `passkey`, `phoneNumber`, `requireMcpAuth`, `scim`, `siwe`, `twoFactor`, and `username`. Enterprise SSO ships separately as `sso` from `@lunora/auth/plugins/enterprise` (an optional peer — see the docs).
88
88
 
89
89
  For Cloudflare Turnstile on the **auth flow**, use the `captcha` plugin (`captcha({ provider: "cloudflare-turnstile", secretKey: env.TURNSTILE_SECRET_KEY })`); it reads the token from the `x-captcha-response` header. For **non-auth** procedures, the package root also exports standalone helpers — `verifyTurnstile` (pure `siteverify`) and `verifyTurnstileMiddleware` (a `.use()` middleware that takes the token from the function args).
90
90
 
91
+ ### Disposable / free-email gating
92
+
93
+ Reject throwaway/disposable signups (and branch on free-vs-business email) by reusing the visulima email lists — pure-data and **edge-safe on the default path** (no DNS). Wire it into better-auth's native signup with `withEmailGate` (or `emailGateDatabaseHooks`):
94
+
95
+ ```ts
96
+ import { createAuth, withEmailGate, lunoraD1Adapter } from "@lunora/auth";
97
+
98
+ const auth = createAuth(
99
+ withEmailGate(
100
+ { secret: env.AUTH_SECRET, database: lunoraD1Adapter(env.DB), emailAndPassword: { enabled: true } },
101
+ {
102
+ blockDisposable: true, // default — reject disposable domains with `EMAIL_DOMAIN_BLOCKED`
103
+ allowDomains: ["your-company.com"], // never blocked; always classified `business`
104
+ denyDomains: [], // extra domains to treat as disposable
105
+ // mx: true, // OPT-IN deliverability check — needs DNS (node:dns), so keep it OFF on the edge path
106
+ onClassify: (c, user) => console.log(`signup ${user.email as string}: ${c.emailClass}`),
107
+ },
108
+ ),
109
+ );
110
+ ```
111
+
112
+ A blocked signup fails with the coded error `EMAIL_DOMAIN_BLOCKED` (HTTP 400); a business/free email passes and its `emailClass` (`disposable | free | business`) is surfaced via `onClassify`. Everything is config-gated and defaults sensibly.
113
+
114
+ - **Programmatic / non-auth use:** `classifyEmail(email, config)` (sync, pure-data) and `assertEmailAllowed(email, config)` (async; throws the coded error) come from `@lunora/auth/email-guard`, plus `emailGateMiddleware({ email: (ctx) => ctx.args.email })` for a `.use()` gate on your own signup mutations.
115
+ - **Edge-safety:** on workerd, `await loadEmailDomainLists()` once at worker init (the gate helpers do this for you). The optional `mx: true` deliverability check is loaded via a dynamic import so `node:dns` never enters the default bundle — enable it only with `nodejs_compat` (or a DNS-over-HTTPS shim).
116
+
117
+ ### Security / audit trail
118
+
119
+ Record authentication & security events (sign-in, sign-up, password change, MFA enable/disable, token refresh, session revoke, …) to a durable, queryable audit trail. Install the better-auth `hooks.after` recorder with `authAuditHook` (or compose via `withAuthAudit`), backed by the same D1 database as the auth tables:
120
+
121
+ ```ts
122
+ import { authAuditHook, createAuth, d1Executor, lunoraD1Adapter, readAuthAuditLog } from "@lunora/auth";
123
+
124
+ const executor = d1Executor(env.DB);
125
+
126
+ const auth = createAuth({
127
+ secret: env.AUTH_SECRET,
128
+ database: lunoraD1Adapter(env.DB),
129
+ hooks: {
130
+ after: authAuditHook({
131
+ executor,
132
+ // retention is CONFIGURABLE and NOT capped — omit it for an unbounded, compliance-grade trail
133
+ retention: 100_000,
134
+ // optional export tap for SIEM forwarding (receives each redacted entry)
135
+ onRecord: (entry) => forwardToSiem(entry),
136
+ }),
137
+ },
138
+ });
139
+
140
+ // Query the trail (RLS/admin-gate this in your own read):
141
+ const recent = await readAuthAuditLog(executor, { event: "sign-in", limit: 100 });
142
+ ```
143
+
144
+ The free-form `detail` payload is scrubbed with `@visulima/redact` before it is persisted, so a token/password that leaks into an event's context never reaches the durable table. Retention defaults to unbounded (set `retention` to bound it). The store lives in the reserved `__lunora_auth_audit__` table (auto-hidden from the data browser).
145
+
91
146
  > This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/packages/auth)**.
92
147
 
93
148
  ## Related
@@ -1,43 +1,4 @@
1
- import { createAdapterFactory } from 'better-auth/adapters';
2
- import { d1Executor } from "./sql-store.mjs";
3
- import { AuthStore } from "./store.mjs";
4
- /**
5
- * A better-auth database adapter backed by an {@link AuthStore} — the bridge
6
- * that routes better-auth's reads and writes through Lunora's data layer
7
- * instead of better-auth's built-in D1/Kysely adapter. Pass the result as
8
- * `createAuth({ database: lunoraAuthAdapter(store) })`; better-auth's
9
- * `createAdapterFactory` handles id generation, default values, field-name
10
- * mapping and output shaping, so this only translates the cleaned CRUD calls
11
- * onto the store.
12
- *
13
- * ```ts
14
- * const auth = createAuth({
15
- * secret: env.AUTH_SECRET,
16
- * emailAndPassword: { enabled: true },
17
- * database: lunoraAuthAdapter(lunoraStore), // lunoraStore writes via ctx.db
18
- * });
19
- * ```
20
- *
21
- * Scope: the {@link AuthStore} interface is single-table CRUD. better-auth's
22
- * relational `join` reads (an advanced opt-in) are not handled — pair the
23
- * adapter with `disableJoins` or let better-auth fall back to per-table reads.
24
- */
25
- declare const lunoraAuthAdapter: (store: AuthStore) => ReturnType<typeof createAdapterFactory>;
26
- /**
27
- * One-liner for the common case: a better-auth `database` backed by a Cloudflare
28
- * D1 binding, via Lunora's SQL store — equivalent to
29
- * `lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)))`.
30
- *
31
- * Prefer this over passing the raw `env.DB` as `database`. With raw D1,
32
- * better-auth resolves its Kysely adapter through a runtime `await import(...)`
33
- * inside `auth.$context`, and that dynamic import never settles under
34
- * `@cloudflare/vite-plugin`'s worker runner — so it hangs *every* auth request
35
- * in `pnpm dev` (a standalone `wrangler dev` or a deployed worker bundle it
36
- * up-front, so they're unaffected — which makes the hang baffling to debug).
37
- * This explicit adapter skips that import entirely, so dev and prod behave the
38
- * same. The migration instance is the one exception — it wants raw `env.DB` so
39
- * `ensureMigrated`'s Kysely migrator can create the tables (its `$context` is
40
- * never resolved, so the hang doesn't apply there).
41
- */
42
- declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
43
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import 'better-auth/adapters';
2
+ export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-DrD3bb1u.mjs";
3
+ import "./sql-store.mjs";
4
+ import "./store.mjs";
package/dist/adapter.d.ts CHANGED
@@ -1,43 +1,4 @@
1
- import { createAdapterFactory } from 'better-auth/adapters';
2
- import { d1Executor } from "./sql-store.js";
3
- import { AuthStore } from "./store.js";
4
- /**
5
- * A better-auth database adapter backed by an {@link AuthStore} — the bridge
6
- * that routes better-auth's reads and writes through Lunora's data layer
7
- * instead of better-auth's built-in D1/Kysely adapter. Pass the result as
8
- * `createAuth({ database: lunoraAuthAdapter(store) })`; better-auth's
9
- * `createAdapterFactory` handles id generation, default values, field-name
10
- * mapping and output shaping, so this only translates the cleaned CRUD calls
11
- * onto the store.
12
- *
13
- * ```ts
14
- * const auth = createAuth({
15
- * secret: env.AUTH_SECRET,
16
- * emailAndPassword: { enabled: true },
17
- * database: lunoraAuthAdapter(lunoraStore), // lunoraStore writes via ctx.db
18
- * });
19
- * ```
20
- *
21
- * Scope: the {@link AuthStore} interface is single-table CRUD. better-auth's
22
- * relational `join` reads (an advanced opt-in) are not handled — pair the
23
- * adapter with `disableJoins` or let better-auth fall back to per-table reads.
24
- */
25
- declare const lunoraAuthAdapter: (store: AuthStore) => ReturnType<typeof createAdapterFactory>;
26
- /**
27
- * One-liner for the common case: a better-auth `database` backed by a Cloudflare
28
- * D1 binding, via Lunora's SQL store — equivalent to
29
- * `lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)))`.
30
- *
31
- * Prefer this over passing the raw `env.DB` as `database`. With raw D1,
32
- * better-auth resolves its Kysely adapter through a runtime `await import(...)`
33
- * inside `auth.$context`, and that dynamic import never settles under
34
- * `@cloudflare/vite-plugin`'s worker runner — so it hangs *every* auth request
35
- * in `pnpm dev` (a standalone `wrangler dev` or a deployed worker bundle it
36
- * up-front, so they're unaffected — which makes the hang baffling to debug).
37
- * This explicit adapter skips that import entirely, so dev and prod behave the
38
- * same. The migration instance is the one exception — it wants raw `env.DB` so
39
- * `ensureMigrated`'s Kysely migrator can create the tables (its `$context` is
40
- * never resolved, so the hang doesn't apply there).
41
- */
42
- declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
43
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import 'better-auth/adapters';
2
+ export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-2a61HAY2.js";
3
+ import "./sql-store.js";
4
+ import "./store.js";
package/dist/adapter.mjs CHANGED
@@ -1,47 +1 @@
1
- import { createAdapterFactory } from 'better-auth/adapters';
2
- import { createSqlAuthStore, d1Executor } from './sql-store.mjs';
3
-
4
- const asRow = (row) => row;
5
- const asRowOrNull = (row) => row ?? null;
6
- const asRows = (rows) => rows;
7
- const lunoraAuthAdapter = (store) => createAdapterFactory({
8
- adapter: () => {
9
- return {
10
- consumeOne: async ({ model, where }) => asRowOrNull(await store.consumeOne(model, where)),
11
- count: async ({ model, where }) => store.count(model, where ?? []),
12
- create: async ({ data, model }) => asRow(await store.create(model, data)),
13
- delete: async ({ model, where }) => {
14
- await store.remove(model, where);
15
- },
16
- deleteMany: async ({ model, where }) => store.remove(model, where),
17
- findMany: async ({ limit, model, offset, sortBy, where }) => asRows(await store.read(model, { limit, offset, sortBy, where: where ?? [] })),
18
- findOne: async ({ model, where }) => {
19
- const [row] = await store.read(model, { limit: 1, where });
20
- return asRowOrNull(row);
21
- },
22
- update: async ({ model, update, where }) => {
23
- const [row] = await store.update(model, where, update);
24
- return asRowOrNull(row);
25
- },
26
- updateMany: async ({ model, update, where }) => {
27
- const updated = await store.update(model, where, update);
28
- return updated.length;
29
- }
30
- };
31
- },
32
- config: {
33
- adapterId: "lunora",
34
- adapterName: "Lunora Adapter",
35
- // Conservative flags so the adapter is store-agnostic: better-auth
36
- // serializes dates/booleans/json to primitives (string/number) before a
37
- // write and parses them back after a read, so a store — in-memory or
38
- // SQL — only ever handles primitives, never schema-aware codecs.
39
- supportsBooleans: false,
40
- supportsDates: false,
41
- supportsJSON: false,
42
- supportsNumericIds: false
43
- }
44
- });
45
- const lunoraD1Adapter = (d1) => lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)));
46
-
47
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import"better-auth/adapters";import{s as p,l as e,w as l}from"./packem_shared/adapter-RvDcm0Zy.mjs";import"./sql-store.mjs";export{p as lunoraAuthAdapter,e as lunoraD1Adapter,l as lunoraDoAdapter};
@@ -0,0 +1,146 @@
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
+ /**
86
+ * Create the `__lunora_auth_audit__` table. `seq` is an `AUTOINCREMENT` primary
87
+ * key giving the database a monotonic cursor the Security page pages through.
88
+ * Idempotent, so read and write paths can call it defensively.
89
+ *
90
+ * `target_email` is added via a guarded `ALTER TABLE` rather than baked only
91
+ * into the `CREATE`, mirroring `@lunora/observability`'s
92
+ * `ensureRequestLogTable`/`ensureFunctionMetricsTables` — `CREATE TABLE IF NOT
93
+ * EXISTS` only helps a table that doesn't exist yet, so a database whose audit
94
+ * table predates this column needs the `ALTER` to gain it. SQLite has no `ADD
95
+ * COLUMN IF NOT EXISTS`; the duplicate-column error from a re-run (or from the
96
+ * column already existing on the freshly-created schema above) is swallowed —
97
+ * anything else re-throws, so a genuinely broken executor is not silently
98
+ * papered over.
99
+ */
100
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
101
+ /**
102
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
103
+ * when `retention` is set — trimming the log back to the most recent rows.
104
+ * Creates the table first so callers needn't. Returns the redacted, persisted
105
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
106
+ */
107
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
108
+ /**
109
+ * Read audit events newest-first, optionally filtered by `actorId` / `event` and
110
+ * paged past `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's
111
+ * `detail` JSON back into an object. Creates the table first so reads on a
112
+ * never-audited database return `[]` instead of throwing.
113
+ *
114
+ * `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
115
+ * `Number.NaN`, or an upstream boundary that failed to reject one) falls back
116
+ * to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
117
+ * which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
118
+ * parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
119
+ * rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
120
+ * safety net for every OTHER caller of this function too.
121
+ */
122
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
123
+ /**
124
+ * The auth/security audit read plane the runtime's `authAuditReader` option
125
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
126
+ * its admin gate to back the studio's "Security / audit" page
127
+ * (`__lunora_admin__:getAuthAuditLog`).
128
+ */
129
+ interface AuthAuditReader {
130
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
131
+ }
132
+ /**
133
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
134
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
135
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
136
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
137
+ *
138
+ * ```ts
139
+ * export default createWorker({
140
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
141
+ * // …
142
+ * });
143
+ * ```
144
+ */
145
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
146
+ 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,146 @@
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
+ /**
86
+ * Create the `__lunora_auth_audit__` table. `seq` is an `AUTOINCREMENT` primary
87
+ * key giving the database a monotonic cursor the Security page pages through.
88
+ * Idempotent, so read and write paths can call it defensively.
89
+ *
90
+ * `target_email` is added via a guarded `ALTER TABLE` rather than baked only
91
+ * into the `CREATE`, mirroring `@lunora/observability`'s
92
+ * `ensureRequestLogTable`/`ensureFunctionMetricsTables` — `CREATE TABLE IF NOT
93
+ * EXISTS` only helps a table that doesn't exist yet, so a database whose audit
94
+ * table predates this column needs the `ALTER` to gain it. SQLite has no `ADD
95
+ * COLUMN IF NOT EXISTS`; the duplicate-column error from a re-run (or from the
96
+ * column already existing on the freshly-created schema above) is swallowed —
97
+ * anything else re-throws, so a genuinely broken executor is not silently
98
+ * papered over.
99
+ */
100
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
101
+ /**
102
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
103
+ * when `retention` is set — trimming the log back to the most recent rows.
104
+ * Creates the table first so callers needn't. Returns the redacted, persisted
105
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
106
+ */
107
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
108
+ /**
109
+ * Read audit events newest-first, optionally filtered by `actorId` / `event` and
110
+ * paged past `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's
111
+ * `detail` JSON back into an object. Creates the table first so reads on a
112
+ * never-audited database return `[]` instead of throwing.
113
+ *
114
+ * `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
115
+ * `Number.NaN`, or an upstream boundary that failed to reject one) falls back
116
+ * to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
117
+ * which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
118
+ * parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
119
+ * rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
120
+ * safety net for every OTHER caller of this function too.
121
+ */
122
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
123
+ /**
124
+ * The auth/security audit read plane the runtime's `authAuditReader` option
125
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
126
+ * its admin gate to back the studio's "Security / audit" page
127
+ * (`__lunora_admin__:getAuthAuditLog`).
128
+ */
129
+ interface AuthAuditReader {
130
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
131
+ }
132
+ /**
133
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
134
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
135
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
136
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
137
+ *
138
+ * ```ts
139
+ * export default createWorker({
140
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
141
+ * // …
142
+ * });
143
+ * ```
144
+ */
145
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
146
+ 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{redact as p,standardRules as A,piiRules as g}from"@visulima/redact";const n="__lunora_auth_audit__",L=[...A,...g],N=1e3,R=1e4,o=null,E=t=>{if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean")return String(t)},d=async t=>{await t.run(`CREATE TABLE IF NOT EXISTS "${n}" (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ event TEXT NOT NULL,
5
+ outcome TEXT NOT NULL,
6
+ actor_id TEXT,
7
+ actor_email TEXT,
8
+ target_email TEXT,
9
+ ip TEXT,
10
+ user_agent TEXT,
11
+ detail TEXT
12
+ )`,[]);try{await t.run(`ALTER TABLE "${n}" ADD COLUMN target_email TEXT`,[])}catch(e){if(!(e instanceof Error?e.message.toLowerCase():String(e).toLowerCase()).includes("duplicate column"))throw e}},I=async(t,e,i={})=>{await d(t);let a;return e.detail!==void 0&&(a=i.redactDetail===!1?e.detail:p(e.detail,L)),await t.run(`INSERT INTO "${n}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.ts,e.event,e.outcome,e.actorId??o,e.actorEmail??o,e.targetEmail??o,e.ip??o,e.userAgent??o,a===void 0?o:JSON.stringify(a)]),typeof i.retention=="number"&&i.retention>0&&await t.run(`DELETE FROM "${n}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${n}")`,[i.retention]),{...e,detail:a}},f=async(t,e={})=>{await d(t);const i=Number.isFinite(e.limit)?Math.max(1,Math.min(e.limit,R)):N,a=["seq > ?"],s=[e.sinceSeq??0];return e.actorId!==void 0&&(a.push("actor_id = ?"),s.push(e.actorId)),e.event!==void 0&&(a.push("event = ?"),s.push(e.event)),s.push(i),(await t.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${n}" WHERE ${a.join(" AND ")} ORDER BY seq DESC LIMIT ?`,s)).map(r=>{const u={event:E(r.event)??"",outcome:r.outcome==="failure"?"failure":"success",seq:Number(r.seq),ts:Number(r.ts)},T=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[m,_]of T){const l=E(r[_]);l!==void 0&&(u[m]=l)}const c=E(r.detail);return c!==void 0&&(u.detail=JSON.parse(c)),u})},h=t=>({read:e=>f(t,e)});export{n as AUTH_AUDIT_TABLE,I as appendAuthAuditEntry,h as createAuthAuditReader,d as ensureAuthAuditTable,f as readAuthAuditLog};