@lunora/auth 1.0.0-alpha.27 → 1.0.0-alpha.270
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 +107 -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 +147 -0
- package/dist/audit.d.ts +147 -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 +469 -544
- package/dist/index.d.ts +469 -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-fIdwSspk.mjs +1 -0
- package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs +1 -0
- package/dist/packem_shared/LunoraAuthAdminError-Ce2uHRXx.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/api-key-storage-D15k9_CF.mjs +1 -0
- package/dist/packem_shared/apiKey-B9uGt5Nc.mjs +1 -0
- package/dist/packem_shared/auth-do-BQPWOWW0.mjs +1 -0
- package/dist/packem_shared/authAuditBeforeHook-CQxnNVQq.mjs +1 -0
- package/dist/packem_shared/authCredentialColumns-C09M65Uc.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-QQ66RlWp.d.mts +149 -0
- package/dist/packem_shared/create-auth.d-QQ66RlWp.d.ts +149 -0
- package/dist/packem_shared/createAuth-EjuBT-g8.mjs +1 -0
- package/dist/packem_shared/createDoAuthWiring-DRWvSJIC.mjs +1 -0
- package/dist/packem_shared/createLunoraAuthClient-Ca1AdNhq.mjs +1 -0
- package/dist/packem_shared/createSignUpInvitation-CwrPh0XH.mjs +1 -0
- package/dist/packem_shared/effectiveCookieCache-JvL6i6YO.mjs +1 -0
- package/dist/packem_shared/emailGateDatabaseHooks-Dvyliwxx.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-C5_mvDx4.d.mts +126 -0
- package/dist/packem_shared/invite-only.d-CYPBrNgv.d.ts +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-EBhckRBW.mjs +1 -0
- package/dist/packem_shared/sessionPresets-DQQYAOER.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-BZ9zDaZC.d.mts +873 -0
- package/dist/packem_shared/worker.d-Ckaeq8QN.d.ts +873 -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 +180 -2
- package/dist/plugins.d.ts +180 -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,147 @@
|
|
|
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-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" | "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. 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
|
+
* The key a failed attempt's identifiers are HMAC'd under. A failed attempt can carry text the caller typed into an
|
|
64
|
+
* identifier field, such as a pasted password, and an unkeyed digest of that would be brute-forceable.
|
|
65
|
+
*/
|
|
66
|
+
hashKey?: string;
|
|
67
|
+
/**
|
|
68
|
+
* Redact secrets/PII in the `detail` payload before persisting. Defaults to
|
|
69
|
+
* `true`. Set `false` only for a trusted, pre-scrubbed payload.
|
|
70
|
+
*/
|
|
71
|
+
redactDetail?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Keep only the most recent `retention` rows (trimmed after each append),
|
|
74
|
+
* mirroring the admin audit log's bounded retention. Omit for an unbounded
|
|
75
|
+
* trail (the compliance default) — deliberately NOT capped at 1000.
|
|
76
|
+
*/
|
|
77
|
+
retention?: number;
|
|
78
|
+
}
|
|
79
|
+
/** Options for {@link readAuthAuditLog}. */
|
|
80
|
+
interface ReadAuthAuditOptions {
|
|
81
|
+
/** Return only events for this actor id. */
|
|
82
|
+
actorId?: string;
|
|
83
|
+
/** Return only events of this type. */
|
|
84
|
+
event?: string;
|
|
85
|
+
/** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
|
|
86
|
+
limit?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Return only events with `seq` strictly greater than this. Supplying it
|
|
89
|
+
* switches the page to oldest-first so the cursor walks forward; omit it for
|
|
90
|
+
* the newest-first feed.
|
|
91
|
+
*/
|
|
92
|
+
sinceSeq?: number;
|
|
93
|
+
}
|
|
94
|
+
declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Append one auth event, redacting its `detail` payload (unless disabled) and —
|
|
97
|
+
* when `retention` is set — trimming the log back to the most recent rows.
|
|
98
|
+
* Creates the table first so callers needn't. Returns the redacted, persisted
|
|
99
|
+
* entry (sans `seq`) so an export tap can forward exactly what was stored.
|
|
100
|
+
*/
|
|
101
|
+
declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
|
|
102
|
+
/**
|
|
103
|
+
* Read audit events, optionally filtered by `actorId` / `event` and paged past
|
|
104
|
+
* `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's `detail`
|
|
105
|
+
* JSON back into an object. Creates the table first so reads on a never-audited
|
|
106
|
+
* database return `[]` instead of throwing.
|
|
107
|
+
*
|
|
108
|
+
* Ordering follows the cursor: **without** `sinceSeq` the page is newest-first
|
|
109
|
+
* (`seq DESC`) — the feed the studio's Security panel renders. **With**
|
|
110
|
+
* `sinceSeq` it is oldest-first (`seq ASC`), because a lower bound is a forward
|
|
111
|
+
* walk: a descending page above the bound would hand back the newest rows and
|
|
112
|
+
* leave everything between the cursor and them unreachable once the caller
|
|
113
|
+
* advanced past it.
|
|
114
|
+
*
|
|
115
|
+
* `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
|
|
116
|
+
* `Number.NaN`, or an upstream boundary that failed to reject one) falls back
|
|
117
|
+
* to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
|
|
118
|
+
* which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
|
|
119
|
+
* parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
|
|
120
|
+
* rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
|
|
121
|
+
* safety net for every OTHER caller of this function too.
|
|
122
|
+
*/
|
|
123
|
+
declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
124
|
+
/**
|
|
125
|
+
* The auth/security audit read plane the runtime's `authAuditReader` option
|
|
126
|
+
* accepts — a structurally-compatible `{ read }` object the worker calls behind
|
|
127
|
+
* its admin gate to back the studio's "Security / audit" page
|
|
128
|
+
* (`__lunora_admin__:getAuthAuditLog`).
|
|
129
|
+
*/
|
|
130
|
+
interface AuthAuditReader {
|
|
131
|
+
read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Build the reader the runtime's `authAuditReader` option accepts, closing over
|
|
135
|
+
* the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
|
|
136
|
+
* `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
|
|
137
|
+
* through to {@link readAuthAuditLog} (which clamps `limit`).
|
|
138
|
+
*
|
|
139
|
+
* ```ts
|
|
140
|
+
* export default createWorker({
|
|
141
|
+
* authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
|
|
142
|
+
* // …
|
|
143
|
+
* });
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
|
|
147
|
+
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,147 @@
|
|
|
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-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" | "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. 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
|
+
* The key a failed attempt's identifiers are HMAC'd under. A failed attempt can carry text the caller typed into an
|
|
64
|
+
* identifier field, such as a pasted password, and an unkeyed digest of that would be brute-forceable.
|
|
65
|
+
*/
|
|
66
|
+
hashKey?: string;
|
|
67
|
+
/**
|
|
68
|
+
* Redact secrets/PII in the `detail` payload before persisting. Defaults to
|
|
69
|
+
* `true`. Set `false` only for a trusted, pre-scrubbed payload.
|
|
70
|
+
*/
|
|
71
|
+
redactDetail?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Keep only the most recent `retention` rows (trimmed after each append),
|
|
74
|
+
* mirroring the admin audit log's bounded retention. Omit for an unbounded
|
|
75
|
+
* trail (the compliance default) — deliberately NOT capped at 1000.
|
|
76
|
+
*/
|
|
77
|
+
retention?: number;
|
|
78
|
+
}
|
|
79
|
+
/** Options for {@link readAuthAuditLog}. */
|
|
80
|
+
interface ReadAuthAuditOptions {
|
|
81
|
+
/** Return only events for this actor id. */
|
|
82
|
+
actorId?: string;
|
|
83
|
+
/** Return only events of this type. */
|
|
84
|
+
event?: string;
|
|
85
|
+
/** Max rows to return, clamped to [1, 10000]. Defaults to 1000. */
|
|
86
|
+
limit?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Return only events with `seq` strictly greater than this. Supplying it
|
|
89
|
+
* switches the page to oldest-first so the cursor walks forward; omit it for
|
|
90
|
+
* the newest-first feed.
|
|
91
|
+
*/
|
|
92
|
+
sinceSeq?: number;
|
|
93
|
+
}
|
|
94
|
+
declare const ensureAuthAuditTable: (executor: SqlExecutor) => Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Append one auth event, redacting its `detail` payload (unless disabled) and —
|
|
97
|
+
* when `retention` is set — trimming the log back to the most recent rows.
|
|
98
|
+
* Creates the table first so callers needn't. Returns the redacted, persisted
|
|
99
|
+
* entry (sans `seq`) so an export tap can forward exactly what was stored.
|
|
100
|
+
*/
|
|
101
|
+
declare const appendAuthAuditEntry: (executor: SqlExecutor, entry: AppendAuthAuditEntry, options?: AppendAuthAuditOptions) => Promise<AppendAuthAuditEntry>;
|
|
102
|
+
/**
|
|
103
|
+
* Read audit events, optionally filtered by `actorId` / `event` and paged past
|
|
104
|
+
* `sinceSeq`, up to `limit` (clamped to [1, 10000]). Parses each row's `detail`
|
|
105
|
+
* JSON back into an object. Creates the table first so reads on a never-audited
|
|
106
|
+
* database return `[]` instead of throwing.
|
|
107
|
+
*
|
|
108
|
+
* Ordering follows the cursor: **without** `sinceSeq` the page is newest-first
|
|
109
|
+
* (`seq DESC`) — the feed the studio's Security panel renders. **With**
|
|
110
|
+
* `sinceSeq` it is oldest-first (`seq ASC`), because a lower bound is a forward
|
|
111
|
+
* walk: a descending page above the bound would hand back the newest rows and
|
|
112
|
+
* leave everything between the cursor and them unreachable once the caller
|
|
113
|
+
* advanced past it.
|
|
114
|
+
*
|
|
115
|
+
* `limit` is NaN-safe: a non-finite/non-number value (e.g. a caller passing
|
|
116
|
+
* `Number.NaN`, or an upstream boundary that failed to reject one) falls back
|
|
117
|
+
* to {@link DEFAULT_READ_LIMIT} rather than reaching `Math.min`/`Math.max`,
|
|
118
|
+
* which both propagate `NaN` and would otherwise bind it as the SQL `LIMIT`
|
|
119
|
+
* parameter. This is the library-level fix; `#readAudit` (`./auth-do`) also
|
|
120
|
+
* rejects a non-numeric `limit` at the boundary with a 400 — this clamp is the
|
|
121
|
+
* safety net for every OTHER caller of this function too.
|
|
122
|
+
*/
|
|
123
|
+
declare const readAuthAuditLog: (executor: SqlExecutor, options?: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
124
|
+
/**
|
|
125
|
+
* The auth/security audit read plane the runtime's `authAuditReader` option
|
|
126
|
+
* accepts — a structurally-compatible `{ read }` object the worker calls behind
|
|
127
|
+
* its admin gate to back the studio's "Security / audit" page
|
|
128
|
+
* (`__lunora_admin__:getAuthAuditLog`).
|
|
129
|
+
*/
|
|
130
|
+
interface AuthAuditReader {
|
|
131
|
+
read: (options: ReadAuthAuditOptions) => Promise<AuthAuditEntry[]>;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Build the reader the runtime's `authAuditReader` option accepts, closing over
|
|
135
|
+
* the auth D1 `executor` (`d1Executor(env.DB)`) so an admin caller reads the same
|
|
136
|
+
* `__lunora_auth_audit__` table the hook writes. Filters/paging pass straight
|
|
137
|
+
* through to {@link readAuthAuditLog} (which clamps `limit`).
|
|
138
|
+
*
|
|
139
|
+
* ```ts
|
|
140
|
+
* export default createWorker({
|
|
141
|
+
* authAuditReader: createAuthAuditReader(d1Executor(env.DB)),
|
|
142
|
+
* // …
|
|
143
|
+
* });
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
declare const createAuthAuditReader: (executor: SqlExecutor) => AuthAuditReader;
|
|
147
|
+
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 x,piiRules as $,redact as U}from"@visulima/redact";const M=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"]),z=new Set(["card","pass","pin","session"]),j=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),F=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),H=new Set(["card no","connection string","database url","one time"]),v=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],W=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"]),X=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),G=new Set(["max","min","num","total"]),m=4096,P=128,Z=16384,l="<REDACTED>",K="[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,q=(e,t)=>{const n=y(e[t]),s=t>0?y(e[t-1]):void 0;if(M.has(n))return n;if(s!==void 0){if(n==="key"&&j.has(s))return"key";if(n==="code"&&F.has(s))return"code";if(H.has(`${s} ${n}`))return`${s} ${n}`}return v.some(r=>n.endsWith(r))?n:void 0},R=e=>{const t=V(e);if(t.length===0)return"none";const n=X.has(t.at(-1))||G.has(t[0]);for(let s=t.length-1;s>=0;s-=1){const r=q(t,s);if(r!==void 0)return n?"count-secret":t.slice(s+1).every(i=>W.has(i))?z.has(r)&&s===t.length-1?"scalar-secret":"secret":"none"}return"none"},B=e=>typeof e=="boolean"||e===null||e===void 0?e:l,Y=e=>{const t=e.indexOf("://")+3,n=e.slice(t),s=n.split(/[?#]/,1)[0],r=s.lastIndexOf("@"),i=s.indexOf(":"),o=s.indexOf("/"),a=i!==-1&&/^\d+$/.test(s.slice(i+1,o===-1?void 0:o)),c=i!==-1&&!a&&(o===-1||i<o);if(r===-1&&c&&n.includes("@",s.length))return e.slice(0,t);const d=r!==-1&&(o===-1||r<o||i!==-1&&i<r&&!a);return`${e.slice(0,t)}${d?s.slice(r+1):s}`},J=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Q=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,ee=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,k=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,L=[{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\.`}],te=String.raw`(?<=^|[^\w-]|${k})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ne=new RegExp([...L.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${k})${t}${e}`),te].join("|"),"g"),se=new RegExp([...L.map(({prefix:e})=>e),"eyJ"].join("|")),re=/(\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,I=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ie=e=>{let t="",n=0;f.lastIndex=0;for(let s=f.exec(e);s!==null;s=f.exec(e)){const r=R(s[2]),i=s.index+s[0].length;w.lastIndex=i;const o=r==="none"?null:w.exec(e);if(o===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(o[0])){f.lastIndex=Math.max(i,s.index+1);continue}const a=o[0],c=a.startsWith('\\"')?'\\"':a.startsWith('"')||a.startsWith("'")?a[0]:"";let d=i+a.length;c===""&&s[3]===":"&&(I.lastIndex=d,d+=I.exec(e)?.[0].length??0),t+=`${e.slice(n,i)}${c}${l}${a.length>c.length&&a.endsWith(c)?c:""}`,n=d,f.lastIndex=n}return t+e.slice(n)},ae=/[:=@]|basic|bearer|digest|-u\b|--/i,oe=e=>{const t=se.test(e);if(!t&&!ae.test(e))return e;const n=e.replaceAll(Q,`-----BEGIN $1-----${l}`).replaceAll(J,Y).replaceAll(ee,`$1 ${l}`);return ie((t?n.replaceAll(ne,l):n).replaceAll(re,`$1$2$3${l}`))},ce=(e,t)=>{if(t.remaining<=0)return K;const n=e.slice(0,m+P);t.remaining-=n.length;const s=oe(n);return s.length>m||e.length>n.length?`${s.slice(0,m)}…[truncated]`:s},de=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),u=Symbol("no-json"),le=e=>{const{toJSON:t}=e;if(typeof t!="function")return u;try{const n=t.call(e);return n===e?u:n}catch{return u}},Ee=32,g=(e,t,n,s,r)=>{if(typeof e=="string")return s?l:ce(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&de(e))return e;if(t.has(e)||n>=Ee)return l;const i=Array.isArray(e)?u:le(e);if(i!==u){t.add(e);const a=g(i,t,n+1,s,r);return t.delete(e),a}t.add(e);const o=Array.isArray(e)?e.map(a=>g(a,t,n+1,s,r)):Object.fromEntries(Object.entries(e).map(([a,c])=>{const d=R(a);return d==="secret"||d==="scalar-secret"&&(typeof c!="object"||c===null)?[a,B(c)]:[a,g(c,t,n+1,d==="count-secret"&&(typeof c=="string"||Array.isArray(c)),r)]}));return t.delete(e),o},pe=e=>g(e,new WeakSet,0,!1,{remaining:Z}),Ae=(e,t)=>{if(e.size<t)return;const n=e.keys().next().value;n!==void 0&&e.delete(n)},fe=(e,t,n,s)=>{const r=e.get(t);if(r!==void 0)return r;Ae(e,s);const i=n().catch(o=>{throw e.get(t)===i&&e.delete(t),o});return e.set(t,i),i},ue=new TextEncoder,ge=64,me=new Map,b=async e=>fe(me,e,async()=>crypto.subtle.importKey("raw",ue.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ge),A="__lunora_auth_audit__",Se=[...x,...$],N=new Set(["clientId","consentId","invitationId","keyId","memberId","organizationId","providerId","resourceIdentifier","role","roleId","roleName","scimGroupId","scimUserId","targetUserId","teamId"]),_e=/^[^\s?#=@]{1,256}$/u,he="hmac-sha256:",Te="lunora/auth-audit/failed-identifier",O=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),ye=async(e,t)=>{if(t===void 0)return e;const n=await b(t),s=await b(O(await crypto.subtle.sign("HMAC",n,new TextEncoder().encode(Te)))),r=await Promise.all(Object.entries(e).filter(([i,o])=>N.has(i)&&typeof o=="string").map(async([i,o])=>{const a=await crypto.subtle.sign("HMAC",s,new TextEncoder().encode(String(o)));return[i,he+O(a)]}));return{...e,...Object.fromEntries(r)}},we=e=>{const t=Object.fromEntries(Object.entries(e).filter(([r,i])=>N.has(r)&&typeof i=="string"&&_e.test(i))),n=new Set(Object.keys(t)),s=Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)));return{...U(pe(s),Se),...t}},Ie=1e3,be=1e4,p=null,S=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},Oe=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${A}" (
|
|
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 "${A}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},_=new WeakMap,D=e=>{const t=_.get(e);if(t)return t;const n=Oe(e);return _.set(e,n),n.catch(()=>_.delete(e)),n},Le=async(e,t,n={})=>{await D(e);let s;if(t.detail!==void 0){const r=t.outcome==="failure"?await ye(t.detail,n.hashKey):t.detail;s=n.redactDetail===!1?r:we(r)}return await e.run(`INSERT INTO "${A}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??p,t.actorEmail??p,t.targetEmail??p,t.ip??p,t.userAgent??p,s===void 0?p:JSON.stringify(s)]),typeof n.retention=="number"&&n.retention>0&&await e.run(`DELETE FROM "${A}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${A}")`,[n.retention]),{...t,detail:s}},Re=async(e,t={})=>{await D(e);const n=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,be)):Ie,s=["seq > ?"],r=[t.sinceSeq??0],i=t.sinceSeq===void 0?"DESC":"ASC";return t.actorId!==void 0&&(s.push("actor_id = ?"),r.push(t.actorId)),t.event!==void 0&&(s.push("event = ?"),r.push(t.event)),r.push(n),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${A}" WHERE ${s.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,r)).map(a=>{const c={event:S(a.event)??"",outcome:a.outcome==="failure"?"failure":"success",seq:Number(a.seq),ts:Number(a.ts)},d=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[E,C]of d){const T=S(a[C]);T!==void 0&&(c[E]=T)}const h=S(a.detail);if(h!==void 0)try{const E=JSON.parse(h);typeof E=="object"&&E!==null&&!Array.isArray(E)&&(c.detail=E)}catch{}return c})},Ne=e=>({read:t=>Re(e,t)});export{A as AUTH_AUDIT_TABLE,Le as appendAuthAuditEntry,Ne as createAuthAuditReader,D as ensureAuthAuditTable,Re 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};
|