@lunora/auth 1.0.0-alpha.28 → 1.0.0-alpha.280

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 (107) hide show
  1. package/LICENSE.md +233 -104
  2. package/README.md +109 -15
  3. package/dist/adapter.d.mts +4 -43
  4. package/dist/adapter.d.ts +4 -43
  5. package/dist/adapter.mjs +1 -48
  6. package/dist/audit.d.mts +173 -0
  7. package/dist/audit.d.ts +173 -0
  8. package/dist/audit.mjs +1 -0
  9. package/dist/cimd-node.d.mts +1 -0
  10. package/dist/cimd-node.d.ts +1 -0
  11. package/dist/cimd-node.mjs +1 -0
  12. package/dist/cimd-workers.d.mts +64 -0
  13. package/dist/cimd-workers.d.ts +64 -0
  14. package/dist/cimd-workers.mjs +1 -0
  15. package/dist/email-guard.d.mts +143 -0
  16. package/dist/email-guard.d.ts +143 -0
  17. package/dist/email-guard.mjs +1 -0
  18. package/dist/index.d.mts +620 -541
  19. package/dist/index.d.ts +620 -541
  20. package/dist/index.mjs +1 -12
  21. package/dist/middleware.d.mts +165 -155
  22. package/dist/middleware.d.ts +165 -155
  23. package/dist/middleware.mjs +1 -56
  24. package/dist/migrate.d.mts +62 -0
  25. package/dist/migrate.d.ts +62 -0
  26. package/dist/migrate.mjs +1 -0
  27. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-jbpoDPJs.mjs +1 -0
  28. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs +1 -0
  29. package/dist/packem_shared/LunoraAuthAdminError-Cg94b5lr.mjs +1 -0
  30. package/dist/packem_shared/adapter-L3XvHnkW.mjs +2 -0
  31. package/dist/packem_shared/adapter.d-BEvPbvSs.d.ts +110 -0
  32. package/dist/packem_shared/adapter.d-RQVSeO5T.d.mts +110 -0
  33. package/dist/packem_shared/api-key-storage-D15k9_CF.mjs +1 -0
  34. package/dist/packem_shared/apiKey-B9uGt5Nc.mjs +1 -0
  35. package/dist/packem_shared/audit-daeExZWv.mjs +12 -0
  36. package/dist/packem_shared/auth-do-JzJM4sBK.mjs +1 -0
  37. package/dist/packem_shared/authAuditBeforeHook-DPRq6mbA.mjs +1 -0
  38. package/dist/packem_shared/authBackfillStatus-ZDUCk4U6.mjs +1 -0
  39. package/dist/packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs +1 -0
  40. package/dist/packem_shared/authCredentialColumns-CnsISHUl.mjs +1 -0
  41. package/dist/packem_shared/authDiscoveryPaths-BtKCs_3V.mjs +1 -0
  42. package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
  43. package/dist/packem_shared/convertAuthDatesOnce-DE_O-bpx.mjs +1 -0
  44. package/dist/packem_shared/create-auth.d-B8S7aw9O.d.mts +153 -0
  45. package/dist/packem_shared/create-auth.d-B8S7aw9O.d.ts +153 -0
  46. package/dist/packem_shared/createAuth-DFkaeVge.mjs +1 -0
  47. package/dist/packem_shared/createDoAuthWiring-o3mfSSIf.mjs +1 -0
  48. package/dist/packem_shared/createLunoraAuthClient-wzZk9E0m.mjs +1 -0
  49. package/dist/packem_shared/createSignUpInvitation-miwkunlA.mjs +1 -0
  50. package/dist/packem_shared/effectiveCookieCache-JvL6i6YO.mjs +1 -0
  51. package/dist/packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs +1 -0
  52. package/dist/packem_shared/handleAuthRequest-Id9Vv_Tk.mjs +1 -0
  53. package/dist/packem_shared/identity-claims-hAvIl2wm.mjs +1 -0
  54. package/dist/packem_shared/invitation-email-backfill-DUwurNbV.mjs +1 -0
  55. package/dist/packem_shared/invite-only.d-CsBPLsY1.d.mts +126 -0
  56. package/dist/packem_shared/invite-only.d-JdPDmy_a.d.ts +126 -0
  57. package/dist/packem_shared/isDevEnvironment-yLbPngwn.mjs +1 -0
  58. package/dist/packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs +1 -0
  59. package/dist/packem_shared/mcp-CK5XkDFp.mjs +1 -0
  60. package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
  61. package/dist/packem_shared/prepareAuthData-CP4M7zk1.mjs +1 -0
  62. package/dist/packem_shared/provision-DWGVCbQD.mjs +1 -0
  63. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
  64. package/dist/packem_shared/resolveSessionIdentity-EBhckRBW.mjs +1 -0
  65. package/dist/packem_shared/sessionPresets-DQQYAOER.mjs +1 -0
  66. package/dist/packem_shared/sql-store-CFeVqF0V.mjs +1 -0
  67. package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
  68. package/dist/packem_shared/worker.d-CDnMrB5s.d.mts +912 -0
  69. package/dist/packem_shared/worker.d-CVuhZPM3.d.ts +912 -0
  70. package/dist/plugins-client.d.mts +251 -1
  71. package/dist/plugins-client.d.ts +251 -1
  72. package/dist/plugins-client.mjs +1 -2
  73. package/dist/plugins-enterprise-client.d.mts +13 -0
  74. package/dist/plugins-enterprise-client.d.ts +13 -0
  75. package/dist/plugins-enterprise-client.mjs +1 -0
  76. package/dist/plugins-enterprise.d.mts +1659 -0
  77. package/dist/plugins-enterprise.d.ts +1659 -0
  78. package/dist/plugins-enterprise.mjs +1 -0
  79. package/dist/plugins.d.mts +180 -2
  80. package/dist/plugins.d.ts +180 -2
  81. package/dist/plugins.mjs +1 -22
  82. package/dist/schema.d.mts +47 -39
  83. package/dist/schema.d.ts +47 -39
  84. package/dist/schema.mjs +1 -62
  85. package/dist/sql-store.d.mts +48 -29
  86. package/dist/sql-store.d.ts +48 -29
  87. package/dist/sql-store.mjs +1 -184
  88. package/dist/store.d.mts +65 -47
  89. package/dist/store.d.ts +65 -47
  90. package/dist/store.mjs +1 -183
  91. package/dist/turnstile-middleware.d.mts +73 -55
  92. package/dist/turnstile-middleware.d.ts +73 -55
  93. package/dist/turnstile-middleware.mjs +1 -34
  94. package/dist/turnstile.d.mts +42 -49
  95. package/dist/turnstile.d.ts +42 -49
  96. package/dist/turnstile.mjs +1 -54
  97. package/dist/worker.d.mts +9 -0
  98. package/dist/worker.d.ts +9 -0
  99. package/dist/worker.mjs +1 -0
  100. package/package.json +58 -7
  101. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  102. package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
  103. package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.mjs +0 -29
  104. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
  105. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
  106. package/dist/packem_shared/createAuth-BVMMllTm.mjs +0 -87
  107. package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
