@lunora/auth 1.0.0-alpha.26 → 1.0.0-alpha.261
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +233 -104
- package/README.md +105 -15
- package/dist/adapter.d.mts +4 -43
- package/dist/adapter.d.ts +4 -43
- package/dist/adapter.mjs +1 -48
- package/dist/audit.d.mts +142 -0
- package/dist/audit.d.ts +142 -0
- package/dist/audit.mjs +12 -0
- package/dist/cimd-node.d.mts +1 -0
- package/dist/cimd-node.d.ts +1 -0
- package/dist/cimd-node.mjs +1 -0
- package/dist/cimd-workers.d.mts +64 -0
- package/dist/cimd-workers.d.ts +64 -0
- package/dist/cimd-workers.mjs +1 -0
- package/dist/email-guard.d.mts +143 -0
- package/dist/email-guard.d.ts +143 -0
- package/dist/email-guard.mjs +1 -0
- package/dist/index.d.mts +426 -544
- package/dist/index.d.ts +426 -544
- package/dist/index.mjs +1 -12
- package/dist/middleware.d.mts +165 -155
- package/dist/middleware.d.ts +165 -155
- package/dist/middleware.mjs +1 -56
- package/dist/migrate.d.mts +47 -0
- package/dist/migrate.d.ts +47 -0
- package/dist/migrate.mjs +1 -0
- package/dist/packem_shared/AUTH_DO_AUDIT_PATH-DbYrTk_T.mjs +1 -0
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs +1 -0
- package/dist/packem_shared/LunoraAuthAdminError-y7tL8fRi.mjs +1 -0
- package/dist/packem_shared/adapter-CBZ17jKi.mjs +2 -0
- package/dist/packem_shared/adapter.d-CElAPJ1U.d.ts +88 -0
- package/dist/packem_shared/adapter.d-CaPwF2v3.d.mts +88 -0
- package/dist/packem_shared/auth-do-DHxBZtyS.mjs +1 -0
- package/dist/packem_shared/authAuditHook-DPTKdjBe.mjs +1 -0
- package/dist/packem_shared/authDiscoveryPaths-BtKCs_3V.mjs +1 -0
- package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
- package/dist/packem_shared/create-auth.d-DNGo48je.d.mts +146 -0
- package/dist/packem_shared/create-auth.d-DNGo48je.d.ts +146 -0
- package/dist/packem_shared/createAuth-Dioo_-mD.mjs +1 -0
- package/dist/packem_shared/createDoAuthWiring-BXyBVIda.mjs +1 -0
- package/dist/packem_shared/createLunoraAuthClient-Ca1AdNhq.mjs +1 -0
- package/dist/packem_shared/createSignUpInvitation-DHZL9fNl.mjs +1 -0
- package/dist/packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs +1 -0
- package/dist/packem_shared/handleAuthRequest-Id9Vv_Tk.mjs +1 -0
- package/dist/packem_shared/identity-claims-hAvIl2wm.mjs +1 -0
- package/dist/packem_shared/invite-only.d-BAKOiLTW.d.ts +126 -0
- package/dist/packem_shared/invite-only.d-BDErbVxw.d.mts +126 -0
- package/dist/packem_shared/isDevEnvironment-yLbPngwn.mjs +1 -0
- package/dist/packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs +1 -0
- package/dist/packem_shared/mcp-CK5XkDFp.mjs +1 -0
- package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
- package/dist/packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs +1 -0
- package/dist/packem_shared/sessionPresets-C867Mlo4.mjs +1 -0
- package/dist/packem_shared/sql-store-uMubPYI9.mjs +1 -0
- package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
- package/dist/packem_shared/worker.d-CR5A_T7A.d.mts +789 -0
- package/dist/packem_shared/worker.d-DHZUCAyH.d.ts +789 -0
- package/dist/plugins-client.d.mts +251 -1
- package/dist/plugins-client.d.ts +251 -1
- package/dist/plugins-client.mjs +1 -2
- package/dist/plugins-enterprise-client.d.mts +13 -0
- package/dist/plugins-enterprise-client.d.ts +13 -0
- package/dist/plugins-enterprise-client.mjs +1 -0
- package/dist/plugins-enterprise.d.mts +1669 -0
- package/dist/plugins-enterprise.d.ts +1669 -0
- package/dist/plugins-enterprise.mjs +1 -0
- package/dist/plugins.d.mts +167 -2
- package/dist/plugins.d.ts +167 -2
- package/dist/plugins.mjs +1 -22
- package/dist/schema.d.mts +39 -39
- package/dist/schema.d.ts +39 -39
- package/dist/schema.mjs +1 -62
- package/dist/sql-store.d.mts +43 -28
- package/dist/sql-store.d.ts +43 -28
- package/dist/sql-store.mjs +1 -184
- package/dist/store.d.mts +65 -47
- package/dist/store.d.ts +65 -47
- package/dist/store.mjs +1 -183
- package/dist/turnstile-middleware.d.mts +73 -55
- package/dist/turnstile-middleware.d.ts +73 -55
- package/dist/turnstile-middleware.mjs +1 -34
- package/dist/turnstile.d.mts +42 -49
- package/dist/turnstile.d.ts +42 -49
- package/dist/turnstile.mjs +1 -54
- package/dist/worker.d.mts +9 -0
- package/dist/worker.d.ts +9 -0
- package/dist/worker.mjs +1 -0
- package/package.json +58 -7
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
- package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
- package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.mjs +0 -29
- package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
- package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
- package/dist/packem_shared/createAuth-BVMMllTm.mjs +0 -87
- package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
package/dist/adapter.mjs
CHANGED
|
@@ -1,48 +1 @@
|
|
|
1
|
-
import
|
|
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 t,a as p,b as e}from"./packem_shared/adapter-CBZ17jKi.mjs";import"./packem_shared/sql-store-uMubPYI9.mjs";export{t as lunoraAuthAdapter,p as lunoraD1Adapter,e as lunoraDoAdapter};
|
package/dist/audit.d.mts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
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
|
+
/**
|
|
83
|
+
* Return only events with `seq` strictly greater than this. Supplying it
|
|
84
|
+
* switches the page to oldest-first so the cursor walks forward; omit it for
|
|
85
|
+
* the newest-first feed.
|
|
86
|
+
*/
|
|
87
|
+
sinceSeq?: number;
|
|
88
|
+
}
|
|
89
|
+
declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Append one auth event, redacting its `detail` payload (unless disabled) and —
|
|
92
|
+
* when `retention` is set — trimming the log back to the most recent rows.
|
|
93
|
+
* Creates the table first so callers needn't. Returns the redacted, persisted
|
|
94
|
+
* entry (sans `seq`) so an export tap can forward exactly what was stored.
|
|
95
|
+
*/
|
|
96
|
+
declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
|
|
97
|
+
/**
|
|
98
|
+
* Read audit events, optionally filtered by `actorId` / `event` and paged past
|
|
99
|
+
* `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's `detail`
|
|
100
|
+
* JSON back into an object. Creates the table first so reads on a never-audited
|
|
101
|
+
* database return `[]` instead of throwing.
|
|
102
|
+
*
|
|
103
|
+
* Ordering follows the cursor: **without** `sinceSeq` the page is newest-first
|
|
104
|
+
* (`seq DESC`) — the feed the studio's Security panel renders. **With**
|
|
105
|
+
* `sinceSeq` it is oldest-first (`seq ASC`), because a lower bound is a forward
|
|
106
|
+
* walk: a descending page above the bound would hand back the newest rows and
|
|
107
|
+
* leave everything between the cursor and them unreachable once the caller
|
|
108
|
+
* advanced past it.
|
|
109
|
+
*
|
|
110
|
+
* `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
|
|
111
|
+
* `Number.NaN`, or an upstream boundary that failed to reject one) falls back
|
|
112
|
+
* to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
|
|
113
|
+
* which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
|
|
114
|
+
* parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
|
|
115
|
+
* rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
|
|
116
|
+
* safety net for every OTHER caller of this function too.
|
|
117
|
+
*/
|
|
118
|
+
declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
119
|
+
/**
|
|
120
|
+
* The auth/security audit read plane the runtime's `authAuditReader` option
|
|
121
|
+
* accepts — a structurally-compatible `{ read }` object the worker calls behind
|
|
122
|
+
* its admin gate to back the studio's "Security / audit" page
|
|
123
|
+
* (`__lunora_admin__:getAuthAuditLog`).
|
|
124
|
+
*/
|
|
125
|
+
interface AuthAuditReader {
|
|
126
|
+
read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Build the reader the runtime's `authAuditReader` option accepts, closing over
|
|
130
|
+
* the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
|
|
131
|
+
* `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
|
|
132
|
+
* through to {@link readAuthAuditLog} (which clamps `limit`).
|
|
133
|
+
*
|
|
134
|
+
* ```ts
|
|
135
|
+
* export default createWorker({
|
|
136
|
+
* authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
|
|
137
|
+
* // …
|
|
138
|
+
* });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
|
|
142
|
+
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.d.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
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
|
+
/**
|
|
83
|
+
* Return only events with `seq` strictly greater than this. Supplying it
|
|
84
|
+
* switches the page to oldest-first so the cursor walks forward; omit it for
|
|
85
|
+
* the newest-first feed.
|
|
86
|
+
*/
|
|
87
|
+
sinceSeq?: number;
|
|
88
|
+
}
|
|
89
|
+
declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Append one auth event, redacting its `detail` payload (unless disabled) and —
|
|
92
|
+
* when `retention` is set — trimming the log back to the most recent rows.
|
|
93
|
+
* Creates the table first so callers needn't. Returns the redacted, persisted
|
|
94
|
+
* entry (sans `seq`) so an export tap can forward exactly what was stored.
|
|
95
|
+
*/
|
|
96
|
+
declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
|
|
97
|
+
/**
|
|
98
|
+
* Read audit events, optionally filtered by `actorId` / `event` and paged past
|
|
99
|
+
* `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's `detail`
|
|
100
|
+
* JSON back into an object. Creates the table first so reads on a never-audited
|
|
101
|
+
* database return `[]` instead of throwing.
|
|
102
|
+
*
|
|
103
|
+
* Ordering follows the cursor: **without** `sinceSeq` the page is newest-first
|
|
104
|
+
* (`seq DESC`) — the feed the studio's Security panel renders. **With**
|
|
105
|
+
* `sinceSeq` it is oldest-first (`seq ASC`), because a lower bound is a forward
|
|
106
|
+
* walk: a descending page above the bound would hand back the newest rows and
|
|
107
|
+
* leave everything between the cursor and them unreachable once the caller
|
|
108
|
+
* advanced past it.
|
|
109
|
+
*
|
|
110
|
+
* `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
|
|
111
|
+
* `Number.NaN`, or an upstream boundary that failed to reject one) falls back
|
|
112
|
+
* to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
|
|
113
|
+
* which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
|
|
114
|
+
* parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
|
|
115
|
+
* rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
|
|
116
|
+
* safety net for every OTHER caller of this function too.
|
|
117
|
+
*/
|
|
118
|
+
declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
119
|
+
/**
|
|
120
|
+
* The auth/security audit read plane the runtime's `authAuditReader` option
|
|
121
|
+
* accepts — a structurally-compatible `{ read }` object the worker calls behind
|
|
122
|
+
* its admin gate to back the studio's "Security / audit" page
|
|
123
|
+
* (`__lunora_admin__:getAuthAuditLog`).
|
|
124
|
+
*/
|
|
125
|
+
interface AuthAuditReader {
|
|
126
|
+
read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Build the reader the runtime's `authAuditReader` option accepts, closing over
|
|
130
|
+
* the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
|
|
131
|
+
* `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
|
|
132
|
+
* through to {@link readAuthAuditLog} (which clamps `limit`).
|
|
133
|
+
*
|
|
134
|
+
* ```ts
|
|
135
|
+
* export default createWorker({
|
|
136
|
+
* authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
|
|
137
|
+
* // …
|
|
138
|
+
* });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
|
|
142
|
+
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 N,piiRules as D,redact as $}from"@visulima/redact";const C=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),x=new Set(["card","pass","pin","session"]),U=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),M=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),z=new Set(["card no","connection string","database url","one time"]),W=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],F=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),G=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),X=new Set(["max","min","num","total"]),S=4096,Z=128,j=16384,l="<REDACTED>",P="[redaction budget exceeded]",v=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),y=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,H=(e,t)=>{const n=y(e[t]),s=t>0?y(e[t-1]):void 0;if(C.has(n))return n;if(s!==void 0){if(n==="key"&&U.has(s))return"key";if(n==="code"&&M.has(s))return"code";if(z.has(`${s} ${n}`))return`${s} ${n}`}return W.some(a=>n.endsWith(a))?n:void 0},k=e=>{const t=v(e);if(t.length===0)return"none";const n=G.has(t.at(-1))||X.has(t[0]);for(let s=t.length-1;s>=0;s-=1){const a=H(t,s);if(a!==void 0)return n?"count-secret":t.slice(s+1).every(i=>F.has(i))?x.has(a)&&s===t.length-1?"scalar-secret":"secret":"none"}return"none"},V=e=>typeof e=="boolean"||e===null||e===void 0?e:l,q=e=>{const t=e.indexOf("://")+3,n=e.slice(t),s=n.split(/[?#]/,1)[0],a=s.lastIndexOf("@"),i=s.indexOf(":"),c=s.indexOf("/"),r=i!==-1&&/^\d+$/.test(s.slice(i+1,c===-1?void 0:c)),o=i!==-1&&!r&&(c===-1||i<c);if(a===-1&&o&&n.includes("@",s.length))return e.slice(0,t);const d=a!==-1&&(c===-1||a<c||i!==-1&&i<a&&!r);return`${e.slice(0,t)}${d?s.slice(a+1):s}`},B=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Y=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,K=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,R=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,I=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],J=String.raw`(?<=^|[^\w-]|${R})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Q=new RegExp([...I.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${R})${t}${e}`),J].join("|"),"g"),ee=new RegExp([...I.map(({prefix:e})=>e),"eyJ"].join("|")),te=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,f=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,w=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,b=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ne=e=>{let t="",n=0;f.lastIndex=0;for(let s=f.exec(e);s!==null;s=f.exec(e)){const a=k(s[2]),i=s.index+s[0].length;w.lastIndex=i;const c=a==="none"?null:w.exec(e);if(c===null||a==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){f.lastIndex=Math.max(i,s.index+1);continue}const r=c[0],o=r.startsWith('\\"')?'\\"':r.startsWith('"')||r.startsWith("'")?r[0]:"";let d=i+r.length;o===""&&s[3]===":"&&(b.lastIndex=d,d+=b.exec(e)?.[0].length??0),t+=`${e.slice(n,i)}${o}${l}${r.length>o.length&&r.endsWith(o)?o:""}`,n=d,f.lastIndex=n}return t+e.slice(n)},se=/[:=@]|basic|bearer|digest|-u\b|--/i,re=e=>{const t=ee.test(e);if(!t&&!se.test(e))return e;const n=e.replaceAll(Y,`-----BEGIN $1-----${l}`).replaceAll(B,q).replaceAll(K,`$1 ${l}`);return ne((t?n.replaceAll(Q,l):n).replaceAll(te,`$1$2$3${l}`))},ae=(e,t)=>{if(t.remaining<=0)return P;const n=e.slice(0,S+Z);t.remaining-=n.length;const s=re(n);return s.length>S||e.length>n.length?`${s.slice(0,S)}…[truncated]`:s},ie=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),g=Symbol("no-json"),oe=e=>{const{toJSON:t}=e;if(typeof t!="function")return g;try{const n=t.call(e);return n===e?g:n}catch{return g}},ce=32,u=(e,t,n,s,a)=>{if(typeof e=="string")return s?l:ae(e,a);if(typeof e!="object"||e===null||!Array.isArray(e)&&ie(e))return e;if(t.has(e)||n>=ce)return l;const i=Array.isArray(e)?g:oe(e);if(i!==g){t.add(e);const r=u(i,t,n+1,s,a);return t.delete(e),r}t.add(e);const c=Array.isArray(e)?e.map(r=>u(r,t,n+1,s,a)):Object.fromEntries(Object.entries(e).map(([r,o])=>{const d=k(r);return d==="secret"||d==="scalar-secret"&&(typeof o!="object"||o===null)?[r,V(o)]:[r,u(o,t,n+1,d==="count-secret"&&(typeof o=="string"||Array.isArray(o)),a)]}));return t.delete(e),c},de=e=>u(e,new WeakSet,0,!1,{remaining:j}),E="__lunora_auth_audit__",le=[...N,...D],pe=1e3,Ae=1e4,A=null,m=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},Ee=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${E}" (
|
|
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 "${E}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},_=new WeakMap,L=e=>{const t=_.get(e);if(t)return t;const n=Ee(e);return _.set(e,n),n.catch(()=>_.delete(e)),n},ue=async(e,t,n={})=>{await L(e);let s;return t.detail!==void 0&&(s=n.redactDetail===!1?t.detail:$(de(t.detail),le)),await e.run(`INSERT INTO "${E}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??A,t.actorEmail??A,t.targetEmail??A,t.ip??A,t.userAgent??A,s===void 0?A:JSON.stringify(s)]),typeof n.retention=="number"&&n.retention>0&&await e.run(`DELETE FROM "${E}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${E}")`,[n.retention]),{...t,detail:s}},fe=async(e,t={})=>{await L(e);const n=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,Ae)):pe,s=["seq > ?"],a=[t.sinceSeq??0],i=t.sinceSeq===void 0?"DESC":"ASC";return t.actorId!==void 0&&(s.push("actor_id = ?"),a.push(t.actorId)),t.event!==void 0&&(s.push("event = ?"),a.push(t.event)),a.push(n),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${E}" WHERE ${s.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,a)).map(r=>{const o={event:m(r.event)??"",outcome:r.outcome==="failure"?"failure":"success",seq:Number(r.seq),ts:Number(r.ts)},d=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[p,O]of d){const T=m(r[O]);T!==void 0&&(o[p]=T)}const h=m(r.detail);if(h!==void 0)try{const p=JSON.parse(h);typeof p=="object"&&p!==null&&!Array.isArray(p)&&(o.detail=p)}catch{}return o})},Se=e=>({read:t=>fe(e,t)});export{E as AUTH_AUDIT_TABLE,ue as appendAuthAuditEntry,Se as createAuthAuditReader,L as ensureAuthAuditTable,fe 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};
|
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
* Which built-in lists {@link assertEmailAllowed} loads (both by default, so the
|
|
38
|
+
* returned class is complete). The disposable list is ~2.7 MB and the free list
|
|
39
|
+
* ~143 KB of bundle; `emailGateMiddleware` and `emailGateDatabaseHooks` set this
|
|
40
|
+
* for you: the free list loads only with `onClassify`, the disposable list only
|
|
41
|
+
* with `blockDisposable !== false` or `onClassify`.
|
|
42
|
+
*/
|
|
43
|
+
lists?: {
|
|
44
|
+
disposable?: boolean;
|
|
45
|
+
free?: boolean;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Opt-in MX deliverability verification. Off by default because it needs DNS
|
|
49
|
+
* (`@visulima/email-verifier/checks/mx` → `node:dns`), which is not available
|
|
50
|
+
* on the default workerd path. When `true`, {@link assertEmailAllowed} rejects
|
|
51
|
+
* an address whose domain publishes no MX (or fallback A/AAAA) records with
|
|
52
|
+
* `EMAIL_UNDELIVERABLE`. The check is loaded via a dynamic import, so leaving
|
|
53
|
+
* this off keeps the DNS module out of the bundle entirely.
|
|
54
|
+
*/
|
|
55
|
+
mx?: boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Reject structurally invalid addresses up front (via
|
|
58
|
+
* `@visulima/email-verifier/checks/syntax`, pure-data/edge-safe). Defaults to
|
|
59
|
+
* `true`. When `false`, an unparseable address classifies as `business` with
|
|
60
|
+
* `domain: undefined` and is not rejected on syntax alone.
|
|
61
|
+
*/
|
|
62
|
+
requireValidSyntax?: boolean;
|
|
63
|
+
}
|
|
64
|
+
/** Options for {@link emailGateMiddleware}: the base gate config plus how to read the email from `ctx`. */
|
|
65
|
+
interface EmailGateMiddlewareOptions<Context> extends EmailGateConfig {
|
|
66
|
+
/**
|
|
67
|
+
* Selector that pulls the signup email off `ctx`. The procedure context
|
|
68
|
+
* carries only the resolved identity, not the raw request body, so the email
|
|
69
|
+
* travels in the function `args` — which the builder surfaces to middleware
|
|
70
|
+
* as `ctx.args` (validated, frozen). Mirrors `verifyTurnstileMiddleware`'s
|
|
71
|
+
* `token` selector:
|
|
72
|
+
*
|
|
73
|
+
* ```ts
|
|
74
|
+
* export const signUp = mutation
|
|
75
|
+
* .input({ email: v.string() })
|
|
76
|
+
* .use(emailGateMiddleware({ email: (ctx) => ctx.args.email }))
|
|
77
|
+
* .mutation(async ({ args, ctx }) => { … });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
email: (context: Context) => string | undefined;
|
|
81
|
+
/**
|
|
82
|
+
* Called with the resolved classification once the gate passes, so app policy
|
|
83
|
+
* can branch on `free` vs `business` (e.g. gate a plan behind a business
|
|
84
|
+
* email). Never fires when the gate rejects.
|
|
85
|
+
*/
|
|
86
|
+
onClassify?: (classification: EmailClassification, context: Context) => void;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Inject the built-in domain lists into the lookup packages, once each. Call this
|
|
90
|
+
* at worker init on workerd (where the packages' `node:fs` loader is unavailable)
|
|
91
|
+
* so {@link classifyEmail} has data to match against; {@link assertEmailAllowed} /
|
|
92
|
+
* {@link emailGateMiddleware} await it for you, loading only what the config needs.
|
|
93
|
+
* Both lists (~2.7 MB disposable, ~143 KB free) load by default; pass
|
|
94
|
+
* `{ free: false }` or `{ disposable: false }` to skip one. Idempotent — repeat
|
|
95
|
+
* calls share one load per list.
|
|
96
|
+
*/
|
|
97
|
+
declare const loadEmailDomainLists: ({ disposable, free }?: {
|
|
98
|
+
disposable?: boolean;
|
|
99
|
+
free?: boolean;
|
|
100
|
+
}) => Promise<void>;
|
|
101
|
+
/**
|
|
102
|
+
* Classify an email address' domain as `disposable` / `free` / `business`,
|
|
103
|
+
* pure-data and edge-safe (no DNS, no filesystem). A structurally invalid
|
|
104
|
+
* address resolves to `{ domain: undefined, emailClass: "business" }` — use
|
|
105
|
+
* {@link assertEmailAllowed} (which can reject on syntax) for the gating path.
|
|
106
|
+
* `allowDomains` wins over both lists; `denyDomains` adds to the disposable list.
|
|
107
|
+
*
|
|
108
|
+
* The lookup relies on the built-in domain lists being loaded. On Node they
|
|
109
|
+
* auto-load from disk; on workerd, `await loadEmailDomainLists()` first (or use
|
|
110
|
+
* {@link assertEmailAllowed} / {@link emailGateMiddleware}, which await it).
|
|
111
|
+
*
|
|
112
|
+
* The returned/compared domain is IDNA-normalized (see {@link toAsciiDomain}) so
|
|
113
|
+
* a Unicode-form internationalized domain matches its `xn--` blocklist entry.
|
|
114
|
+
*/
|
|
115
|
+
declare const classifyEmail: (email: string, config?: EmailGateConfig) => EmailClassification;
|
|
116
|
+
/**
|
|
117
|
+
* Classify `email` and enforce the gate, throwing a coded {@link LunoraError}
|
|
118
|
+
* when it fails: `VALIDATION_ERROR` (structurally invalid, only when
|
|
119
|
+
* `requireValidSyntax`, the default), `EMAIL_DOMAIN_BLOCKED` (disposable or
|
|
120
|
+
* deny-listed, only when `blockDisposable`, the default), or `EMAIL_UNDELIVERABLE`
|
|
121
|
+
* (no MX records, only when `mx: true`).
|
|
122
|
+
*
|
|
123
|
+
* Returns the {@link EmailClassification} on success so callers can branch on
|
|
124
|
+
* `free` vs `business`. Async only because of the opt-in MX step; with `mx` off
|
|
125
|
+
* it resolves without any network I/O.
|
|
126
|
+
*/
|
|
127
|
+
declare const assertEmailAllowed: (email: string, config?: EmailGateConfig) => Promise<EmailClassification>;
|
|
128
|
+
/**
|
|
129
|
+
* Lunora procedure middleware that gates a non-auth, signup-shaped
|
|
130
|
+
* `mutation`/`action` on the email-domain policy. Attach it with `.use()`; it
|
|
131
|
+
* reads the email from `ctx` via the `email` selector (declare it with
|
|
132
|
+
* `.input(...)` and read it back as `ctx.args.email`)
|
|
133
|
+
* and runs {@link assertEmailAllowed}, which throws a coded {@link LunoraError}
|
|
134
|
+
* (`EMAIL_DOMAIN_BLOCKED` / `EMAIL_UNDELIVERABLE` / `VALIDATION_ERROR`) the
|
|
135
|
+
* runtime maps to the matching status.
|
|
136
|
+
*
|
|
137
|
+
* To gate better-auth's native `/sign-up/email` endpoint instead, use
|
|
138
|
+
* `emailGateDatabaseHooks` / `withEmailGate` from `@lunora/auth` — those hook
|
|
139
|
+
* better-auth's own user-create path. The `Middleware` import is type-only, so
|
|
140
|
+
* this stays free of any runtime `@lunora/server` dependency.
|
|
141
|
+
*/
|
|
142
|
+
declare const emailGateMiddleware: <Context>(options: EmailGateMiddlewareOptions<Context>) => Middleware<Context, Context>;
|
|
143
|
+
export { type EmailClass, type EmailClassification, type EmailGateConfig, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists };
|