@tylix/auth 1.4.0 → 1.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.
Files changed (65) hide show
  1. package/README.md +284 -14
  2. package/package.json +95 -9
  3. package/src/client/client.d.ts +14 -0
  4. package/src/client/client.js +83 -0
  5. package/src/cookies/authCookies.d.ts +8 -6
  6. package/src/cookies/authCookies.js +43 -28
  7. package/src/core/crypto.js +143 -0
  8. package/src/core/keys.js +83 -0
  9. package/src/core/seal.js +43 -0
  10. package/src/generators/AuthGenerator.d.ts +9 -3
  11. package/src/generators/AuthGenerator.js +16 -4
  12. package/src/generators/templates/auth-controller-ts.tyx +401 -98
  13. package/src/generators/templates/auth-controller.tyx +384 -96
  14. package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
  15. package/src/generators/templates/auth-session-migration.tyx +32 -0
  16. package/src/generators/templates/auth-session-model-ts.tyx +53 -0
  17. package/src/generators/templates/auth-session-model.tyx +34 -0
  18. package/src/generators/templates/auth-validator-ts.tyx +17 -0
  19. package/src/generators/templates/auth-validator.tyx +17 -0
  20. package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
  21. package/src/generators/templates/oauth-account-migration.tyx +27 -0
  22. package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
  23. package/src/generators/templates/oauth-account-model.tyx +45 -0
  24. package/src/generators/templates/password-reset-model-ts.tyx +26 -4
  25. package/src/generators/templates/password-reset-model.tyx +26 -4
  26. package/src/generators/templates/reset-password-view.html +30 -3
  27. package/src/generators/templates/verify-email-view.html +30 -3
  28. package/src/http/cookies.js +91 -0
  29. package/src/http/origin.js +68 -0
  30. package/src/http/request.js +179 -0
  31. package/src/index.d.ts +9 -1
  32. package/src/index.js +5 -0
  33. package/src/integrations/h3.d.ts +6 -0
  34. package/src/integrations/h3.js +70 -0
  35. package/src/integrations/hono.d.ts +6 -0
  36. package/src/integrations/hono.js +36 -0
  37. package/src/integrations/next.d.ts +16 -0
  38. package/src/integrations/next.js +36 -0
  39. package/src/integrations/node.d.ts +7 -0
  40. package/src/integrations/node.js +87 -0
  41. package/src/integrations/routes.js +92 -0
  42. package/src/integrations/sveltekit.d.ts +5 -0
  43. package/src/integrations/sveltekit.js +52 -0
  44. package/src/integrations/web.js +69 -0
  45. package/src/mfa/totp.js +150 -0
  46. package/src/oauth/oauth.js +142 -0
  47. package/src/oauth/providers.js +112 -0
  48. package/src/password/hashPassword.d.ts +5 -1
  49. package/src/password/hashPassword.js +96 -30
  50. package/src/password/index.d.ts +2 -0
  51. package/src/password/index.js +2 -0
  52. package/src/password/policy.js +108 -0
  53. package/src/rateLimiter/loginRateLimiter.js +16 -6
  54. package/src/ratelimit/limiter.js +129 -0
  55. package/src/session/adapters/keyValue.js +87 -0
  56. package/src/session/adapters/memory.js +38 -0
  57. package/src/session/adapters/model.js +97 -0
  58. package/src/session/adapters/prisma.js +67 -0
  59. package/src/session/adapters/sql.js +128 -0
  60. package/src/session/createAuth.js +420 -0
  61. package/src/token/jwt.js +144 -0
  62. package/src/token/signToken.js +41 -22
  63. package/src/tylix/accessTokens.js +61 -0
  64. package/src/web.d.ts +359 -0
  65. package/src/web.js +47 -0
