@santi020k/auth-cloudflare 0.3.0 → 0.5.0

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/README.md CHANGED
@@ -1,183 +1,167 @@
1
1
  # `@santi020k/auth-cloudflare`
2
2
 
3
- Single-owner and multi-user email-code and passkey authentication policy for Hono applications running on Cloudflare
4
- Workers and D1.
5
- Better Auth owns the authentication protocol and persistence implementation; this package owns the shared Santiago
6
- policy.
3
+ Email-code and passkey authentication policy for Hono applications running on Cloudflare Workers and D1. Choose a
4
+ single configured owner or let the consuming application approve multiple identities. Better Auth owns the
5
+ authentication protocol and persistence implementation; this package owns the shared Santiago policy.
7
6
 
8
7
  The package intentionally does not share sessions, cookies, passkeys, databases, secrets, or relying-party IDs between
9
- applications. Every consumer supplies a unique browser origin, auth server URL, cookie prefix, secret, D1 binding, and
10
- email delivery callback.
11
-
12
- ## Status
8
+ applications. Every consumer supplies a unique origin, cookie prefix, secret, D1 binding, and email delivery callback.
13
9
 
14
- This is a public experimental `0.x` package. Pin the version, review release notes before updating, and keep an
15
- application's existing authentication and recovery path during a bounded rollout. Real-world adoption validates a later
16
- promotion to supported/stable status; it is not a prerequisite for installing the package.
10
+ When the authentication Worker is hosted separately from the browser application, `baseURL` is the public Worker URL
11
+ and `browserOrigin` is the single exact browser origin allowed to make unsafe requests and register passkeys. Omitting
12
+ `browserOrigin` keeps the same-origin default.
17
13
 
18
- ## Install
14
+ ## Current status
19
15
 
20
- ```sh
21
- pnpm add @santi020k/auth-cloudflare hono
22
- ```
16
+ This package is already public. Version 0.4 preserves its v0.3 policy options and compatibility subpaths and prepares
17
+ the seven split packages for public release. Publication does not replace consumer rollout validation: an application
18
+ must still prove its own D1 migration, compatibility route, session cutover, and browser passkey flow. See the
19
+ repository's [release process](https://github.com/santi020k/auth/blob/main/docs/releasing.md).
23
20
 
24
- The package exports:
21
+ ## v0.3 compatibility
25
22
 
26
- - `@santi020k/auth-cloudflare`: server policy with `createOwnerAuth` and `createMultiUserAuth`;
27
- - `@santi020k/auth-cloudflare/client`: credentialed owner and application browser clients with email OTP and passkeys;
28
- - `@santi020k/auth-cloudflare/hono`: typed owner and application session middleware for protected Hono routes;
29
- - `@santi020k/auth-cloudflare/schema`: owner and generic D1 schema diagnostics.
23
+ Existing consumers may continue using `applicationOrigin` and `authServerURL`; they are compatibility aliases for
24
+ `browserOrigin` and `baseURL`. Versioned `secrets` with an optional `legacySecret`, configurable `emailOtpRateLimit`,
25
+ and the original two-field `AuthSessionIdentity` assignment contract also remain supported. Newly resolved sessions
26
+ include optional typed lifecycle fields (`authenticatedAt`, `expiresAt`, and `sessionId`). New code should use
27
+ `browserOrigin` and `baseURL`; providing a legacy and replacement origin option with different values fails closed.
30
28
 
31
- The published tarball also includes `schema/d1.sql`, the canonical SQL to copy into an app-owned additive migration.
29
+ Version 0.4 intentionally expands three pre-1.0 TypeScript contracts. Code that manually constructs an `AuthPolicy`
30
+ must use `resolveOwnerAuthPolicy` or `resolveMultiUserAuthPolicy` so the new `baseURL`, `origin`, and `tableNames` fields
31
+ are present. Test doubles typed as `OwnerAuthInstance` or `MultiUserAuthInstance` must add the session inventory,
32
+ revocation, emergency-lockout, and rate-limit pruning methods. Their `resolveSession` implementation must return the lifecycle fields in
33
+ `ResolvedAuthSessionIdentity`. Runtime consumers that call the factory functions require no adapter.
32
34
 
