@tylix/auth 1.3.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.
- package/README.md +284 -14
- package/package.json +95 -9
- package/src/client/client.d.ts +14 -0
- package/src/client/client.js +83 -0
- package/src/cookies/authCookies.d.ts +8 -6
- package/src/cookies/authCookies.js +43 -28
- package/src/core/crypto.js +143 -0
- package/src/core/keys.js +83 -0
- package/src/core/seal.js +43 -0
- package/src/generators/AuthGenerator.d.ts +9 -3
- package/src/generators/AuthGenerator.js +16 -4
- package/src/generators/templates/auth-controller-ts.tyx +401 -98
- package/src/generators/templates/auth-controller.tyx +384 -96
- package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
- package/src/generators/templates/auth-session-migration.tyx +32 -0
- package/src/generators/templates/auth-session-model-ts.tyx +53 -0
- package/src/generators/templates/auth-session-model.tyx +34 -0
- package/src/generators/templates/auth-validator-ts.tyx +17 -0
- package/src/generators/templates/auth-validator.tyx +17 -0
- package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
- package/src/generators/templates/oauth-account-migration.tyx +27 -0
- package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
- package/src/generators/templates/oauth-account-model.tyx +45 -0
- package/src/generators/templates/password-reset-model-ts.tyx +26 -4
- package/src/generators/templates/password-reset-model.tyx +26 -4
- package/src/generators/templates/reset-password-view.html +30 -3
- package/src/generators/templates/verify-email-view.html +30 -3
- package/src/http/cookies.js +91 -0
- package/src/http/origin.js +68 -0
- package/src/http/request.js +179 -0
- package/src/index.d.ts +9 -1
- package/src/index.js +5 -0
- package/src/integrations/h3.d.ts +6 -0
- package/src/integrations/h3.js +70 -0
- package/src/integrations/hono.d.ts +6 -0
- package/src/integrations/hono.js +36 -0
- package/src/integrations/next.d.ts +16 -0
- package/src/integrations/next.js +36 -0
- package/src/integrations/node.d.ts +7 -0
- package/src/integrations/node.js +87 -0
- package/src/integrations/routes.js +92 -0
- package/src/integrations/sveltekit.d.ts +5 -0
- package/src/integrations/sveltekit.js +52 -0
- package/src/integrations/web.js +69 -0
- package/src/mfa/totp.js +150 -0
- package/src/oauth/oauth.js +142 -0
- package/src/oauth/providers.js +112 -0
- package/src/password/hashPassword.d.ts +5 -1
- package/src/password/hashPassword.js +96 -30
- package/src/password/index.d.ts +2 -0
- package/src/password/index.js +2 -0
- package/src/password/policy.js +108 -0
- package/src/rateLimiter/loginRateLimiter.js +16 -6
- package/src/ratelimit/limiter.js +129 -0
- package/src/session/adapters/keyValue.js +87 -0
- package/src/session/adapters/memory.js +38 -0
- package/src/session/adapters/model.js +97 -0
- package/src/session/adapters/prisma.js +67 -0
- package/src/session/adapters/sql.js +128 -0
- package/src/session/createAuth.js +420 -0
- package/src/token/jwt.js +144 -0
- package/src/token/signToken.js +41 -22
- package/src/tylix/accessTokens.js +61 -0
- package/src/web.d.ts +359 -0
- package/src/web.js +47 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { getHeader, getHost, getMethod } from './request.js'
|
|
2
|
+
|
|
3
|
+
// CSRF protection without tokens, the way modern browsers make possible:
|
|
4
|
+
// every browser request is labelled with Sec-Fetch-Site (and Origin on
|
|
5
|
+
// writes). Those headers cannot be set by page JavaScript, so a write
|
|
6
|
+
// from another site is recognisable and refused. Requests with neither
|
|
7
|
+
// header (curl, server-to-server, webhooks) carry no ambient browser
|
|
8
|
+
// cookies by accident and are not CSRF; they pass.
|
|
9
|
+
//
|
|
10
|
+
// Combined with SameSite=Lax cookies this blocks cross-site and
|
|
11
|
+
// same-site (sibling subdomain) forgeries alike.
|
|
12
|
+
|
|
13
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
14
|
+
|
|
15
|
+
export function originOf(value) {
|
|
16
|
+
if (!value || value === 'null') return null
|
|
17
|
+
try {
|
|
18
|
+
const url = new URL(value)
|
|
19
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
|
|
20
|
+
return url.origin.toLowerCase()
|
|
21
|
+
} catch {
|
|
22
|
+
return null
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* True when the request is a state-changing browser request from a site
|
|
28
|
+
* other than this one (or a trusted origin). Use it to refuse the request.
|
|
29
|
+
*/
|
|
30
|
+
export function isCrossSiteRequest(input, { trustedOrigins = [], trustProxy = false, allowSafeMethods = true } = {}) {
|
|
31
|
+
if (allowSafeMethods && SAFE_METHODS.has(getMethod(input))) return false
|
|
32
|
+
|
|
33
|
+
const site = getHeader(input, 'sec-fetch-site')
|
|
34
|
+
const originHeader = getHeader(input, 'origin')
|
|
35
|
+
if (!site && !originHeader) return false
|
|
36
|
+
if (site === 'same-origin' || site === 'none') return false
|
|
37
|
+
|
|
38
|
+
const origin = originOf(originHeader)
|
|
39
|
+
if (!origin) return true
|
|
40
|
+
const trusted = new Set(trustedOrigins.map((o) => originOf(o)).filter(Boolean))
|
|
41
|
+
if (trusted.has(origin)) return false
|
|
42
|
+
|
|
43
|
+
// Same-site (a sibling subdomain) is NOT trusted unless listed: a
|
|
44
|
+
// compromised or user-controlled subdomain must not be able to act.
|
|
45
|
+
if (site === 'same-site' || site === 'cross-site') return true
|
|
46
|
+
|
|
47
|
+
// No Sec-Fetch-Site (older browser): compare Origin with Host.
|
|
48
|
+
const host = getHost(input, { trustProxy })
|
|
49
|
+
return !host || new URL(origin).host !== host
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Only allows relative, same-site paths as redirect targets: "/dashboard?x=1"
|
|
54
|
+
* yes; "https://evil.example", "//evil.example", "/\\evil.example",
|
|
55
|
+
* "javascript:..." no. Use it for every ?next= / returnTo value.
|
|
56
|
+
*/
|
|
57
|
+
export function safeRedirectPath(value, fallback = '/') {
|
|
58
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > 2048) return fallback
|
|
59
|
+
if (!value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) return fallback
|
|
60
|
+
if (/[\u0000-\u001f\u007f]/.test(value)) return fallback
|
|
61
|
+
try {
|
|
62
|
+
const url = new URL(value, 'http://localhost')
|
|
63
|
+
if (url.origin !== 'http://localhost') return fallback
|
|
64
|
+
return url.pathname + url.search + url.hash
|
|
65
|
+
} catch {
|
|
66
|
+
return fallback
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { parseCookieHeaderAll } from './cookies.js'
|
|
2
|
+
|
|
3
|
+
// Reads what auth needs from whatever a framework calls a request:
|
|
4
|
+
//
|
|
5
|
+
// Web Request Next.js App Router, Remix, Astro, Bun, Deno, Workers
|
|
6
|
+
// Headers Next.js `await headers()`
|
|
7
|
+
// { request } SvelteKit RequestEvent, Astro APIContext
|
|
8
|
+
// { req: { raw } } Hono Context
|
|
9
|
+
// { node: { req } } h3 / Nuxt / Nitro H3Event
|
|
10
|
+
// { headers: {...} } Node http, Express, Connect, Fastify, Koa ctx/request, Tylix
|
|
11
|
+
|
|
12
|
+
function isHeaders(value) {
|
|
13
|
+
return value != null && typeof value.get === 'function' && typeof value.has === 'function'
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Unwraps a framework event/context to the object that carries headers. */
|
|
17
|
+
export function unwrapRequest(input) {
|
|
18
|
+
if (input == null) throw new TypeError('Expected a request')
|
|
19
|
+
if (isHeaders(input)) return { headers: input }
|
|
20
|
+
if (typeof Request !== 'undefined' && input instanceof Request) return input
|
|
21
|
+
if (input.req?.raw) return input.req.raw // Hono
|
|
22
|
+
if (typeof Request !== 'undefined' && input.req instanceof Request) return input.req // h3 v2
|
|
23
|
+
if (input.request && (input.request.headers || input.request instanceof Request)) {
|
|
24
|
+
// SvelteKit/Astro carry a Web Request; Koa's ctx.request carries
|
|
25
|
+
// Node headers. Either way the inner object is the request.
|
|
26
|
+
return input.request
|
|
27
|
+
}
|
|
28
|
+
if (input.node?.req) return input.node.req // h3
|
|
29
|
+
return input
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function getHeader(input, name) {
|
|
33
|
+
const req = unwrapRequest(input)
|
|
34
|
+
const headers = req.headers
|
|
35
|
+
if (!headers) return null
|
|
36
|
+
if (isHeaders(headers)) return headers.get(name)
|
|
37
|
+
const value = headers[name.toLowerCase()] ?? headers[name]
|
|
38
|
+
if (Array.isArray(value)) return value.join(name.toLowerCase() === 'cookie' ? '; ' : ', ')
|
|
39
|
+
return value == null ? null : String(value)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function getMethod(input) {
|
|
43
|
+
const req = unwrapRequest(input)
|
|
44
|
+
return String(req.method ?? 'GET').toUpperCase()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** All values per cookie name, straight from the Cookie header. */
|
|
48
|
+
export function getCookiesAll(input) {
|
|
49
|
+
return parseCookieHeaderAll(getHeader(input, 'cookie'))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** First value of one cookie, or null. */
|
|
53
|
+
export function getCookie(input, name) {
|
|
54
|
+
return getCookiesAll(input)[name]?.[0] ?? null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function firstForwarded(value) {
|
|
58
|
+
return value ? String(value).split(',')[0].trim() : null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Whether the request arrived over HTTPS. X-Forwarded-Proto is only
|
|
63
|
+
* believed with trustProxy, since any client can send it.
|
|
64
|
+
*/
|
|
65
|
+
export function isSecureRequest(input, { trustProxy = false } = {}) {
|
|
66
|
+
const req = unwrapRequest(input)
|
|
67
|
+
if (trustProxy) {
|
|
68
|
+
const proto = firstForwarded(getHeader(req, 'x-forwarded-proto'))
|
|
69
|
+
if (proto) return proto === 'https'
|
|
70
|
+
}
|
|
71
|
+
if (typeof req.url === 'string' && /^https:/i.test(req.url)) return true
|
|
72
|
+
if (req.secure === true || req.protocol === 'https') return true
|
|
73
|
+
if (req.socket?.encrypted || req.connection?.encrypted) return true
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function getHost(input, { trustProxy = false } = {}) {
|
|
78
|
+
if (trustProxy) {
|
|
79
|
+
const forwarded = firstForwarded(getHeader(input, 'x-forwarded-host'))
|
|
80
|
+
if (forwarded) return forwarded.toLowerCase()
|
|
81
|
+
}
|
|
82
|
+
const req = unwrapRequest(input)
|
|
83
|
+
const host = getHeader(req, 'host')
|
|
84
|
+
if (host) return host.toLowerCase()
|
|
85
|
+
if (typeof req.url === 'string' && /^https?:\/\//i.test(req.url)) {
|
|
86
|
+
try {
|
|
87
|
+
return new URL(req.url).host.toLowerCase()
|
|
88
|
+
} catch {}
|
|
89
|
+
}
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The path of the request (no query string). */
|
|
94
|
+
export function getPathname(input) {
|
|
95
|
+
const req = unwrapRequest(input)
|
|
96
|
+
const raw = req.originalUrl ?? req.url ?? '/'
|
|
97
|
+
try {
|
|
98
|
+
return new URL(raw, 'http://localhost').pathname
|
|
99
|
+
} catch {
|
|
100
|
+
return '/'
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function getSearchParam(input, name) {
|
|
105
|
+
const req = unwrapRequest(input)
|
|
106
|
+
const raw = req.originalUrl ?? req.url ?? '/'
|
|
107
|
+
try {
|
|
108
|
+
return new URL(raw, 'http://localhost').searchParams.get(name)
|
|
109
|
+
} catch {
|
|
110
|
+
return null
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The client's IP. Proxy headers are only read with trustProxy (a client
|
|
116
|
+
* can put anything there). Falls back to the socket address, or an IP a
|
|
117
|
+
* framework already resolved (Express req.ip, Fastify request.ip).
|
|
118
|
+
*/
|
|
119
|
+
export function getClientIp(input, { trustProxy = false } = {}) {
|
|
120
|
+
const req = unwrapRequest(input)
|
|
121
|
+
if (trustProxy) {
|
|
122
|
+
const candidates = [
|
|
123
|
+
getHeader(req, 'cf-connecting-ip'),
|
|
124
|
+
getHeader(req, 'x-real-ip'),
|
|
125
|
+
firstForwarded(getHeader(req, 'x-forwarded-for')),
|
|
126
|
+
]
|
|
127
|
+
for (const ip of candidates) if (ip) return ip.trim()
|
|
128
|
+
}
|
|
129
|
+
return req.ip ?? req.socket?.remoteAddress ?? req.connection?.remoteAddress ?? input?.clientAddress ?? 'unknown'
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// --- writing cookies back ------------------------------------------------
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Adds Set-Cookie headers to whatever the framework uses as a response:
|
|
136
|
+
* Headers, a Web Response, Node/Express res, Fastify reply, Koa ctx,
|
|
137
|
+
* Hono context or an h3 event. Returns the target for chaining.
|
|
138
|
+
*/
|
|
139
|
+
export function applyCookies(target, cookies) {
|
|
140
|
+
const list = (Array.isArray(cookies) ? cookies : [cookies]).filter(Boolean)
|
|
141
|
+
if (list.length === 0 || target == null) return target
|
|
142
|
+
|
|
143
|
+
if (isHeaders(target)) {
|
|
144
|
+
for (const c of list) target.append('Set-Cookie', c)
|
|
145
|
+
return target
|
|
146
|
+
}
|
|
147
|
+
if (target.headers && isHeaders(target.headers) && typeof target.status === 'number' && !target.setHeader) {
|
|
148
|
+
for (const c of list) target.headers.append('Set-Cookie', c) // Web Response
|
|
149
|
+
return target
|
|
150
|
+
}
|
|
151
|
+
if (target.req?.raw && typeof target.header === 'function') {
|
|
152
|
+
for (const c of list) target.header('Set-Cookie', c, { append: true }) // Hono
|
|
153
|
+
return target
|
|
154
|
+
}
|
|
155
|
+
if (target.node?.res) return applyCookies(target.node.res, list) // h3 v1
|
|
156
|
+
if (target.res?.headers && isHeaders(target.res.headers)) {
|
|
157
|
+
for (const c of list) target.res.headers.append('Set-Cookie', c) // h3 v2
|
|
158
|
+
return target
|
|
159
|
+
}
|
|
160
|
+
if (typeof target.append === 'function' && target.res) {
|
|
161
|
+
for (const c of list) target.append('Set-Cookie', c) // Koa ctx
|
|
162
|
+
return target
|
|
163
|
+
}
|
|
164
|
+
// Node res, Express res, Fastify reply (getHeader/header or setHeader).
|
|
165
|
+
const get = target.getHeader?.bind(target)
|
|
166
|
+
const existing = get ? get('set-cookie') : undefined
|
|
167
|
+
const merged = [...(existing == null ? [] : Array.isArray(existing) ? existing : [String(existing)]), ...list]
|
|
168
|
+
if (typeof target.setHeader === 'function') target.setHeader('Set-Cookie', merged)
|
|
169
|
+
else if (typeof target.header === 'function') target.header('set-cookie', merged)
|
|
170
|
+
else throw new TypeError('applyCookies: unrecognised response object')
|
|
171
|
+
return target
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A Headers object holding the given Set-Cookie values. */
|
|
175
|
+
export function cookieHeaders(cookies, init) {
|
|
176
|
+
const headers = new Headers(init)
|
|
177
|
+
for (const c of cookies ?? []) headers.append('Set-Cookie', c)
|
|
178
|
+
return headers
|
|
179
|
+
}
|
package/src/index.d.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
+
export * from './web.js'
|
|
1
2
|
export * from './password/hashPassword.js'
|
|
2
3
|
export * from './token/signToken.js'
|
|
3
4
|
export * from './cookies/authCookies.js'
|
|
4
5
|
export * from './rateLimiter/loginRateLimiter.js'
|
|
5
|
-
export * from './generators/AuthGenerator.js'
|
|
6
|
+
export * from './generators/AuthGenerator.js'
|
|
7
|
+
|
|
8
|
+
import type { VerifyResult } from './web.js'
|
|
9
|
+
/** The check @tylix/core's requireAuth runs: session JWTs (with the session guard) and legacy access tokens. */
|
|
10
|
+
export declare function verifyTylixAccessToken(token: string, secret: string | string[]): Promise<VerifyResult>
|
|
11
|
+
/** Registers (fn) or clears (null) the check that a token's session still exists. */
|
|
12
|
+
export declare function setSessionGuard(fn: ((claims: Record<string, any>) => boolean | Promise<boolean>) | null): void
|
|
13
|
+
export declare function getSessionGuard(): ((claims: Record<string, any>) => boolean | Promise<boolean>) | null
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
// Node entry: everything in "@tylix/auth/web", plus scrypt password
|
|
2
|
+
// hashing, the original Tylix token/cookie helpers and the make:auth
|
|
3
|
+
// generator.
|
|
4
|
+
export * from './web.js'
|
|
1
5
|
export * from './password/hashPassword.js'
|
|
2
6
|
export * from './token/signToken.js'
|
|
3
7
|
export * from './cookies/authCookies.js'
|
|
4
8
|
export * from './rateLimiter/loginRateLimiter.js'
|
|
9
|
+
export { verifyAccessToken as verifyTylixAccessToken, setSessionGuard, getSessionGuard } from './tylix/accessTokens.js'
|
|
5
10
|
export * from './generators/AuthGenerator.js'
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Auth, CurrentSession, ProtectRule, RouteOptions } from '../web.js'
|
|
2
|
+
type H3Event = any
|
|
3
|
+
export declare function h3AuthHandler(auth: Auth, options?: RouteOptions): (event: H3Event) => Promise<unknown>
|
|
4
|
+
export declare function h3AuthMiddleware(auth: Auth, options?: { protect?: ProtectRule; loginPath?: string }): (event: H3Event) => Promise<void>
|
|
5
|
+
export declare function requireH3Session(auth: Auth, event: H3Event, options?: { checkRevocation?: boolean }): Promise<CurrentSession>
|
|
6
|
+
export { applyCookies } from '../web.js'
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { applyCookies } from '../http/request.js'
|
|
2
|
+
import { handleAuthRoute, matchesProtected } from './routes.js'
|
|
3
|
+
import { safeRedirectPath } from '../http/origin.js'
|
|
4
|
+
|
|
5
|
+
// Nuxt / Nitro / h3. No import of h3 itself, so any h3 version works.
|
|
6
|
+
//
|
|
7
|
+
// // server/api/auth/[...].ts
|
|
8
|
+
// export default defineEventHandler(h3AuthHandler(auth))
|
|
9
|
+
//
|
|
10
|
+
// // server/middleware/auth.ts
|
|
11
|
+
// export default defineEventHandler(h3AuthMiddleware(auth))
|
|
12
|
+
// // then in any handler: event.context.auth (null for guests)
|
|
13
|
+
//
|
|
14
|
+
// // a protected handler
|
|
15
|
+
// const session = await requireH3Session(auth, event)
|
|
16
|
+
//
|
|
17
|
+
// // after checking a password in your login handler
|
|
18
|
+
// const { cookies } = await auth.signIn(event, user.id)
|
|
19
|
+
// applyCookies(event, cookies)
|
|
20
|
+
|
|
21
|
+
function httpError(statusCode, message) {
|
|
22
|
+
// h3's error handler reads statusCode/statusMessage from thrown errors.
|
|
23
|
+
return Object.assign(new Error(message), { statusCode, status: statusCode, statusMessage: message, data: { error: message } })
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function nodeRes(event) {
|
|
27
|
+
return event.node?.res ?? event.res
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function h3AuthHandler(auth, options = {}) {
|
|
31
|
+
return async function handler(event) {
|
|
32
|
+
const result = await handleAuthRoute(auth, event, options)
|
|
33
|
+
const res = nodeRes(event)
|
|
34
|
+
if (!result) throw httpError(404, 'Not found.')
|
|
35
|
+
applyCookies(event, result.cookies)
|
|
36
|
+
if (res?.setHeader) {
|
|
37
|
+
res.statusCode = result.status
|
|
38
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
39
|
+
} else if (res) {
|
|
40
|
+
res.status = result.status // h3 v2
|
|
41
|
+
res.headers?.set?.('Cache-Control', 'no-store')
|
|
42
|
+
}
|
|
43
|
+
return result.body ?? null
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Sets event.context.auth to the session (or null) for every request. */
|
|
48
|
+
export function h3AuthMiddleware(auth, { protect, loginPath = '/login' } = {}) {
|
|
49
|
+
return async function middleware(event) {
|
|
50
|
+
event.context ??= {}
|
|
51
|
+
event.context.auth = await auth.getSession(event)
|
|
52
|
+
const path = (event.path ?? event.node?.req?.url ?? '/').split('?')[0]
|
|
53
|
+
if (protect && !event.context.auth && matchesProtected(protect, path)) {
|
|
54
|
+
const res = nodeRes(event)
|
|
55
|
+
const location = `${loginPath}?next=${encodeURIComponent(safeRedirectPath(event.path ?? event.node?.req?.url ?? '/'))}`
|
|
56
|
+
res.statusCode = 307
|
|
57
|
+
res.setHeader('Location', location)
|
|
58
|
+
res.end()
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The session, or throws a 401 that h3 turns into a JSON error. */
|
|
64
|
+
export async function requireH3Session(auth, event, options) {
|
|
65
|
+
const session = event.context?.auth ?? (await auth.getSession(event, options))
|
|
66
|
+
if (!session) throw httpError(401, 'Not authenticated.')
|
|
67
|
+
return session
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export { applyCookies } from '../http/request.js'
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Auth, RouteOptions } from '../web.js'
|
|
2
|
+
type Middleware = (c: any, next: () => Promise<void>) => Promise<Response | void>
|
|
3
|
+
export declare function honoAuth(auth: Auth, options?: { checkRevocation?: boolean }): Middleware
|
|
4
|
+
export declare function honoRequireAuth(auth: Auth, options?: { checkRevocation?: boolean }): Middleware
|
|
5
|
+
export declare function honoAuthRoutes(auth: Auth, options?: RouteOptions): (c: any) => Promise<Response>
|
|
6
|
+
export { applyCookies } from '../web.js'
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { handleAuthRoute, toResponse } from './routes.js'
|
|
2
|
+
|
|
3
|
+
// Hono (Node, Bun, Deno, Workers).
|
|
4
|
+
//
|
|
5
|
+
// app.use('*', honoAuth(auth)) // c.get('auth'): session or null
|
|
6
|
+
// app.all('/api/auth/*', honoAuthRoutes(auth))
|
|
7
|
+
// app.get('/api/me', honoRequireAuth(auth), (c) => c.json({ id: c.get('auth').userId }))
|
|
8
|
+
//
|
|
9
|
+
// // in your login route, after checking the password
|
|
10
|
+
// const { cookies } = await auth.signIn(c, user.id)
|
|
11
|
+
// applyCookies(c, cookies)
|
|
12
|
+
|
|
13
|
+
export function honoAuth(auth, options) {
|
|
14
|
+
return async (c, next) => {
|
|
15
|
+
c.set('auth', await auth.getSession(c.req.raw, options))
|
|
16
|
+
await next()
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function honoRequireAuth(auth, options) {
|
|
21
|
+
return async (c, next) => {
|
|
22
|
+
const session = c.get?.('auth') ?? (await auth.getSession(c.req.raw, options))
|
|
23
|
+
if (!session) return c.json({ error: 'Not authenticated.' }, 401)
|
|
24
|
+
c.set('auth', session)
|
|
25
|
+
await next()
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function honoAuthRoutes(auth, options) {
|
|
30
|
+
return async (c) => {
|
|
31
|
+
const result = await handleAuthRoute(auth, c.req.raw, options)
|
|
32
|
+
return toResponse(result ?? { status: 404, body: { error: 'Not found.' } })
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export { applyCookies } from '../http/request.js'
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Auth, CurrentSession, ProtectRule, RouteOptions } from '../web.js'
|
|
2
|
+
export declare function nextAuthHandlers(auth: Auth, options?: RouteOptions): {
|
|
3
|
+
GET: (request: Request) => Promise<Response>
|
|
4
|
+
POST: (request: Request) => Promise<Response>
|
|
5
|
+
DELETE: (request: Request) => Promise<Response>
|
|
6
|
+
}
|
|
7
|
+
export declare function nextMiddleware(
|
|
8
|
+
auth: Auth,
|
|
9
|
+
options?: { protect?: ProtectRule; guestOnly?: ProtectRule; loginPath?: string; homePath?: string },
|
|
10
|
+
): (request: Request) => Promise<Response | undefined>
|
|
11
|
+
export declare function withNextSession<C extends object = {}>(
|
|
12
|
+
auth: Auth,
|
|
13
|
+
handler: (request: Request, context: C & { session: CurrentSession | null }) => Response | Promise<Response>,
|
|
14
|
+
options?: { optional?: boolean; checkRevocation?: boolean },
|
|
15
|
+
): (request: Request, context?: C) => Promise<Response>
|
|
16
|
+
export { jsonWithCookies, redirectWithCookies } from '../web.js'
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { createAuthHandler, guardRequest, withSession } from './web.js'
|
|
2
|
+
|
|
3
|
+
// Next.js (App Router, Node or Edge runtime).
|
|
4
|
+
//
|
|
5
|
+
// // app/api/auth/[...auth]/route.js
|
|
6
|
+
// export const { GET, POST, DELETE } = nextAuthHandlers(auth)
|
|
7
|
+
//
|
|
8
|
+
// // middleware.js
|
|
9
|
+
// export default nextMiddleware(auth, { protect: ['/dashboard'], loginPath: '/login' })
|
|
10
|
+
//
|
|
11
|
+
// // a Server Component / Server Action / route handler
|
|
12
|
+
// const session = await auth.getSession(await headers())
|
|
13
|
+
|
|
14
|
+
export function nextAuthHandlers(auth, options) {
|
|
15
|
+
const handler = createAuthHandler(auth, options)
|
|
16
|
+
return { GET: handler, POST: handler, DELETE: handler }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Edge middleware: redirects guests away from protected paths. Returns
|
|
21
|
+
* undefined to let everything else through (Next's NextResponse.next()).
|
|
22
|
+
* Token checks are stateless here; route handlers and server components
|
|
23
|
+
* still call auth.getSession(), which checks revocation.
|
|
24
|
+
*/
|
|
25
|
+
export function nextMiddleware(auth, options = {}) {
|
|
26
|
+
return async function middleware(request) {
|
|
27
|
+
return (await guardRequest(auth, request, options)) ?? undefined
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Route handler that requires a signed-in user: (request, { params, session }) => Response. */
|
|
32
|
+
export function withNextSession(auth, handler, options) {
|
|
33
|
+
return withSession(auth, handler, options)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export { jsonWithCookies, redirectWithCookies } from './web.js'
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Auth, RouteOptions } from '../web.js'
|
|
2
|
+
export declare function expressAuth(auth: Auth, options?: RouteOptions): (req: any, res: any, next: (error?: unknown) => void) => Promise<void>
|
|
3
|
+
export declare function requireExpressAuth(): (req: any, res: any, next: () => void) => void
|
|
4
|
+
export declare function fastifyAuth(app: any, auth: Auth, options?: RouteOptions): void
|
|
5
|
+
export declare function requireFastifyAuth(): (request: any, reply: any) => Promise<unknown>
|
|
6
|
+
export declare function koaAuth(auth: Auth, options?: RouteOptions): (ctx: any, next: () => Promise<unknown>) => Promise<void>
|
|
7
|
+
export { applyCookies } from '../web.js'
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { applyCookies } from '../http/request.js'
|
|
2
|
+
import { handleAuthRoute } from './routes.js'
|
|
3
|
+
|
|
4
|
+
// Express / Connect / plain node:http, Fastify and Koa.
|
|
5
|
+
//
|
|
6
|
+
// Express:
|
|
7
|
+
// app.use(expressAuth(auth)) // req.auth: session or null; serves /api/auth/*
|
|
8
|
+
// app.get('/api/me', requireExpressAuth(), (req, res) => res.json({ id: req.auth.userId }))
|
|
9
|
+
// // login: const { cookies } = await auth.signIn(req, user.id); applyCookies(res, cookies)
|
|
10
|
+
//
|
|
11
|
+
// Fastify:
|
|
12
|
+
// fastifyAuth(app, auth) // request.auth + /api/auth/* routes
|
|
13
|
+
//
|
|
14
|
+
// Koa:
|
|
15
|
+
// app.use(koaAuth(auth)) // ctx.state.auth + /api/auth/* routes
|
|
16
|
+
|
|
17
|
+
function send(res, { status, body, cookies }) {
|
|
18
|
+
applyCookies(res, cookies)
|
|
19
|
+
res.statusCode = status
|
|
20
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
21
|
+
if (body == null) return res.end()
|
|
22
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8')
|
|
23
|
+
res.end(JSON.stringify(body))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function expressAuth(auth, options = {}) {
|
|
27
|
+
return async function authMiddleware(req, res, next) {
|
|
28
|
+
try {
|
|
29
|
+
const result = await handleAuthRoute(auth, req, options)
|
|
30
|
+
if (result) return send(res, result)
|
|
31
|
+
req.auth = await auth.getSession(req)
|
|
32
|
+
next()
|
|
33
|
+
} catch (error) {
|
|
34
|
+
next(error)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 401s requests without a session. Use after expressAuth(). */
|
|
40
|
+
export function requireExpressAuth() {
|
|
41
|
+
return function requireAuth(req, res, next) {
|
|
42
|
+
if (req.auth) return next()
|
|
43
|
+
send(res, { status: 401, body: { error: 'Not authenticated.' }, cookies: [] })
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function fastifyAuth(app, auth, options = {}) {
|
|
48
|
+
const basePath = (options.basePath ?? '/api/auth').replace(/\/+$/, '')
|
|
49
|
+
app.decorateRequest?.('auth', null)
|
|
50
|
+
app.addHook('preHandler', async (request) => {
|
|
51
|
+
request.auth = await auth.getSession(request)
|
|
52
|
+
})
|
|
53
|
+
app.route({
|
|
54
|
+
method: ['GET', 'POST', 'DELETE'],
|
|
55
|
+
url: `${basePath}/*`,
|
|
56
|
+
handler: async (request, reply) => {
|
|
57
|
+
const result = (await handleAuthRoute(auth, request, options)) ?? { status: 404, body: { error: 'Not found.' }, cookies: [] }
|
|
58
|
+
applyCookies(reply, result.cookies)
|
|
59
|
+
reply.header('Cache-Control', 'no-store')
|
|
60
|
+
reply.code(result.status)
|
|
61
|
+
return result.body == null ? reply.send() : reply.send(result.body)
|
|
62
|
+
},
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function requireFastifyAuth() {
|
|
67
|
+
return async (request, reply) => {
|
|
68
|
+
if (!request.auth) return reply.code(401).send({ error: 'Not authenticated.' })
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function koaAuth(auth, options = {}) {
|
|
73
|
+
return async function authMiddleware(ctx, next) {
|
|
74
|
+
const result = await handleAuthRoute(auth, ctx, options)
|
|
75
|
+
if (result) {
|
|
76
|
+
applyCookies(ctx, result.cookies)
|
|
77
|
+
ctx.set('Cache-Control', 'no-store')
|
|
78
|
+
ctx.status = result.status
|
|
79
|
+
if (result.body != null) ctx.body = result.body
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
ctx.state.auth = await auth.getSession(ctx)
|
|
83
|
+
await next()
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export { applyCookies } from '../http/request.js'
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { getMethod, getPathname } from '../http/request.js'
|
|
2
|
+
|
|
3
|
+
// The session endpoints every app needs, independent of any framework.
|
|
4
|
+
// Mounted under basePath (default /api/auth):
|
|
5
|
+
//
|
|
6
|
+
// POST /refresh rotate the refresh token, new access token
|
|
7
|
+
// POST /logout end this session
|
|
8
|
+
// POST /logout-all end every session of this user
|
|
9
|
+
// GET /session who is signed in (401 if nobody)
|
|
10
|
+
// GET /sessions this user's active sessions ("devices")
|
|
11
|
+
// DELETE /sessions/:id end one of them
|
|
12
|
+
//
|
|
13
|
+
// Each adapter turns the { status, body, cookies } result into its own
|
|
14
|
+
// response type. Login and registration stay in your code: verify the
|
|
15
|
+
// password your way, then call auth.signIn(request, userId).
|
|
16
|
+
|
|
17
|
+
const NO_SESSION = { status: 401, body: { error: 'Not authenticated.' }, cookies: [] }
|
|
18
|
+
|
|
19
|
+
export async function handleAuthRoute(auth, request, { basePath = '/api/auth', user } = {}) {
|
|
20
|
+
const pathname = getPathname(request)
|
|
21
|
+
const base = basePath.replace(/\/+$/, '')
|
|
22
|
+
if (pathname !== base && !pathname.startsWith(`${base}/`)) return null
|
|
23
|
+
const route = pathname.slice(base.length) || '/'
|
|
24
|
+
const method = getMethod(request)
|
|
25
|
+
|
|
26
|
+
if (route === '/refresh' && method === 'POST') {
|
|
27
|
+
const result = await auth.refresh(request)
|
|
28
|
+
if (!result.ok) {
|
|
29
|
+
const status = result.reason === 'cross-site' ? 403 : 401
|
|
30
|
+
return { status, body: { error: status === 403 ? 'Cross-site request blocked.' : 'Session expired. Please sign in again.', reason: result.reason }, cookies: result.cookies }
|
|
31
|
+
}
|
|
32
|
+
return { status: 200, body: { ok: true, session: result.session }, cookies: result.cookies }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (route === '/logout' && method === 'POST') {
|
|
36
|
+
if (auth.isCrossSite(request)) return { status: 403, body: { error: 'Cross-site request blocked.' }, cookies: [] }
|
|
37
|
+
const result = await auth.signOut(request)
|
|
38
|
+
return { status: 204, body: null, cookies: result.cookies }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (route === '/session' && method === 'GET') {
|
|
42
|
+
const session = await auth.getSession(request)
|
|
43
|
+
if (!session) return NO_SESSION
|
|
44
|
+
const body = { userId: session.userId, session: session.session }
|
|
45
|
+
if (typeof user === 'function') body.user = await user(session.userId, session)
|
|
46
|
+
return { status: 200, body, cookies: [] }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (route === '/sessions' && method === 'GET') {
|
|
50
|
+
const session = await auth.getSession(request)
|
|
51
|
+
if (!session) return NO_SESSION
|
|
52
|
+
return { status: 200, body: { sessions: await auth.listSessions(session.userId, { currentSessionId: session.sessionId }) }, cookies: [] }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const one = /^\/sessions\/([A-Za-z0-9_-]{22})$/.exec(route)
|
|
56
|
+
if (one && method === 'DELETE') {
|
|
57
|
+
const session = await auth.getSession(request)
|
|
58
|
+
if (!session) return NO_SESSION
|
|
59
|
+
// Only the user's own sessions: an unknown id and someone else's id
|
|
60
|
+
// get the same answer.
|
|
61
|
+
const owned = (await auth.listSessions(session.userId)).some((s) => s.id === one[1])
|
|
62
|
+
if (!owned) return { status: 404, body: { error: 'Session not found.' }, cookies: [] }
|
|
63
|
+
await auth.revokeSession(one[1])
|
|
64
|
+
return { status: 204, body: null, cookies: one[1] === session.sessionId ? auth.clearCookies(request) : [] }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (route === '/logout-all' && method === 'POST') {
|
|
68
|
+
const session = await auth.getSession(request)
|
|
69
|
+
if (!session) return NO_SESSION
|
|
70
|
+
await auth.revokeAllSessions(session.userId)
|
|
71
|
+
return { status: 204, body: null, cookies: auth.clearCookies(request) }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return { status: 404, body: { error: 'Not found.' }, cookies: [] }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Turns a route result into a Web Response. */
|
|
78
|
+
export function toResponse({ status, body, cookies }) {
|
|
79
|
+
const headers = new Headers({ 'Cache-Control': 'no-store' })
|
|
80
|
+
for (const c of cookies ?? []) headers.append('Set-Cookie', c)
|
|
81
|
+
if (body == null) return new Response(null, { status, headers })
|
|
82
|
+
headers.set('Content-Type', 'application/json; charset=utf-8')
|
|
83
|
+
return new Response(JSON.stringify(body), { status, headers })
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Is this path protected? `protect` is a list of prefixes, a RegExp or a function. */
|
|
87
|
+
export function matchesProtected(protect, pathname) {
|
|
88
|
+
if (!protect) return false
|
|
89
|
+
if (typeof protect === 'function') return Boolean(protect(pathname))
|
|
90
|
+
if (protect instanceof RegExp) return protect.test(pathname)
|
|
91
|
+
return protect.some((prefix) => pathname === prefix || pathname.startsWith(prefix.endsWith('/') ? prefix : `${prefix}/`))
|
|
92
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Auth, ProtectRule, RouteOptions } from '../web.js'
|
|
2
|
+
export declare function sveltekitHandle(
|
|
3
|
+
auth: Auth,
|
|
4
|
+
options?: RouteOptions & { protect?: ProtectRule; loginPath?: string },
|
|
5
|
+
): (input: { event: any; resolve: (event: any) => Response | Promise<Response> }) => Promise<Response>
|