@@ -0,0 +1,61 @@
1
+ import { createTokenSigner } from '../token/jwt.js'
2
+ import { verifyToken } from '../token/signToken.js'
3
+
4
+ // What @tylix/core's requireAuth uses to check a request's token. Accepts:
5
+ // - JWT access tokens from createAuth() sessions (current controllers)
6
+ // - legacy two-part tokens (older controllers, the test helper), but
7
+ // only real access tokens: anything carrying a purpose (an email
8
+ // verification link, say) or without an expiry is refused
9
+ //
10
+ // When the app's AuthController has registered a session guard, a JWT is
11
+ // only accepted while its session exists, so logout, "sign out
12
+ // everywhere" and password resets end access immediately.
13
+
14
+ const GUARD = Symbol.for('tylix.auth.sessionGuard')
15
+ const signers = new Map()
16
+
17
+ function signerFor(secret) {
18
+ const key = Array.isArray(secret) ? secret.join('\u0000') : secret
19
+ if (!signers.has(key)) signers.set(key, createTokenSigner({ secret }))
20
+ return signers.get(key)
21
+ }
22
+
23
+ /** Registers (fn) or clears (null) the check that a token's session still exists. */
24
+ export function setSessionGuard(fn) {
25
+ globalThis[GUARD] = typeof fn === 'function' ? fn : null
26
+ }
27
+
28
+ export function getSessionGuard() {
29
+ return globalThis[GUARD] ?? null
30
+ }
31
+
32
+ function fail(error) {
33
+ return { valid: false, payload: null, error }
34
+ }
35
+
36
+ export async function verifyAccessToken(token, secret) {
37
+ if (typeof token !== 'string' || token.length === 0) return fail('Malformed token')
38
+ if (!secret) return fail('No secret configured')
39
+
40
+ const segments = token.split('.').length
41
+ if (segments === 3) {
42
+ const result = await signerFor(secret).verify(token, { type: 'access' })
43
+ if (!result.valid) return result
44
+ const guard = getSessionGuard()
45
+ if (guard && typeof result.payload.sid === 'string' && !(await guard(result.payload))) {
46
+ return fail('Session ended')
47
+ }
48
+ return result
49
+ }
50
+
51
+ if (segments === 2) {
52
+ const primary = Array.isArray(secret) ? secret[0] : secret
53
+ const result = verifyToken(token, primary)
54
+ if (!result.valid) return result
55
+ if (result.payload.purpose != null || result.payload.typ != null) return fail('Wrong token type')
56
+ if (!Number.isFinite(result.payload.exp)) return fail('Token has no expiry')
57
+ return result
58
+ }
59
+
60
+ return fail('Malformed token')
61
+ }
package/src/web.d.ts ADDED
@@ -0,0 +1,359 @@
1
+ // Types for "@tylix/auth/web" (edge-safe) and re-exported by "@tylix/auth".
2
+
3
+ /** Anything a framework calls a request: Web Request, Headers, Node/Express/Fastify req, Koa ctx, h3 event, SvelteKit event, Hono context. */
4
+ export type RequestLike = Request | Headers | { headers: unknown; [key: string]: any } | { request: unknown } | { req: unknown } | { node: { req: unknown } } | Record<string, any>
5
+ /** Anything Set-Cookie headers can be written to: Headers, Response, Node/Express res, Fastify reply, Koa ctx, Hono context, h3 event. */
6
+ export type ResponseLike = Headers | Response | Record<string, any>
7
+ /** Seconds, or "30s", "15m", "12h", "30d", "2w". */
8
+ export type Duration = number | string
9
+ export type Secret = string | string[]
10
+ export type UserId = string | number
11
+
12
+ // --- sessions ----------------------------------------------------------------
13
+
14
+ export interface SessionRecord {
15
+ id: string
16
+ userId: UserId
17
+ tokenHash: string
18
+ prevTokenHash: string | null
19
+ rotatedAt: number | null
20
+ createdAt: number
21
+ lastUsedAt: number
22
+ expiresAt: number
23
+ idleExpiresAt: number | null
24
+ persistent: boolean
25
+ ip: string | null
26
+ userAgent: string | null
27
+ data: unknown
28
+ }
29
+
30
+ export type PublicSession = Omit<SessionRecord, 'tokenHash' | 'prevTokenHash' | 'rotatedAt'> & { current?: boolean }
31
+
32
+ /** Where sessions are stored. Implement this to use any database. */
33
+ export interface SessionAdapter {
34
+ ephemeral?: boolean
35
+ create(record: SessionRecord): Promise<void>
36
+ get(id: string): Promise<SessionRecord | null>
37
+ /** With expectTokenHash, must update only if the stored tokenHash still equals it (compare-and-swap) and resolve whether it did. */
38
+ update(id: string, patch: Partial<SessionRecord>, options?: { expectTokenHash?: string }): Promise<boolean>
39
+ delete(id: string): Promise<void>
40
+ deleteByUser(userId: UserId, options?: { exceptId?: string }): Promise<number>
41
+ listByUser(userId: UserId): Promise<SessionRecord[]>
42
+ }
43
+
44
+ export interface AuthEvent {
45
+ type: 'session.created' | 'session.refreshed' | 'session.revoked' | 'session.revoked_all' | 'session.expired' | 'session.rejected' | 'session.reuse_detected'
46
+ at: string
47
+ sessionId?: string
48
+ userId?: UserId
49
+ [key: string]: unknown
50
+ }
51
+
52
+ export interface CreateAuthOptions {
53
+ /** One secret, or several for rotation (the first signs, all verify). At least 32 characters. */
54
+ secret: Secret
55
+ /** Where sessions live. Default: memory (single process, dev only). */
56
+ adapter?: SessionAdapter
57
+ issuer?: string
58
+ audience?: string | string[]
59
+ /** Default "15m". */
60
+ accessTokenTtl?: Duration
61
+ /** Absolute session lifetime for "remember me" logins. Default "30d". */
62
+ sessionTtl?: Duration
63
+ /** Absolute lifetime when persistent: false. Default "1d". */
64
+ shortSessionTtl?: Duration
65
+ /** Ends sessions unused for this long. Default "14d". */
66
+ idleTimeout?: Duration
67
+ /** How long a just-rotated refresh token still works (parallel tabs). Default "30s". */
68
+ rotationGrace?: Duration
69
+ /** Believe X-Forwarded-* headers. Only behind a proxy you control. */
70
+ trustProxy?: boolean
71
+ /** Other origins allowed to make cookie-authenticated writes. */
72
+ trustedOrigins?: string[]
73
+ /** getSession() looks the session up, so revocation is immediate. Default true. */
74
+ checkRevocation?: boolean
75
+ /** Accept "Authorization: Bearer". Default true. */
76
+ allowBearer?: boolean
77
+ /** Refuse cookie-authenticated cross-site writes. Default true. */
78
+ csrf?: boolean
79
+ storeIp?: boolean
80
+ storeUserAgent?: boolean
81
+ cookies?: {
82
+ accessName?: string
83
+ refreshName?: string
84
+ /** Use __Host-/__Secure- prefixes on HTTPS. Default true. */
85
+ prefix?: boolean
86
+ /** Path of the refresh cookie; must cover your refresh and logout routes. Default "/api/auth". */
87
+ refreshPath?: string
88
+ sameSite?: 'lax' | 'strict' | 'none'
89
+ domain?: string
90
+ /** Default "auto": on for HTTPS requests and in production. */
91
+ secure?: boolean | 'auto'
92
+ /** Old refresh-cookie paths to expire whenever the cookie is set. */
93
+ legacyRefreshPaths?: string[]
94
+ }
95
+ /** Extra claims for access tokens. */
96
+ claims?: (session: PublicSession) => Record<string, unknown> | Promise<Record<string, unknown>>
97
+ /** Called at every refresh; return false to end the session (banned user, ...). */
98
+ validateSession?: (session: PublicSession) => boolean | Promise<boolean>
99
+ /** Audit hook. Errors thrown here are ignored. */
100
+ onEvent?: (event: AuthEvent) => unknown
101
+ }
102
+
103
+ export interface AccessClaims {
104
+ sub: string
105
+ sid: string
106
+ uid: UserId
107
+ iat: number
108
+ exp: number
109
+ jti: string
110
+ [key: string]: unknown
111
+ }
112
+
113
+ export interface CurrentSession {
114
+ userId: UserId
115
+ sessionId: string
116
+ claims: AccessClaims
117
+ /** null when checkRevocation is off. */
118
+ session: PublicSession | null
119
+ via: 'cookie' | 'bearer'
120
+ }
121
+
122
+ export interface SignInResult {
123
+ session: PublicSession
124
+ accessToken: string
125
+ refreshToken: string
126
+ /** Set-Cookie header values: send them with the response (see applyCookies). */
127
+ cookies: string[]
128
+ }
129
+
130
+ export type RefreshResult =
131
+ | { ok: true; session: PublicSession; accessToken: string; refreshToken: string | null; cookies: string[] }
132
+ | { ok: false; reason: 'missing' | 'invalid' | 'expired' | 'reused' | 'revoked' | 'rejected' | 'cross-site'; cookies: string[] }
133
+
134
+ export interface Auth {
135
+ signIn(request: RequestLike | null, userId: UserId, options?: { persistent?: boolean; data?: unknown }): Promise<SignInResult>
136
+ signOut(request: RequestLike): Promise<{ ok: true; sessionId: string | null; cookies: string[] }>
137
+ refresh(request: RequestLike): Promise<RefreshResult>
138
+ getSession(request: RequestLike, options?: { checkRevocation?: boolean }): Promise<CurrentSession | null>
139
+ verifyAccessToken(token: string): Promise<AccessClaims | null>
140
+ revokeSession(sessionId: string): Promise<boolean>
141
+ revokeAllSessions(userId: UserId, options?: { exceptSessionId?: string }): Promise<number>
142
+ listSessions(userId: UserId, options?: { currentSessionId?: string }): Promise<PublicSession[]>
143
+ updateSessionData(sessionId: string, data: unknown): Promise<boolean>
144
+ isSessionActive(sessionId: string, userId?: UserId): Promise<boolean>
145
+ clearCookies(request?: RequestLike | null): string[]
146
+ cookieNames(request?: RequestLike | null): { access: string; refresh: string; secure: boolean }
147
+ isCrossSite(request: RequestLike): boolean
148
+ tokens: TokenSigner
149
+ sealer: Sealer
150
+ adapter: SessionAdapter
151
+ options: { accessTokenTtl: number; refreshPath: string; trustProxy: boolean; trustedOrigins: string[] }
152
+ }
153
+
154
+ export declare function createAuth(options: CreateAuthOptions): Auth
155
+
156
+ export declare function memoryAdapter(): SessionAdapter
157
+ export declare function keyValueAdapter(
158
+ store: { get(key: string): Promise<unknown>; set(key: string, value: string, options?: { ttlMs?: number }): Promise<unknown>; delete(key: string): Promise<unknown> },
159
+ options?: { prefix?: string },
160
+ ): SessionAdapter
161
+ export declare function sqlAdapter(options: {
162
+ query: (sql: string, params: unknown[]) => Promise<unknown>
163
+ dialect?: 'postgres' | 'mysql' | 'sqlite'
164
+ table?: string
165
+ }): SessionAdapter
166
+ export declare function createTableSql(options?: { table?: string; dialect?: 'postgres' | 'mysql' | 'sqlite' }): string[]
167
+ export declare function prismaAdapter(delegate: any): SessionAdapter
168
+ export declare function modelAdapter(Model: any): SessionAdapter
169
+
170
+ // --- tokens & sealing --------------------------------------------------------
171
+
172
+ export interface VerifyResult<T = Record<string, unknown>> {
173
+ valid: boolean
174
+ payload: (T & { iat?: number; exp: number; sub?: string; jti?: string }) | null
175
+ error: string | null
176
+ }
177
+
178
+ export interface TokenSigner {
179
+ sign(claims?: Record<string, unknown>, options?: { type?: string; expiresIn: Duration; notBefore?: Duration; jwtId?: boolean; subject?: UserId }): Promise<string>
180
+ verify<T = Record<string, unknown>>(token: string, options?: { type?: string; issuer?: string; audience?: string | string[]; maxAgeSeconds?: Duration }): Promise<VerifyResult<T>>
181
+ }
182
+
183
+ export declare function createTokenSigner(options: { secret?: Secret; keyring?: Keyring; issuer?: string; audience?: string | string[]; clockToleranceSeconds?: number; maxTokenLength?: number }): TokenSigner
184
+ export declare function decodeTokenUnsafe(token: string): { header: Record<string, unknown>; payload: Record<string, unknown> } | null
185
+
186
+ export interface Sealer {
187
+ seal(value: unknown, options?: { purpose?: string; expiresIn?: Duration }): Promise<string>
188
+ unseal<T = unknown>(sealed: string, options?: { purpose?: string }): Promise<T | null>
189
+ }
190
+ export declare function createSealer(options: { secret?: Secret; keyring?: Keyring }): Sealer
191
+
192
+ export interface Keyring {
193
+ size: number
194
+ kid(index: number): Promise<string>
195
+ hmac(purpose: string, index?: number, hash?: string): Promise<CryptoKey>
196
+ aes(purpose: string, index?: number): Promise<CryptoKey>
197
+ indexOfKid(kid: string): Promise<number>
198
+ }
199
+ export declare function createKeyring(secret: Secret): Keyring
200
+ export declare function normalizeSecrets(secret: Secret): string[]
201
+ export declare function toSeconds(value: Duration, name?: string): number
202
+ export declare const MIN_SECRET_LENGTH: number
203
+
204
+ export declare function randomToken(bytes?: number): string
205
+ export declare function timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean
206
+ export declare function sha256Hex(input: string | Uint8Array): Promise<string>
207
+ export declare function base64urlEncode(input: string | Uint8Array): string
208
+ export declare function base64urlDecode(input: string): Uint8Array
209
+
210
+ // --- http --------------------------------------------------------------------
211
+
212
+ export interface CookieOptions {
213
+ maxAge?: number
214
+ expires?: Date | string | number
215
+ path?: string
216
+ domain?: string
217
+ secure?: boolean
218
+ httpOnly?: boolean
219
+ sameSite?: 'lax' | 'strict' | 'none'
220
+ partitioned?: boolean
221
+ priority?: 'Low' | 'Medium' | 'High'
222
+ }
223
+ export declare function parseCookieHeader(header: string | null | undefined): Record<string, string>
224
+ export declare function parseCookieHeaderAll(header: string | null | undefined): Record<string, string[]>
225
+ export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string
226
+ export declare function expireCookie(name: string, options?: CookieOptions): string
227
+
228
+ export declare function applyCookies<T extends ResponseLike>(target: T, cookies: string | string[]): T
229
+ export declare function cookieHeaders(cookies: string[], init?: HeadersInit): Headers
230
+ export declare function getClientIp(request: RequestLike, options?: { trustProxy?: boolean }): string
231
+ export declare function getCookie(request: RequestLike, name: string): string | null
232
+ export declare function getHeader(request: RequestLike, name: string): string | null
233
+ export declare function isSecureRequest(request: RequestLike, options?: { trustProxy?: boolean }): boolean
234
+ export declare function isCrossSiteRequest(request: RequestLike, options?: { trustedOrigins?: string[]; trustProxy?: boolean; allowSafeMethods?: boolean }): boolean
235
+ export declare function safeRedirectPath(value: unknown, fallback?: string): string
236
+
237
+ // --- rate limits & passwords -------------------------------------------------
238
+
239
+ export interface CounterStore {
240
+ get(key: string): Promise<unknown>
241
+ increment(key: string, options?: { by?: number; ttlMs?: number }): Promise<number>
242
+ delete?(key: string): Promise<unknown>
243
+ }
244
+ export interface LimitResult {
245
+ allowed: boolean
246
+ remaining: number
247
+ retryAfterSeconds: number
248
+ }
249
+ export interface RateLimiter {
250
+ check(identifier: string, options?: { cost?: number }): Promise<LimitResult>
251
+ peek(identifier: string): Promise<LimitResult>
252
+ reset(identifier: string): Promise<void>
253
+ }
254
+ export declare function createRateLimiter(options: { name: string; max: number; window: Duration; store?: CounterStore }): RateLimiter
255
+ export interface LoginThrottle {
256
+ check(attempt: { identifier: string; ip?: string }): Promise<{ allowed: boolean; retryAfterSeconds: number }>
257
+ fail(attempt: { identifier: string; ip?: string }): Promise<void>
258
+ succeed(attempt: { identifier: string; ip?: string }): Promise<void>
259
+ }
260
+ export declare function createLoginThrottle(options?: {
261
+ store?: CounterStore
262
+ name?: string
263
+ limits?: Partial<Record<'pair' | 'account' | 'ip', { max?: number; window?: Duration }>>
264
+ }): LoginThrottle
265
+ export declare function createMemoryCounterStore(options?: { maxKeys?: number }): CounterStore
266
+
267
+ export declare function checkPasswordStrength(
268
+ password: unknown,
269
+ options?: { minLength?: number; maxLength?: number; userInputs?: string[]; breached?: boolean; fetch?: typeof fetch },
270
+ ): Promise<{ ok: boolean; errors: string[] }>
271
+ export declare function breachCount(password: string, options?: { fetch?: typeof fetch; timeoutMs?: number }): Promise<number>
272
+
273
+ // --- MFA ---------------------------------------------------------------------
274
+
275
+ type TotpOptions = { digits?: number; period?: number; algorithm?: 'SHA1' | 'SHA256' | 'SHA512' }
276
+ export declare function generateTotpSecret(bytes?: number): string
277
+ export declare function generateTotp(secret: string, options?: TotpOptions & { time?: number }): Promise<string>
278
+ export declare function verifyTotp(
279
+ code: string,
280
+ secret: string,
281
+ options?: TotpOptions & { time?: number; window?: number; lastUsedStep?: number | null },
282
+ ): Promise<{ valid: boolean; step: number | null; replay?: boolean }>
283
+ export declare function totpUri(options: { secret: string; issuer: string; account: string } & TotpOptions): string
284
+ export declare function generateRecoveryCodes(count?: number): Promise<{ codes: string[]; hashes: string[] }>
285
+ export declare function verifyRecoveryCode(code: string, hashes: string[]): Promise<number>
286
+ export declare function base32Encode(bytes: Uint8Array): string
287
+ export declare function base32Decode(input: string): Uint8Array
288
+
289
+ // --- OAuth -------------------------------------------------------------------
290
+
291
+ export interface OAuthProfile {
292
+ provider: string
293
+ id: string
294
+ email: string | null
295
+ /** Only true when the provider vouches for the address. Link accounts by email only when this is true. */
296
+ emailVerified: boolean
297
+ name: string | null
298
+ avatarUrl: string | null
299
+ [key: string]: unknown
300
+ }
301
+ export interface OAuthProvider {
302
+ id: string
303
+ authorizationUrl: string
304
+ tokenUrl: string
305
+ clientId: string
306
+ clientSecret?: string
307
+ redirectUri: string
308
+ scopes: string[]
309
+ authorizationParams?: Record<string, string>
310
+ clientAuth?: 'post' | 'basic'
311
+ oidc?: boolean
312
+ profile(context: { get(url: string): Promise<any>; tokens: Record<string, any> }): Promise<Omit<OAuthProfile, 'provider'>>
313
+ }
314
+ type ProviderOptions = { clientId: string; clientSecret: string; redirectUri: string; scopes?: string[]; authorizationParams?: Record<string, string> }
315
+ export declare function oauthProvider(definition: Partial<OAuthProvider> & Pick<OAuthProvider, 'id' | 'authorizationUrl' | 'tokenUrl' | 'clientId' | 'redirectUri' | 'profile'>): OAuthProvider
316
+ export declare function github(options: ProviderOptions): OAuthProvider
317
+ export declare function google(options: ProviderOptions): OAuthProvider
318
+ export declare function discord(options: ProviderOptions): OAuthProvider
319
+ export declare function gitlab(options: ProviderOptions & { baseUrl?: string }): OAuthProvider
320
+ export declare function microsoft(options: ProviderOptions & { tenant?: string }): OAuthProvider
321
+
322
+ export declare class OAuthError extends Error {
323
+ code: 'provider_error' | 'missing_params' | 'state_mismatch' | 'token_exchange_failed' | 'profile_failed'
324
+ cookies?: string[]
325
+ }
326
+ export interface OAuth {
327
+ start(provider: OAuthProvider, request: RequestLike | null, options?: { returnTo?: string; scopes?: string[]; params?: Record<string, string> }): Promise<{ url: string; cookies: string[] }>
328
+ callback(provider: OAuthProvider, request: RequestLike): Promise<{ profile: OAuthProfile; tokens: Record<string, any>; returnTo: string; cookies: string[] }>
329
+ }
330
+ export declare function createOAuth(options: { sealer: Sealer; trustProxy?: boolean; cookieName?: string; fetch?: typeof fetch }): OAuth
331
+
332
+ // --- routes ------------------------------------------------------------------
333
+
334
+ export interface RouteOptions {
335
+ /** Default "/api/auth". */
336
+ basePath?: string
337
+ /** Adds `user` to GET /session. */
338
+ user?: (userId: UserId, session: CurrentSession) => unknown
339
+ }
340
+ export interface RouteResult {
341
+ status: number
342
+ body: unknown
343
+ cookies: string[]
344
+ }
345
+ export declare function handleAuthRoute(auth: Auth, request: RequestLike, options?: RouteOptions): Promise<RouteResult | null>
346
+ export declare function createAuthHandler(auth: Auth, options?: RouteOptions): (request: Request) => Promise<Response>
347
+ export declare function jsonWithCookies(body: unknown, options?: { status?: number; cookies?: string[]; headers?: HeadersInit }): Response
348
+ export declare function redirectWithCookies(location: string, options?: { status?: number; cookies?: string[] }): Response
349
+ export declare function withSession<C extends object = {}>(
350
+ auth: Auth,
351
+ handler: (request: Request, context: C & { session: CurrentSession | null }) => Response | Promise<Response>,
352
+ options?: { optional?: boolean; checkRevocation?: boolean },
353
+ ): (request: Request, context?: C) => Promise<Response>
354
+ export type ProtectRule = string[] | RegExp | ((pathname: string) => boolean)
355
+ export declare function guardRequest(
356
+ auth: Auth,
357
+ request: Request,
358
+ options?: { protect?: ProtectRule; guestOnly?: ProtectRule; loginPath?: string; homePath?: string },
359
+ ): Promise<Response | null>
package/src/web.js ADDED
@@ -0,0 +1,47 @@
1
+ // Edge-safe entry: Web Crypto and Web standards only, no node:* imports.
2
+ // Runs on Node, Bun, Deno, Cloudflare Workers, Vercel/Next.js edge.
3
+ // (Password hashing needs node:crypto's scrypt: import it from
4
+ // "@tylix/auth" or "@tylix/auth/password" in server code.)
5
+
6
+ export { createAuth } from './session/createAuth.js'
7
+ export { memoryAdapter } from './session/adapters/memory.js'
8
+ export { keyValueAdapter } from './session/adapters/keyValue.js'
9
+ export { sqlAdapter, createTableSql } from './session/adapters/sql.js'
10
+ export { prismaAdapter } from './session/adapters/prisma.js'
11
+ export { modelAdapter } from './session/adapters/model.js'
12
+
13
+ export { createTokenSigner, decodeTokenUnsafe } from './token/jwt.js'
14
+ export { createSealer } from './core/seal.js'
15
+ export { createKeyring, normalizeSecrets, toSeconds, MIN_SECRET_LENGTH } from './core/keys.js'
16
+ export { randomToken, timingSafeEqual, sha256Hex, base64urlEncode, base64urlDecode } from './core/crypto.js'
17
+
18
+ export { parseCookieHeader, parseCookieHeaderAll, serializeCookie, expireCookie } from './http/cookies.js'
19
+ export {
20
+ applyCookies,
21
+ cookieHeaders,
22
+ getClientIp,
23
+ getCookie,
24
+ getHeader,
25
+ isSecureRequest,
26
+ } from './http/request.js'
27
+ export { isCrossSiteRequest, safeRedirectPath } from './http/origin.js'
28
+
29
+ export { createRateLimiter, createLoginThrottle, createMemoryCounterStore } from './ratelimit/limiter.js'
30
+ export { checkPasswordStrength, breachCount } from './password/policy.js'
31
+
32
+ export {
33
+ generateTotpSecret,
34
+ generateTotp,
35
+ verifyTotp,
36
+ totpUri,
37
+ generateRecoveryCodes,
38
+ verifyRecoveryCode,
39
+ base32Encode,
40
+ base32Decode,
41
+ } from './mfa/totp.js'
42
+
43
+ export { createOAuth, OAuthError } from './oauth/oauth.js'
44
+ export { oauthProvider, github, google, discord, gitlab, microsoft } from './oauth/providers.js'
45
+
46
+ export { handleAuthRoute } from './integrations/routes.js'
47
+ export { createAuthHandler, jsonWithCookies, redirectWithCookies, withSession, guardRequest } from './integrations/web.js'