33
35
  ## Policy
34
36
 
35
37
  - Email OTPs are six digits, expire after ten minutes, allow five verification attempts, and are stored hashed.
36
- - Email OTP rate limits default to three requests per ten minutes and persist in D1 rather than isolate memory.
37
- - Only the configured owner or an email approved by the consumer's authorization callback may create or update an
38
- identity.
38
+ - Rate limits are enabled in every environment and use D1 rather than per-isolate memory.
39
+ - A D1-backed pre-authentication limit also bounds rejected POST requests per Cloudflare client IP and auth path
40
+ before email admission; Better Auth's stricter endpoint limits still apply to requests that continue into its
41
+ handler.
42
+ - Only the configured owner or identities approved by the consumer may create or update an identity.
39
43
  - Unauthorized email-code requests receive the same success-shaped response without sending mail.
40
- - Multi-user session creation, session resolution, and authenticated passkey operations recheck the callback, so
41
- removing membership takes effect immediately even when a stored session has not expired.
42
- - Requests accept only the exact configured browser origin. Unsafe requests without it are rejected, and credentialed
43
- CORS responses never use a wildcard origin.
44
+ - Unsafe requests require the exact configured browser `Origin` header.
44
45
  - Passkeys require discoverable credentials and user verification.
45
- - The WebAuthn relying-party ID is the application hostname, including when the auth Worker uses its supported same-site
46
- subdomain.
47
- - Production cookies are secure and scoped to the auth server hostname.
46
+ - Optional social providers use the same consumer email-admission policy; provider credentials remain consumer-owned.
47
+ - Optional Cloudflare Turnstile protection defaults to the email-code request endpoint.
48
+ - The WebAuthn relying-party ID is always the exact application hostname.
49
+ - Production cookies are secure and remain scoped to the authentication API hostname.
50
+
51
+ ## Example
52
+
53
+ ```ts
54
+ const ownerAuth = createOwnerAuth({
55
+ appName: "Example owner workspace",
56
+ baseURL: "https://planner.example.com",
57
+ cookiePrefix: "example-owner",
58
+ database: env.DB,
59
+ ownerEmail: env.OWNER_EMAIL,
60
+ secret: env.AUTH_SECRET,
61
+ sendVerificationOTP: ({ email, otp }) => sendLoginCode(env, email, otp),
62
+ waitUntil: (task) => context.waitUntil(task),
63
+ });
48
64
 
49
- ## Server
65
+ app.all("/api/auth/*", (context) => ownerAuth.handler(context.req.raw));
66
+ ```
50
67
 
51
- `applicationOrigin` is where the browser application runs. `authServerURL` is where the auth handler runs. Use the same
52
- origin for a simple deployment or the supported same-site subdomain shape for a separate Worker.
68
+ For multiple accounts, keep membership and roles in the consuming application and provide a current access decision:
53
69
 
54
70
  ```ts
55
- import { createOwnerAuth } from "@santi020k/auth-cloudflare";
56
-
57
- app.all("/api/auth/*", (context) => {
58
- const ownerAuth = createOwnerAuth({
59
- appName: "Example owner workspace",
60
- applicationOrigin: "https://workspace.example.com",
61
- authServerURL: "https://auth.workspace.example.com",
62
- cookiePrefix: "example-owner",
63
- database: context.env.DB,
64
- ownerEmail: context.env.OWNER_EMAIL,
65
- secret: context.env.AUTH_SECRET,
66
- sendVerificationOTP: ({ email, otp }) => sendLoginCode(context.env, email, otp),
67
- waitUntil: (task) => {
68
- context.executionCtx.waitUntil(task);
69
- },
70
- });
71
- return ownerAuth.handler(context.req.raw);
71
+ const auth = createMultiUserAuth({
72
+ appName: "Example team workspace",
73
+ authorizeEmail: async (email) => Boolean(await findActiveMember(env.DB, email)),
74
+ baseURL: "https://workspace.example.com",
75
+ cookiePrefix: "example-members",
76
+ database: env.DB,
77
+ secret: env.AUTH_SECRET,
78
+ sendVerificationOTP: ({ email, otp }) => sendLoginCode(env, email, otp),
79
+ waitUntil: (task) => context.executionCtx.waitUntil(task),
72
80
  });
73
81
  ```