package/dist/adapter.mjs CHANGED
@@ -1,48 +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
- incrementOne: async ({ increment, model, set, where }) => asRowOrNull(await store.incrementOne(model, where, increment, set)),
23
- update: async ({ model, update, where }) => {
24
- const [row] = await store.update(model, where, update);
25
- return asRowOrNull(row);
26
- },
27
- updateMany: async ({ model, update, where }) => {
28
- const updated = await store.update(model, where, update);
29
- return updated.length;
30
- }
31
- };
32
- },
33
- config: {
34
- adapterId: "lunora",
35
- adapterName: "Lunora Adapter",
36
- // Conservative flags so the adapter is store-agnostic: better-auth
37
- // serializes dates/booleans/json to primitives (string/number) before a
38
- // write and parses them back after a read, so a store — in-memory or
39
- // SQL — only ever handles primitives, never schema-aware codecs.
40
- supportsBooleans: false,
41
- supportsDates: false,
42
- supportsJSON: false,
43
- supportsNumericIds: false
44
- }
45
- });
46
- const lunoraD1Adapter = (d1) => lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)));
47
-
48
- export { lunoraAuthAdapter, lunoraD1Adapter };
1
+ import{l as p,a as e,b as l}from"./packem_shared/adapter-L3XvHnkW.mjs";import"./packem_shared/provision-DWGVCbQD.mjs";import"./packem_shared/sql-store-CFeVqF0V.mjs";export{p as lunoraAuthAdapter,e as lunoraD1Adapter,l as lunoraDoAdapter};
@@ -0,0 +1,173 @@
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" | "admin-impersonate-start" | "admin-impersonate-stop" | "admin-password-set" | "admin-role-change" | "admin-session-revoke" | "admin-user-ban" | "admin-user-create" | "admin-user-remove" | "admin-user-unban" | "admin-user-update" | "api-key-create" | "api-key-delete" | "api-key-update" | "device-approve" | "device-deny" | "email-change" | "email-change-request" | "email-verification" | "mfa-backup-codes-regenerate" | "mfa-disable" | "mfa-enable" | "oauth-client-create" | "oauth-client-delete" | "oauth-client-keys-rotate" | "oauth-client-secret-rotate" | "oauth-client-update" | "oauth-consent" | "oauth-consent-revoke" | "oauth-consent-update" | "oauth-resource-client-link" | "oauth-resource-client-unlink" | "oauth-resource-create" | "oauth-resource-delete" | "oauth-resource-update" | "oauth-token-issue" | "oauth-token-revoke" | "one-time-token-create" | "org-create" | "org-delete" | "org-invitation-accept" | "org-invitation-cancel" | "org-invitation-create" | "org-invitation-reject" | "org-member-add" | "org-member-leave" | "org-member-remove" | "org-member-role-change" | "org-role-change" | "org-switch" | "org-team-create" | "org-team-member-add" | "org-team-member-remove" | "org-team-remove" | "org-team-switch" | "org-team-update" | "org-update" | "passkey-add" | "passkey-remove" | "passkey-rename" | "password-change" | "password-reset" | "password-reset-request" | "phone-verification" | "scim-group-create" | "scim-group-delete" | "scim-group-update" | "scim-user-create" | "scim-user-delete" | "scim-user-update" | "session-revoke" | "session-switch" | "sign-in" | "sign-in-initiated" | "sign-out" | "sign-up" | "sign-up-invitation-create" | "sign-up-invitation-revoke" | "sso-provider-delete" | "sso-provider-register" | "sso-provider-update" | "token-refresh" | "user-delete" | "user-delete-request" | (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, or the address an admin-plane event acted on.
33
+ * Plain text for a success. For a FAILED attempt it is a keyed digest,
34
+ * `hmac-sha256:<hex>` of the trimmed, lower-cased identifier, because that
35
+ * text is whatever the caller typed (sometimes a pasted password); it is
36
+ * absent when the writer passed no `hashKey`. Unlike `actorEmail` (which
37
+ * requires an authenticated session), this is what lets a FAILED
38
+ * credential-stuffing attempt be grouped by target. Same redaction exemption as `actorEmail`: a
39
+ * top-level column, not a `detail` key, because `AUDIT_REDACT_RULES`
40
+ * scrubs email-shaped values inside `detail` regardless of key name —
41
+ * putting it there would erase exactly this datum. Length-capped to 320
42
+ * chars (RFC 5321) since it carries attacker-controlled request-body text.
43
+ */
44
+ targetEmail?: string;
45
+ /** Wall-clock millis when the event was recorded. */
46
+ ts: number;
47
+ /** Client User-Agent, when present on the request. */
48
+ userAgent?: string;
49
+ }
50
+ /** Fields accepted when appending one event; `seq` is assigned by the table. */
51
+ interface AppendAuthAuditEntry {
52
+ actorEmail?: string;
53
+ actorId?: string;
54
+ detail?: Record<string, unknown>;
55
+ event: string;
56
+ ip?: string;
57
+ outcome: AuthAuditOutcome;
58
+ /** See {@link AuthAuditEntry.targetEmail}. */
59
+ targetEmail?: string;
60
+ ts: number;
61
+ userAgent?: string;
62
+ }
63
+ /** Options for {@link appendAuthAuditEntry}. */
64
+ interface AppendAuthAuditOptions {
65
+ /**
66
+ * The key a failed attempt's identifiers are HMAC'd under. A failed attempt can carry text the caller typed into an
67
+ * identifier field, such as a pasted password, and an unkeyed digest of that would be brute-forceable.
68
+ */
69
+ hashKey?: string;
70
+ /**
71
+ * Redact secrets/PII in the `detail` payload before persisting. Defaults to
72
+ * `true`. Set `false` only for a trusted, pre-scrubbed payload.
73
+ */
74
+ redactDetail?: boolean;
75
+ /**
76
+ * Keep only the most recent `retention` rows (trimmed after each append),
77
+ * mirroring the admin audit log's bounded retention. Omit for an unbounded
78
+ * trail (the compliance default) — deliberately NOT capped at 1000.
79
+ */
80
+ retention?: number;
81
+ }
82
+ /** Options for {@link readAuthAuditLog}. */
83
+ interface ReadAuthAuditOptions {
84
+ /** Return only events for this actor id. */
85
+ actorId?: string;
86
+ /** Return only events of this type. */
87
+ event?: string;
88
+ /** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
89
+ limit?: number;
90
+ /**
91
+ * Return only events with `seq` strictly greater than this. Supplying it
92
+ * switches the page to oldest-first so the cursor walks forward; omit it for
93
+ * the newest-first feed.
94
+ */
95
+ sinceSeq?: number;
96
+ }
97
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
98
+ /**
99
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
100
+ * when `retention` is set — trimming the log back to the most recent rows.
101
+ * Creates the table first so callers needn't. Returns the redacted, persisted
102
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
103
+ */
104
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
105
+ /**
106
+ * Read audit events, optionally filtered by `actorId` / `event` and paged past
107
+ * `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's `detail`
108
+ * JSON back into an object. Creates the table first so reads on a never-audited
109
+ * database return `[]` instead of throwing.
110
+ *
111
+ * Ordering follows the cursor: **without** `sinceSeq` the page is newest-first
112
+ * (`seq DESC`) — the feed the studio's Security panel renders. **With**
113
+ * `sinceSeq` it is oldest-first (`seq ASC`), because a lower bound is a forward
114
+ * walk: a descending page above the bound would hand back the newest rows and
115
+ * leave everything between the cursor and them unreachable once the caller
116
+ * advanced past it.
117
+ *
118
+ * `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
119
+ * `Number.NaN`, or an upstream boundary that failed to reject one) falls back
120
+ * to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
121
+ * which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
122
+ * parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
123
+ * rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
124
+ * safety net for every OTHER caller of this function too.
125
+ */
126
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
127
+ /**
128
+ * The auth/security audit read plane the runtime's `authAuditReader` option
129
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
130
+ * its admin gate to back the studio's "Security / audit" page
131
+ * (`__lunora_admin__:getAuthAuditLog`).
132
+ */
133
+ interface AuthAuditReader {
134
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
135
+ }
136
+ /**
137
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
138
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
139
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
140
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
141
+ *
142
+ * ```ts
143
+ * export default createWorker({
144
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
145
+ * // …
146
+ * });
147
+ * ```
148
+ */
149
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
150
+ /**
151
+ * The audit write plane the runtime's `authAuditWriter` option accepts. The worker's admin plane calls
152
+ * better-auth's adapter directly, so its operations never pass through {@link appendAuthAuditEntry}'s
153
+ * better-auth hook; the admin routes record them through this instead. A revoke or delete of one row refuses when
154
+ * nothing matches and records nothing; revoking all of a user's sessions is recorded even when there were none.
155
+ */
156
+ interface AuthAuditWriter {
157
+ write: (entry: AppendAuthAuditEntry) => Promise<void>;
158
+ }
159
+ /**
160
+ * Build the writer the runtime's `authAuditWriter` option accepts, closing over the auth D1 `executor`
161
+ * so admin-plane rows land in the same `__lunora_auth_audit__` table the hook writes, with the same
162
+ * `detail` redaction. Pass the auth instance and, when its `hooks.after` is the audit hook (directly or
163
+ * through `withAuthAudit`), each row also goes through that hook's `retention`, `redactDetail` and
164
+ * `onRecord`, so a SIEM tap sees the admin plane as well as sign-ins.
165
+ */
166
+ declare const createAuthAuditWriter: (executor: SqlExecutor, auth?: {
167
+ options: {
168
+ hooks?: {
169
+ after?: unknown;
170
+ };
171
+ };
172
+ } | null) => AuthAuditWriter;
173
+ export { AUTH_AUDIT_TABLE, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEntry, type AuthAuditEvent, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog };
@@ -0,0 +1,173 @@
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" | "admin-impersonate-start" | "admin-impersonate-stop" | "admin-password-set" | "admin-role-change" | "admin-session-revoke" | "admin-user-ban" | "admin-user-create" | "admin-user-remove" | "admin-user-unban" | "admin-user-update" | "api-key-create" | "api-key-delete" | "api-key-update" | "device-approve" | "device-deny" | "email-change" | "email-change-request" | "email-verification" | "mfa-backup-codes-regenerate" | "mfa-disable" | "mfa-enable" | "oauth-client-create" | "oauth-client-delete" | "oauth-client-keys-rotate" | "oauth-client-secret-rotate" | "oauth-client-update" | "oauth-consent" | "oauth-consent-revoke" | "oauth-consent-update" | "oauth-resource-client-link" | "oauth-resource-client-unlink" | "oauth-resource-create" | "oauth-resource-delete" | "oauth-resource-update" | "oauth-token-issue" | "oauth-token-revoke" | "one-time-token-create" | "org-create" | "org-delete" | "org-invitation-accept" | "org-invitation-cancel" | "org-invitation-create" | "org-invitation-reject" | "org-member-add" | "org-member-leave" | "org-member-remove" | "org-member-role-change" | "org-role-change" | "org-switch" | "org-team-create" | "org-team-member-add" | "org-team-member-remove" | "org-team-remove" | "org-team-switch" | "org-team-update" | "org-update" | "passkey-add" | "passkey-remove" | "passkey-rename" | "password-change" | "password-reset" | "password-reset-request" | "phone-verification" | "scim-group-create" | "scim-group-delete" | "scim-group-update" | "scim-user-create" | "scim-user-delete" | "scim-user-update" | "session-revoke" | "session-switch" | "sign-in" | "sign-in-initiated" | "sign-out" | "sign-up" | "sign-up-invitation-create" | "sign-up-invitation-revoke" | "sso-provider-delete" | "sso-provider-register" | "sso-provider-update" | "token-refresh" | "user-delete" | "user-delete-request" | (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, or the address an admin-plane event acted on.
33
+ * Plain text for a success. For a FAILED attempt it is a keyed digest,
34
+ * `hmac-sha256:<hex>` of the trimmed, lower-cased identifier, because that
35
+ * text is whatever the caller typed (sometimes a pasted password); it is
36
+ * absent when the writer passed no `hashKey`. Unlike `actorEmail` (which
37
+ * requires an authenticated session), this is what lets a FAILED
38
+ * credential-stuffing attempt be grouped by target. Same redaction exemption as `actorEmail`: a
39
+ * top-level column, not a `detail` key, because `AUDIT_REDACT_RULES`
40
+ * scrubs email-shaped values inside `detail` regardless of key name —
41
+ * putting it there would erase exactly this datum. Length-capped to 320
42
+ * chars (RFC 5321) since it carries attacker-controlled request-body text.
43
+ */
44
+ targetEmail?: string;
45
+ /** Wall-clock millis when the event was recorded. */
46
+ ts: number;
47
+ /** Client User-Agent, when present on the request. */
48
+ userAgent?: string;
49
+ }
50
+ /** Fields accepted when appending one event; `seq` is assigned by the table. */
51
+ interface AppendAuthAuditEntry {
52
+ actorEmail?: string;
53
+ actorId?: string;
54
+ detail?: Record<string, unknown>;
55
+ event: string;
56
+ ip?: string;
57
+ outcome: AuthAuditOutcome;
58
+ /** See {@link AuthAuditEntry.targetEmail}. */
59
+ targetEmail?: string;
60
+ ts: number;
61
+ userAgent?: string;
62
+ }
63
+ /** Options for {@link appendAuthAuditEntry}. */
64
+ interface AppendAuthAuditOptions {
65
+ /**
66
+ * The key a failed attempt's identifiers are HMAC'd under. A failed attempt can carry text the caller typed into an
67
+ * identifier field, such as a pasted password, and an unkeyed digest of that would be brute-forceable.
68
+ */
69
+ hashKey?: string;
70
+ /**
71
+ * Redact secrets/PII in the `detail` payload before persisting. Defaults to
72
+ * `true`. Set `false` only for a trusted, pre-scrubbed payload.
73
+ */
74
+ redactDetail?: boolean;
75
+ /**
76
+ * Keep only the most recent `retention` rows (trimmed after each append),
77
+ * mirroring the admin audit log's bounded retention. Omit for an unbounded
78
+ * trail (the compliance default) — deliberately NOT capped at 1000.
79
+ */
80
+ retention?: number;
81
+ }
82
+ /** Options for {@link readAuthAuditLog}. */
83
+ interface ReadAuthAuditOptions {
84
+ /** Return only events for this actor id. */
85
+ actorId?: string;
86
+ /** Return only events of this type. */
87
+ event?: string;
88
+ /** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
89
+ limit?: number;
90
+ /**
91
+ * Return only events with `seq` strictly greater than this. Supplying it
92
+ * switches the page to oldest-first so the cursor walks forward; omit it for
93
+ * the newest-first feed.
94
+ */
95
+ sinceSeq?: number;
96
+ }
97
+ declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
98
+ /**
99
+ * Append one auth event, redacting its `detail` payload (unless disabled) and —
100
+ * when `retention` is set — trimming the log back to the most recent rows.
101
+ * Creates the table first so callers needn't. Returns the redacted, persisted
102
+ * entry (sans `seq`) so an export tap can forward exactly what was stored.
103
+ */
104
+ declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
105
+ /**
106
+ * Read audit events, optionally filtered by `actorId` / `event` and paged past
107
+ * `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's `detail`
108
+ * JSON back into an object. Creates the table first so reads on a never-audited
109
+ * database return `[]` instead of throwing.
110
+ *
111
+ * Ordering follows the cursor: **without** `sinceSeq` the page is newest-first
112
+ * (`seq DESC`) — the feed the studio's Security panel renders. **With**
113
+ * `sinceSeq` it is oldest-first (`seq ASC`), because a lower bound is a forward
114
+ * walk: a descending page above the bound would hand back the newest rows and
115
+ * leave everything between the cursor and them unreachable once the caller
116
+ * advanced past it.
117
+ *
118
+ * `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
119
+ * `Number.NaN`, or an upstream boundary that failed to reject one) falls back
120
+ * to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
121
+ * which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
122
+ * parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
123
+ * rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
124
+ * safety net for every OTHER caller of this function too.
125
+ */
126
+ declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
127
+ /**
128
+ * The auth/security audit read plane the runtime's `authAuditReader` option
129
+ * accepts — a structurally-compatible `{ read }` object the worker calls behind
130
+ * its admin gate to back the studio's "Security / audit" page
131
+ * (`__lunora_admin__:getAuthAuditLog`).
132
+ */
133
+ interface AuthAuditReader {
134
+ read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
135
+ }
136
+ /**
137
+ * Build the reader the runtime's `authAuditReader` option accepts, closing over
138
+ * the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
139
+ * `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
140
+ * through to {@link readAuthAuditLog} (which clamps `limit`).
141
+ *
142
+ * ```ts
143
+ * export default createWorker({
144
+ * authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
145
+ * // …
146
+ * });
147
+ * ```
148
+ */
149
+ declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
150
+ /**
151
+ * The audit write plane the runtime's `authAuditWriter` option accepts. The worker's admin plane calls
152
+ * better-auth's adapter directly, so its operations never pass through {@link appendAuthAuditEntry}'s
153
+ * better-auth hook; the admin routes record them through this instead. A revoke or delete of one row refuses when
154
+ * nothing matches and records nothing; revoking all of a user's sessions is recorded even when there were none.
155
+ */
156
+ interface AuthAuditWriter {
157
+ write: (entry: AppendAuthAuditEntry) => Promise<void>;
158
+ }
159
+ /**
160
+ * Build the writer the runtime's `authAuditWriter` option accepts, closing over the auth D1 `executor`
161
+ * so admin-plane rows land in the same `__lunora_auth_audit__` table the hook writes, with the same
162
+ * `detail` redaction. Pass the auth instance and, when its `hooks.after` is the audit hook (directly or
163
+ * through `withAuthAudit`), each row also goes through that hook's `retention`, `redactDetail` and
164
+ * `onRecord`, so a SIEM tap sees the admin plane as well as sign-ins.
165
+ */
166
+ declare const createAuthAuditWriter: (executor: SqlExecutor, auth?: {
167
+ options: {
168
+ hooks?: {
169
+ after?: unknown;
170
+ };
171
+ };
172
+ } | null) => AuthAuditWriter;
173
+ export { AUTH_AUDIT_TABLE, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEntry, type AuthAuditEvent, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog };
package/dist/audit.mjs ADDED
@@ -0,0 +1 @@
1
+ import{A,a,c as r,b as u,e as d,r as s}from"./packem_shared/audit-daeExZWv.mjs";export{A as AUTH_AUDIT_TABLE,a as appendAuthAuditEntry,r as createAuthAuditReader,u as createAuthAuditWriter,d as ensureAuthAuditTable,s as readAuthAuditLog};
@@ -0,0 +1 @@
1
+ export { fetchClientMetadataResource as default } from '@better-auth/cimd/node';
@@ -0,0 +1 @@
1
+ export { fetchClientMetadataResource as default } from '@better-auth/cimd/node';
@@ -0,0 +1 @@
1
+ import{fetchClientMetadataResource as a}from"@better-auth/cimd/node";export{a as default};
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The Cloudflare Workers transport for `cimd()` (Client ID Metadata Documents).
3
+ *
4
+ * `@better-auth/cimd` fetches a URL the client hands it — the `client_id` itself,
5
+ * and any `jwks_uri` the document names — so the fetch is server-side request
6
+ * forgery waiting to happen unless the transport keeps it on the public internet.
7
+ * The plugin therefore makes the application supply that transport, and asks it to
8
+ * resolve the host once, reject special-use addresses, pin the connection and
9
+ * refuse redirects.
10
+ *
11
+ * A Worker cannot pin a connection or see the resolved address. What it can do is
12
+ * run with the global_fetch_strictly_public compatibility flag, under which every
13
+ * global `fetch` goes out to the public internet and never to a private or
14
+ * special-use address, the Worker's own zone included. That is the guarantee
15
+ * Cloudflare's own `@cloudflare/workers-oauth-provider` builds its CIMD support on,
16
+ * and the one this transport requires: {@link workersCimdFetch} refuses to build
17
+ * without the flag, so a misconfigured deploy fails at startup instead of quietly
18
+ * fetching attacker-chosen internal URLs.
19
+ *
20
+ * It is weaker than the letter of cimd's contract — there is no DNS pinning, so a
21
+ * rebinding host still reaches *some* public address. An origin allowlist (the
22
+ * isMetadataDocumentUrlAllowed option) narrows that to hosts you trust, but it only
23
+ * gates the `client_id` fetch: oauth-provider fetches a document's `jwks_uri`
24
+ * through this same transport without consulting it. Add `jwks_uri` to cimd's
25
+ * originBoundFields so it must share the allowlisted `client_id` origin.
26
+ *
27
+ * On Node, use the default export of `@lunora/auth/cimd/node`, which
28
+ * does pin the connection.
29
+ *
30
+ * Kept off the package root (and out of `./plugins`) because it is Workers-only:
31
+ * the flag probe means nothing on any other runtime.
32
+ */
33
+ import { ClientMetadataResourceFetch } from '@better-auth/oauth-provider';
34
+ /**
35
+ * Build the `fetchClientMetadataResource` transport for `cimd()` on Cloudflare
36
+ * Workers.
37
+ *
38
+ * ```ts
39
+ * import { cimd, jwt, mcp } from "@lunora/auth/plugins";
40
+ * import workersCimdFetch from "@lunora/auth/cimd/workers";
41
+ *
42
+ * plugins: [
43
+ * jwt(),
44
+ * mcp({ … }),
45
+ * cimd({
46
+ * fetchClientMetadataResource: workersCimdFetch(),
47
+ * metadataProfile: "mcp-2026-07-28",
48
+ * isMetadataDocumentUrlAllowed: (url) => new URL(url).origin === "https://claude.ai",
49
+ * // The allowlist gates only the `client_id` fetch; bind `jwks_uri` to it too.
50
+ * originBoundFields: ["post_logout_redirect_uris", "client_uri", "jwks_uri"],
51
+ * }),
52
+ * ];
53
+ * ```
54
+ *
55
+ * The returned transport only issues `GET` / `HEAD` to `https:` URLs without
56
+ * credentials, and never follows a redirect: it fetches with `redirect: "manual"`
57
+ * (workerd does not implement `"error"`) and throws on any redirect status, which
58
+ * cimd reports as `invalid_client`. A `304` from a conditional revalidation passes
59
+ * through.
60
+ * @throws LunoraError `AUTH_CIMD_FETCH_NOT_PUBLIC` when the Worker runs without the
61
+ * `global_fetch_strictly_public` compatibility flag.
62
+ */
63
+ declare const workersCimdFetch: () => ClientMetadataResourceFetch;
64
+ export { workersCimdFetch as default };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The Cloudflare Workers transport for `cimd()` (Client ID Metadata Documents).
3
+ *
4
+ * `@better-auth/cimd` fetches a URL the client hands it — the `client_id` itself,
5
+ * and any `jwks_uri` the document names — so the fetch is server-side request
6
+ * forgery waiting to happen unless the transport keeps it on the public internet.
7
+ * The plugin therefore makes the application supply that transport, and asks it to
8
+ * resolve the host once, reject special-use addresses, pin the connection and
9
+ * refuse redirects.
10
+ *
11
+ * A Worker cannot pin a connection or see the resolved address. What it can do is
12
+ * run with the global_fetch_strictly_public compatibility flag, under which every
13
+ * global `fetch` goes out to the public internet and never to a private or
14
+ * special-use address, the Worker's own zone included. That is the guarantee
15
+ * Cloudflare's own `@cloudflare/workers-oauth-provider` builds its CIMD support on,
16
+ * and the one this transport requires: {@link workersCimdFetch} refuses to build
17
+ * without the flag, so a misconfigured deploy fails at startup instead of quietly
18
+ * fetching attacker-chosen internal URLs.
19
+ *
20
+ * It is weaker than the letter of cimd's contract — there is no DNS pinning, so a
21
+ * rebinding host still reaches *some* public address. An origin allowlist (the
22
+ * isMetadataDocumentUrlAllowed option) narrows that to hosts you trust, but it only
23
+ * gates the `client_id` fetch: oauth-provider fetches a document's `jwks_uri`
24
+ * through this same transport without consulting it. Add `jwks_uri` to cimd's
25
+ * originBoundFields so it must share the allowlisted `client_id` origin.
26
+ *
27
+ * On Node, use the default export of `@lunora/auth/cimd/node`, which
28
+ * does pin the connection.
29
+ *
30
+ * Kept off the package root (and out of `./plugins`) because it is Workers-only:
31
+ * the flag probe means nothing on any other runtime.
32
+ */
33
+ import { ClientMetadataResourceFetch } from '@better-auth/oauth-provider';
34
+ /**
35
+ * Build the `fetchClientMetadataResource` transport for `cimd()` on Cloudflare
36
+ * Workers.
37
+ *
38
+ * ```ts
39
+ * import { cimd, jwt, mcp } from "@lunora/auth/plugins";
40
+ * import workersCimdFetch from "@lunora/auth/cimd/workers";
41
+ *
42
+ * plugins: [
43
+ * jwt(),
44
+ * mcp({ … }),
45
+ * cimd({
46
+ * fetchClientMetadataResource: workersCimdFetch(),
47
+ * metadataProfile: "mcp-2026-07-28",
48
+ * isMetadataDocumentUrlAllowed: (url) => new URL(url).origin === "https://claude.ai",
49
+ * // The allowlist gates only the `client_id` fetch; bind `jwks_uri` to it too.
50
+ * originBoundFields: ["post_logout_redirect_uris", "client_uri", "jwks_uri"],
51
+ * }),
52
+ * ];
53
+ * ```
54
+ *
55
+ * The returned transport only issues `GET` / `HEAD` to `https:` URLs without
56
+ * credentials, and never follows a redirect: it fetches with `redirect: "manual"`
57
+ * (workerd does not implement `"error"`) and throws on any redirect status, which
58
+ * cimd reports as `invalid_client`. A `304` from a conditional revalidation passes
59
+ * through.
60
+ * @throws LunoraError `AUTH_CIMD_FETCH_NOT_PUBLIC` when the Worker runs without the
61
+ * `global_fetch_strictly_public` compatibility flag.
62
+ */
63
+ declare const workersCimdFetch: () => ClientMetadataResourceFetch;
64
+ export { workersCimdFetch as default };
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";const a="global_fetch_strictly_public",i=()=>{const{Cloudflare:t}=globalThis;return t?.compatibilityFlags?.[a]===!0},n=new Set([301,302,303,307,308]),l=t=>n.has(t.status)||t.type==="opaqueredirect",d=()=>{if(!i())throw new c("AUTH_CIMD_FETCH_NOT_PUBLIC",`CIMD needs the "${a}" compatibility flag, so metadata fetches cannot reach private addresses. Add it to "compatibility_flags" in wrangler.jsonc.`);return async(t,s)=>{const e=new Request(t,{...s,redirect:"manual"}),r=new URL(e.url);if(r.protocol!=="https:")throw new TypeError(`refusing to fetch a client metadata resource over ${r.protocol}`);if(r.username!==""||r.password!=="")throw new TypeError("refusing to fetch a client metadata resource URL that carries credentials");if(e.method!=="GET"&&e.method!=="HEAD")throw new TypeError(`refusing to ${e.method} a client metadata resource`);const o=await fetch(e);if(l(o))throw new TypeError("client metadata resource fetches must not follow redirects");return o}};export{d as default};