74
82
 
75
- For secret rotation, replace `secret` with versioned secrets:
83
+ For a split web/API deployment, keep the two security boundaries explicit:
76
84
 
77
85
  ```ts
78
86
  const ownerAuth = createOwnerAuth({
79
- // Other options omitted.
80
- secrets: [
81
- { value: env.AUTH_SECRET_V2, version: 2 },
82
- { value: env.AUTH_SECRET_V1, version: 1 },
83
- ],
84
- legacySecret: env.AUTH_SECRET_LEGACY,
87
+ appName: "Example control room",
88
+ baseURL: "https://api.example.com",
89
+ browserOrigin: "https://control.example.com",
90
+ cookiePrefix: "example-control-owner",
91
+ database: env.DB,
92
+ ownerEmail: env.OWNER_EMAIL,
93
+ secret: env.AUTH_SECRET,
94
+ sendVerificationOTP: ({ email, otp }) => sendLoginCode(env, email, otp),
95
+ waitUntil: (task) => context.executionCtx.waitUntil(task),
85
96
  });
86
97
  ```
87
98
 
88
- Each value must contain at least 32 characters. Keep the active version first and retain previous versions only for the
89
- documented compatibility window.
99
+ The API must still return credentialed CORS headers for that exact browser origin. `browserOrigin` does not accept an
100
+ origin list and does not create a shared cookie domain.
90
101
 
91
- ### Multiple accounts
102
+ `waitUntil` is required because code delivery runs outside the response path to keep approved and rejected addresses
103
+ indistinguishable even when the provider fails. On Workers, pass `context.executionCtx.waitUntil`; do not substitute an
104
+ untracked promise that the runtime may terminate after sending the response.
92
105
 
93
- Use `createMultiUserAuth` when the application owns a set of approved accounts. The package normalizes the email before
94
- calling `authorizeEmail`; the callback may query an application-owned membership table or another authoritative local
95
- source. Keep invitations, roles, teams, and product permissions outside the auth package.
106
+ Set `tablePrefix` when the consumer database already contains generic tables such as `user` or `session`. Generate its
107
+ app-owned migration with the same prefix through `@santi020k/auth-migrations`; a prefix is part of the persistent storage
108
+ contract and must not be changed after deployment.
96
109
 
97
- ```ts
98
- import { createMultiUserAuth } from "@santi020k/auth-cloudflare";
110
+ `authorizeEmail` receives a normalized email address and is checked during code requests, identity writes, code
111
+ delivery, and session resolution. A member rejected after signing in no longer resolves as authenticated. The package
112
+ does not own roles, invitations, organizations, or cross-application identity state.
99
113
 
114
+ Consumers may pass Better Auth `socialProviders` for approved OAuth providers. The package checks the fresh provider
115
+ email before provisioning, linking, or OAuth sign-in, so OAuth cannot bypass `ownerEmail` or `authorizeEmail`.
116
+ Account-linking UX, scopes, callback routes, and provider credentials remain consumer-owned.
117
+
118
+ Public code-request surfaces can enable Turnstile through the same server policy:
119
+
120
+ ```ts
100
121
  const auth = createMultiUserAuth({
101
- appName: "Example team workspace",
102
- applicationOrigin: "https://workspace.example.com",
103
- authServerURL: "https://auth.workspace.example.com",
104
- cookiePrefix: "example-team",
105
- database: context.env.DB,
106
- secret: context.env.AUTH_SECRET,
107
- authorizeEmail: (email) => isActiveMember(context.env.DB, email),
108
- sendVerificationOTP: ({ email, otp }) => sendLoginCode(context.env, email, otp),
109
- waitUntil: (task) => {
110
- context.executionCtx.waitUntil(task);
122
+ // ...application-owned configuration
123
+ turnstile: {
124
+ allowedHostnames: ["workspace.example.com"],
125
+ expectedAction: "request-login-code",
126
+ secretKey: env.TURNSTILE_SECRET_KEY,
111
127
  },
112
128
  });
113
129
  ```
114
130
 
115
- Approved and rejected code requests intentionally receive the same success-shaped response. Rejected addresses do not
116
- receive mail and cannot create a user, though Better Auth may persist a hashed, expiring verification record as part of
117
- the uniform flow. Session creation, `resolveSession`, and authenticated passkey operations recheck current membership.
118
- Removing a member therefore prevents a new sign-in, passkey mutation, or subsequent session resolution; deleting stored
119
- session records is an optional application-owned cleanup.
131
+ The browser supplies Better Auth's `x-captcha-response` header. Site and secret keys must not be shared across products.
120
132
 
121
- ## Browser and protected routes
122
-
123
- ```ts
124
- import { createOwnerAuthClient } from "@santi020k/auth-cloudflare/client";
133
+ Cloudflare Workers must enable `nodejs_compat` (or the narrower `nodejs_als` flag when no other Node compatibility is
134
+ needed). Each application must generate and review its own Better Auth core and passkey migration; the package does not
135
+ silently create or mutate production tables.
125
136
 
126
- export const authClient = createOwnerAuthClient({
127
- authServerURL: "https://auth.workspace.example.com",
128
- });
129
- ```
137
+ D1 rate-limit counters are persistent. Call `auth.pruneRateLimits()` from the consuming application's scheduled
138
+ maintenance to remove counters older than the default 24-hour retention window. A consumer may provide a positive
139
+ `retentionSeconds` override and deterministic `now` value for testing. Cleanup is explicit and never changes schemas or
140
+ runs implicitly inside an authentication request.
130
141
 
131
- ```ts
132
- import { createOwnerAuthMiddleware, type OwnerAuthEnv } from "@santi020k/auth-cloudflare/hono";
133
- import { Hono } from "hono";
134
-
135
- interface AppEnv extends OwnerAuthEnv {
136
- Bindings: Bindings;
137
- }
138
-
139
- const protectedRoutes = new Hono<AppEnv>();
140
- protectedRoutes.use(
141
- "*",
142
- createOwnerAuthMiddleware<AppEnv>((context) => createOwnerAuthForContext(context)),
143
- );
144
- protectedRoutes.get("/account", (context) => context.json(context.var.ownerAuthSession));
145
- ```
142
+ ## Session operations and security events
146
143
 
147
- `createOwnerAuthForContext` is an application-owned resolver that returns a `createOwnerAuth(...)` instance using the
148
- current request context and bindings, as in the server example above.
144
+ The configured instance provides server-side `listSessions(userId)`, `revokeSession(userId, sessionId)`,
145
+ `revokeAllSessions(userId)`, and `emergencyLockout(userId)` operations. Inventory entries contain ISO timestamps and
146
+ device metadata but never session tokens, and expired sessions are omitted. The explicit `userId` scope prevents a
147
+ session ID from revoking another account's session. Consumers must authenticate and authorize their own management
148
+ routes before calling these methods; this package deliberately does not define roles, recovery, or administrative
149
+ policy.
149
150
 
150
- For multi-user applications, use `createApplicationAuthClient` and `createAuthMiddleware`. The resolved identity is
151
- available as `context.var.authSession` and contains only `email` and `userId`; load roles from application-owned data.
151
+ Supply `onSecurityEvent` to forward authentication events into the consumer's established audit or alerting system:
152
152
 
153
153
  ```ts
154
- import { createApplicationAuthClient } from "@santi020k/auth-cloudflare/client";
155
- import { createAuthMiddleware, type AuthEnv } from "@santi020k/auth-cloudflare/hono";
156
-
157
- export const authClient = createApplicationAuthClient({
158
- authServerURL: "https://auth.workspace.example.com",
154
+ const auth = createMultiUserAuth({
155
+ // ...application-owned configuration
156
+ onSecurityEvent: (event) => auditSecurityEvent(event),
159
157
  });
160
-
161
- interface AppEnv extends AuthEnv {
162
- Bindings: Bindings;
163
- }
164
-
165
- app.use(
166
- "/account/*",
167
- createAuthMiddleware<AppEnv>((context) => createAuthForContext(context)),
168
- );
169
158
  ```
170
159
 
171
- ## D1 ownership
172
-
173
- Cloudflare Workers must enable `nodejs_compat` (or the narrower `nodejs_als` flag when no other Node compatibility is
174
- needed). Copy `schema/d1.sql` into the consumer's migration directory, review it there, and apply it through that
175
- application's deployment process. This package never silently creates or mutates production tables.
176
-
177
- Use `checkAuthSchema` (or the retained `checkOwnerAuthSchema` alias) from `@santi020k/auth-cloudflare/schema` to report
178
- missing required tables, columns, primary and unique key constraints, and indexes before serving authentication traffic.
179
- Application-owned extra schema is allowed. Moving from the owner factory to multi-user auth does not require an auth
180
- schema migration; the canonical tables already support multiple identities.
160
+ Events cover blocked origins or credentials, pre-authentication rate limiting, suppressed and failed email-code
161
+ delivery, code requests, session creation, scoped revocation, revoke-all, and explicit emergency lockout. Listener
162
+ failures are isolated from the auth flow. Event payloads intentionally omit codes, cookies, session tokens, secrets,
163
+ client IPs, and request bodies.
181
164
 
182
- See the complete [consumer integration checklist](https://github.com/santi020k/auth/blob/main/docs/consumer-integration.md)
183
- and [security policy](https://github.com/santi020k/auth/blob/main/SECURITY.md).
165
+ Resolved identities include `authenticatedAt` and `expiresAt` ISO timestamps. Use `isRecentAuthentication` or the Hono
166
+ recent-authentication middleware for sensitive actions. The application still chooses the step-up method and owns the
167
+ authorization decision.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import type { D1Database } from "@cloudflare/workers-types";
2
2
  import { type BetterAuthOptions } from "better-auth";
3
+ export interface AuthTableNames {
4
+ account: string;
5
+ passkey: string;
6
+ rateLimit: string;
7
+ session: string;
8
+ user: string;
9
+ verification: string;
10
+ }
11
+ /**
12
+ * Resolves the table names needed at runtime without making the already-public
13
+ * package depend on the still-private migration package. Contract tests keep
14
+ * this result aligned with `@santi020k/auth-migrations`.
15
+ */
16
+ export declare function resolveAuthTableNames(tablePrefix?: string): AuthTableNames;
3
17
  export interface AuthEmail {
4
18
  email: string;
5
19
  otp: string;
@@ -9,10 +23,9 @@ export interface AuthEmailOtpRateLimit {
9
23
  window: number;
10
24
  }
11
25
  export type AuthVersionedSecret = NonNullable<BetterAuthOptions["secrets"]>[number];
12
- export type OwnerAuthEmail = AuthEmail;
13
26
  export type OwnerAuthEmailOtpRateLimit = AuthEmailOtpRateLimit;
14
27
  export type OwnerAuthVersionedSecret = AuthVersionedSecret;
15
- interface OwnerAuthSimpleSecretOptions {
28
+ interface AuthSimpleSecretOptions {
16
29
  legacySecret?: never;
17
30
  secret: string;
18
31
  secrets?: never;
@@ -22,56 +35,157 @@ interface AuthVersionedSecretOptions {
22
35
  secret?: never;
23
36
  secrets: AuthVersionedSecret[];
24
37
  }
25
- type AuthSecretOptions = OwnerAuthSimpleSecretOptions | AuthVersionedSecretOptions;
26
- interface AuthPolicyConfiguration {
38
+ type AuthSecretOptions = AuthSimpleSecretOptions | AuthVersionedSecretOptions;
39
+ /**
40
+ * Observability hook for security-relevant occurrences. Consumers own
41
+ * storage and alerting; this package only reports what happened. A listener
42
+ * that throws never breaks the authentication flow — the failure is
43
+ * swallowed after the listener runs.
44
+ */
45
+ export type AuthSecurityEvent = {
46
+ email: string;
47
+ path: string;
48
+ type: "credentials_rejected";
49
+ } | {
50
+ email: string;
51
+ type: "email_otp_delivery_failed";
52
+ } | {
53
+ email: string;
54
+ type: "email_otp_delivery_suppressed";
55
+ } | {
56
+ email: string;
57
+ type: "email_otp_requested";
58
+ } | {
59
+ revokedSessions: number;
60
+ type: "emergency_lockout";
61
+ userId: string;
62
+ } | {
63
+ origin: string | null;
64
+ path: string;
65
+ type: "request_origin_rejected";
66
+ } | {
67
+ path: string;
68
+ type: "request_rate_limited";
69
+ } | {
70
+ sessionId: string;
71
+ type: "session_created";
72
+ userId: string;
73
+ } | {
74
+ sessionId: string;
75
+ type: "session_revoked";
76
+ userId: string;
77
+ } | {
78
+ revokedSessions: number;
79
+ type: "sessions_revoked_all";
80
+ userId: string;
81
+ };
82
+ export type AuthSecurityEventListener = (event: AuthSecurityEvent) => Promise<void> | void;
83
+ interface BaseAuthPolicyConfiguration {
27
84
  appName: string;
28
- applicationOrigin: string;
29
- authServerURL: string;
85
+ /** @deprecated Use `browserOrigin`. */
86
+ applicationOrigin?: string;
30
87
  basePath?: `/${string}`;
88
+ baseURL?: string;
89
+ browserOrigin?: string;
31
90
  cookiePrefix: string;
91
+ /** @deprecated Use `baseURL`. */
92
+ authServerURL?: string;
32
93
  emailOtpRateLimit?: AuthEmailOtpRateLimit;
94
+ /** Optional Better Auth social providers. Credentials remain consumer-owned secrets. */
95
+ socialProviders?: BetterAuthOptions["socialProviders"];
96
+ tablePrefix?: string;
97
+ /** Optional Cloudflare Turnstile protection for authentication endpoints. */
98
+ turnstile?: AuthTurnstileOptions;
33
99
  }
34
- interface AuthRuntimeConfiguration {
100
+ type BaseAuthPolicyOptions = BaseAuthPolicyConfiguration & AuthSecretOptions;
101
+ export interface AuthTurnstileOptions {
102
+ allowedHostnames?: readonly string[];
103
+ endpoints?: readonly string[];
104
+ expectedAction?: string;
105
+ secretKey: string;
106
+ }
107
+ interface AuthRuntimeOptions {
35
108
  database: D1Database;
109
+ onSecurityEvent?: AuthSecurityEventListener;
36
110
  sendVerificationOTP(email: AuthEmail): Promise<void>;
37
111
  sessionExpiresIn?: number;
38
112
  sessionUpdateAge?: number;
39
113
  waitUntil(task: Promise<void>): void;
40
114
  }
41
- export type MultiUserAuthPolicyOptions = AuthPolicyConfiguration & AuthSecretOptions;
42
- export type MultiUserAuthOptions = MultiUserAuthPolicyOptions & AuthRuntimeConfiguration & {
43
- authorizeEmail(email: string): boolean | Promise<boolean>;
44
- };
45
- export type OwnerAuthPolicyOptions = AuthPolicyConfiguration & AuthSecretOptions & {
46
- ownerEmail: string;
47
- };
48
- export type OwnerAuthOptions = OwnerAuthPolicyOptions & AuthRuntimeConfiguration;
49
115
  export interface AuthPolicy {
116
+ /** Compatibility alias for `origin`. */
50
117
  applicationOrigin: string;
118
+ /** Compatibility alias for `baseURL`. */
51
119
  authServerOrigin: string;
52
120
  basePath: string;
121
+ baseURL: string;
53
122
  cookiePrefix: string;
54
123
  emailOtpRateLimit: AuthEmailOtpRateLimit;
124
+ origin: string;
55
125
  relyingPartyId: string;
56
126
  secureCookies: boolean;
57
- }
58
- export interface OwnerAuthPolicy extends AuthPolicy {
59
- ownerEmail: string;
127
+ tableNames: AuthTableNames;
60
128
  }
61
129
  export interface AuthSessionIdentity {
130
+ authenticatedAt?: string;
62
131
  email: string;
132
+ expiresAt?: string;
133
+ sessionId?: string;
63
134
  userId: string;
64
135
  }
136
+ export interface ResolvedAuthSessionIdentity extends AuthSessionIdentity {
137
+ authenticatedAt: string;
138
+ expiresAt: string;
139
+ sessionId: string;
140
+ }
141
+ /** One stored session row, safe to render in a "your devices" UI. Never includes the session token. */
142
+ export interface AuthSessionSummary {
143
+ createdAt: string;
144
+ expiresAt: string;
145
+ id: string;
146
+ ipAddress: string | null;
147
+ updatedAt: string;
148
+ userAgent: string | null;
149
+ }
65
150
  interface AuthInstance<TPolicy extends AuthPolicy> {
151
+ /** Revokes every session for `userId` immediately and reports an `emergency_lockout` event. Returns the count revoked. */
152
+ emergencyLockout(userId: string): Promise<number>;
66
153
  handler(request: Request): Promise<Response>;
154
+ /** Lists `userId`'s active sessions, newest first. */
155
+ listSessions(userId: string): Promise<AuthSessionSummary[]>;
67
156
  policy: TPolicy;
68
- resolveSession(headers: Headers): Promise<AuthSessionIdentity | null>;
157
+ /** Deletes expired rate-limit counters. Call from consumer-owned scheduled maintenance. */
158
+ pruneRateLimits(options?: {
159
+ now?: number;
160
+ retentionSeconds?: number;
161
+ }): Promise<number>;
162
+ resolveSession(headers: Headers): Promise<ResolvedAuthSessionIdentity | null>;
163
+ /** Revokes every session for `userId`. Returns the count revoked. */
164
+ revokeAllSessions(userId: string): Promise<number>;
165
+ /** Revokes one session owned by `userId`. Returns `false` if no matching session existed. */
166
+ revokeSession(userId: string, sessionId: string): Promise<boolean>;
69
167
  }
168
+ export type MultiUserAuthPolicyOptions = BaseAuthPolicyOptions;
169
+ export type MultiUserAuthOptions = BaseAuthPolicyOptions & AuthRuntimeOptions & {
170
+ authorizeEmail(email: string): boolean | Promise<boolean>;
171
+ };
70
172
  export type MultiUserAuthInstance = AuthInstance<AuthPolicy>;
173
+ export type OwnerAuthPolicyOptions = BaseAuthPolicyOptions & {
174
+ ownerEmail: string;
175
+ };
176
+ export type OwnerAuthOptions = OwnerAuthPolicyOptions & AuthRuntimeOptions;
177
+ export interface OwnerAuthPolicy extends AuthPolicy {
178
+ ownerEmail: string;
179
+ }
180
+ export type OwnerAuthEmail = AuthEmail;
71
181
  export type OwnerAuthInstance = AuthInstance<OwnerAuthPolicy>;
72
182
  export type OwnerAuthSessionIdentity = AuthSessionIdentity;
73
183
  export declare function normalizeAuthEmail(value: string): string;
74
184
  export declare function normalizeOwnerEmail(value: string): string;
185
+ /** Returns whether a session is recent enough for a consumer-defined step-up boundary. */
186
+ export declare function isRecentAuthentication(identity: {
187
+ authenticatedAt: string;
188
+ }, maxAgeSeconds: number, now?: number): boolean;
75
189
  export declare function resolveMultiUserAuthPolicy(options: MultiUserAuthPolicyOptions): AuthPolicy;
76
190
  export declare function resolveOwnerAuthPolicy(options: OwnerAuthPolicyOptions): OwnerAuthPolicy;
77
191
  export declare function enforceOwnerAuthRequest(policy: OwnerAuthPolicy, request: Request): Promise<Response | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAwB,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAU3E,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpF,MAAM,MAAM,cAAc,GAAG,SAAS,CAAC;AACvC,MAAM,MAAM,0BAA0B,GAAG,qBAAqB,CAAC;AAC/D,MAAM,MAAM,wBAAwB,GAAG,mBAAmB,CAAC;AAE3D,UAAU,4BAA4B;IACpC,YAAY,CAAC,EAAE,KAAK,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,KAAK,CAAC;CACjB;AAED,UAAU,0BAA0B;IAClC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,KAAK,CAAC;IACf,OAAO,EAAE,mBAAmB,EAAE,CAAC;CAChC;AAED,KAAK,iBAAiB,GAAG,4BAA4B,GAAG,0BAA0B,CAAC;AAEnF,UAAU,uBAAuB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC;IACtB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