@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.
- 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,52 @@
|
|
|
1
|
+
import { handleAuthRoute, matchesProtected, toResponse } from './routes.js'
|
|
2
|
+
import { safeRedirectPath } from '../http/origin.js'
|
|
3
|
+
|
|
4
|
+
// SvelteKit.
|
|
5
|
+
//
|
|
6
|
+
// // src/hooks.server.js
|
|
7
|
+
// export const handle = sveltekitHandle(auth, { protect: ['/dashboard'] })
|
|
8
|
+
//
|
|
9
|
+
// Then, in load functions and actions:
|
|
10
|
+
// event.locals.auth the session, or null
|
|
11
|
+
// await event.locals.signIn(userId) after checking the password
|
|
12
|
+
// await event.locals.signOut()
|
|
13
|
+
// The cookies these set are added to the response automatically.
|
|
14
|
+
|
|
15
|
+
export function sveltekitHandle(auth, { basePath = '/api/auth', protect, loginPath = '/login', user } = {}) {
|
|
16
|
+
return async function handle({ event, resolve }) {
|
|
17
|
+
const routed = await handleAuthRoute(auth, event.request, { basePath, user })
|
|
18
|
+
if (routed) return toResponse(routed)
|
|
19
|
+
|
|
20
|
+
const pending = []
|
|
21
|
+
event.locals.auth = await auth.getSession(event.request)
|
|
22
|
+
event.locals.signIn = async (userId, options) => {
|
|
23
|
+
const result = await auth.signIn(event.request, userId, options)
|
|
24
|
+
pending.push(...result.cookies)
|
|
25
|
+
event.locals.auth = { userId: result.session.userId, sessionId: result.session.id, session: result.session }
|
|
26
|
+
return result
|
|
27
|
+
}
|
|
28
|
+
event.locals.signOut = async () => {
|
|
29
|
+
const result = await auth.signOut(event.request)
|
|
30
|
+
pending.push(...result.cookies)
|
|
31
|
+
event.locals.auth = null
|
|
32
|
+
return result
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (!event.locals.auth && matchesProtected(protect, event.url.pathname)) {
|
|
36
|
+
const next = safeRedirectPath(event.url.pathname + event.url.search)
|
|
37
|
+
return new Response(null, { status: 303, headers: { Location: `${loginPath}?next=${encodeURIComponent(next)}` } })
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const response = await resolve(event)
|
|
41
|
+
if (pending.length === 0) return response
|
|
42
|
+
try {
|
|
43
|
+
for (const c of pending) response.headers.append('Set-Cookie', c)
|
|
44
|
+
return response
|
|
45
|
+
} catch {
|
|
46
|
+
// Immutable headers (a fetched Response passed through): copy it.
|
|
47
|
+
const copy = new Response(response.body, response)
|
|
48
|
+
for (const c of pending) copy.headers.append('Set-Cookie', c)
|
|
49
|
+
return copy
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { safeRedirectPath } from '../http/origin.js'
|
|
2
|
+
import { getPathname, unwrapRequest } from '../http/request.js'
|
|
3
|
+
import { handleAuthRoute, matchesProtected, toResponse } from './routes.js'
|
|
4
|
+
|
|
5
|
+
// Web-standard (Request -> Response) integration. Works as-is with Remix,
|
|
6
|
+
// React Router, Astro, SolidStart, Bun.serve, Deno.serve, Cloudflare
|
|
7
|
+
// Workers and Next.js route handlers.
|
|
8
|
+
|
|
9
|
+
/** A fetch-style handler for the session endpoints under basePath. */
|
|
10
|
+
export function createAuthHandler(auth, options = {}) {
|
|
11
|
+
return async function handler(request) {
|
|
12
|
+
const result = await handleAuthRoute(auth, request, options)
|
|
13
|
+
return toResponse(result ?? { status: 404, body: { error: 'Not found.' } })
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** JSON Response carrying the Set-Cookie headers from signIn/signOut/refresh. */
|
|
18
|
+
export function jsonWithCookies(body, { status = 200, cookies = [], headers } = {}) {
|
|
19
|
+
const out = new Headers(headers)
|
|
20
|
+
out.set('Content-Type', 'application/json; charset=utf-8')
|
|
21
|
+
out.set('Cache-Control', 'no-store')
|
|
22
|
+
for (const c of cookies) out.append('Set-Cookie', c)
|
|
23
|
+
return new Response(JSON.stringify(body), { status, headers: out })
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A redirect Response carrying Set-Cookie headers. */
|
|
27
|
+
export function redirectWithCookies(location, { status = 303, cookies = [] } = {}) {
|
|
28
|
+
const headers = new Headers({ Location: location, 'Cache-Control': 'no-store' })
|
|
29
|
+
for (const c of cookies) headers.append('Set-Cookie', c)
|
|
30
|
+
return new Response(null, { status, headers })
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Wraps a Request -> Response handler so it only runs for a signed-in
|
|
35
|
+
* user; the session is passed as the second argument's `session`.
|
|
36
|
+
*/
|
|
37
|
+
export function withSession(auth, handler, { optional = false, checkRevocation } = {}) {
|
|
38
|
+
return async (request, context = {}) => {
|
|
39
|
+
const session = await auth.getSession(request, { checkRevocation })
|
|
40
|
+
if (!session && !optional) return jsonWithCookies({ error: 'Not authenticated.' }, { status: 401 })
|
|
41
|
+
return handler(request, { ...context, session })
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* For middleware that runs before pages: sends guests on protected paths
|
|
47
|
+
* to the login page (with ?next=). Stateless (no session store lookup),
|
|
48
|
+
* so it runs on the edge. Resolves a redirect Response, or null to let
|
|
49
|
+
* the request continue.
|
|
50
|
+
*/
|
|
51
|
+
export async function guardRequest(auth, request, { protect, loginPath = '/login', guestOnly, homePath = '/' } = {}) {
|
|
52
|
+
const pathname = getPathname(request)
|
|
53
|
+
const needsUser = matchesProtected(protect, pathname)
|
|
54
|
+
const needsGuest = matchesProtected(guestOnly, pathname)
|
|
55
|
+
if (!needsUser && !needsGuest) return null
|
|
56
|
+
|
|
57
|
+
const session = await auth.getSession(request, { checkRevocation: false })
|
|
58
|
+
const raw = unwrapRequest(request)
|
|
59
|
+
const base = typeof raw.url === 'string' && /^https?:/.test(raw.url) ? raw.url : 'http://localhost'
|
|
60
|
+
|
|
61
|
+
if (needsUser && !session) {
|
|
62
|
+
const url = new URL(raw.url ?? '/', 'http://localhost')
|
|
63
|
+
const target = new URL(loginPath, base)
|
|
64
|
+
target.searchParams.set('next', safeRedirectPath(url.pathname + url.search))
|
|
65
|
+
return Response.redirect(target.toString(), 307)
|
|
66
|
+
}
|
|
67
|
+
if (needsGuest && session) return Response.redirect(new URL(homePath, base).toString(), 307)
|
|
68
|
+
return null
|
|
69
|
+
}
|
package/src/mfa/totp.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { hmacSign, importHmacKey, randomBytes, sha256Hex, timingSafeEqual } from '../core/crypto.js'
|
|
2
|
+
|
|
3
|
+
// Two-factor authentication with authenticator apps (TOTP, RFC 6238) and
|
|
4
|
+
// one-time recovery codes. Store the TOTP secret encrypted (auth.sealer)
|
|
5
|
+
// and keep the last accepted time step per user: verifyTotp refuses a
|
|
6
|
+
// code from that step or earlier, so an intercepted code can't be replayed.
|
|
7
|
+
|
|
8
|
+
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
|
9
|
+
|
|
10
|
+
export function base32Encode(bytes) {
|
|
11
|
+
let bits = 0
|
|
12
|
+
let value = 0
|
|
13
|
+
let out = ''
|
|
14
|
+
for (const byte of bytes) {
|
|
15
|
+
value = (value << 8) | byte
|
|
16
|
+
bits += 8
|
|
17
|
+
while (bits >= 5) {
|
|
18
|
+
out += BASE32[(value >>> (bits - 5)) & 31]
|
|
19
|
+
bits -= 5
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31]
|
|
23
|
+
return out
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function base32Decode(input) {
|
|
27
|
+
const clean = String(input).toUpperCase().replace(/[\s=-]/g, '')
|
|
28
|
+
let bits = 0
|
|
29
|
+
let value = 0
|
|
30
|
+
const out = []
|
|
31
|
+
for (const char of clean) {
|
|
32
|
+
const index = BASE32.indexOf(char)
|
|
33
|
+
if (index === -1) throw new TypeError('Invalid base32')
|
|
34
|
+
value = (value << 5) | index
|
|
35
|
+
bits += 5
|
|
36
|
+
if (bits >= 8) {
|
|
37
|
+
out.push((value >>> (bits - 8)) & 255)
|
|
38
|
+
bits -= 8
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return new Uint8Array(out)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A new random TOTP secret (base32, 160 bits by default as RFC 4226 recommends). */
|
|
45
|
+
export function generateTotpSecret(bytes = 20) {
|
|
46
|
+
if (bytes < 16) throw new RangeError('TOTP secrets need at least 128 bits')
|
|
47
|
+
return base32Encode(randomBytes(bytes))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The otpauth:// URI to show as a QR code. */
|
|
51
|
+
export function totpUri({ secret, issuer, account, digits = 6, period = 30, algorithm = 'SHA1' }) {
|
|
52
|
+
if (!secret || !issuer || !account) throw new TypeError('totpUri needs secret, issuer and account')
|
|
53
|
+
const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`
|
|
54
|
+
const params = new URLSearchParams({ secret, issuer, algorithm, digits: String(digits), period: String(period) })
|
|
55
|
+
return `otpauth://totp/${label}?${params}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const HASHES = { SHA1: 'SHA-1', SHA256: 'SHA-256', SHA512: 'SHA-512' }
|
|
59
|
+
|
|
60
|
+
async function hotp(keyBytes, counter, digits, algorithm) {
|
|
61
|
+
const key = await importHmacKey(keyBytes, HASHES[algorithm] ?? 'SHA-1')
|
|
62
|
+
const message = new Uint8Array(8)
|
|
63
|
+
let c = BigInt(counter)
|
|
64
|
+
for (let i = 7; i >= 0; i--) {
|
|
65
|
+
message[i] = Number(c & 0xffn)
|
|
66
|
+
c >>= 8n
|
|
67
|
+
}
|
|
68
|
+
const mac = await hmacSign(key, message)
|
|
69
|
+
const offset = mac[mac.length - 1] & 0x0f
|
|
70
|
+
const binary = ((mac[offset] & 0x7f) << 24) | (mac[offset + 1] << 16) | (mac[offset + 2] << 8) | mac[offset + 3]
|
|
71
|
+
return String(binary % 10 ** digits).padStart(digits, '0')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function generateTotp(secret, { time = Date.now(), digits = 6, period = 30, algorithm = 'SHA1' } = {}) {
|
|
75
|
+
return hotp(base32Decode(secret), Math.floor(time / 1000 / period), digits, algorithm)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Checks a code. Resolves { valid, step }: store `step` as the user's
|
|
80
|
+
* last used step and pass it back as `lastUsedStep` next time.
|
|
81
|
+
* window how many periods either side to accept (default 1 = +-30s)
|
|
82
|
+
*/
|
|
83
|
+
export async function verifyTotp(code, secret, { time = Date.now(), digits = 6, period = 30, window = 1, algorithm = 'SHA1', lastUsedStep = null } = {}) {
|
|
84
|
+
const normalized = String(code ?? '').replace(/\s+/g, '')
|
|
85
|
+
if (!new RegExp(`^\\d{${digits}}$`).test(normalized)) return { valid: false, step: null }
|
|
86
|
+
let keyBytes
|
|
87
|
+
try {
|
|
88
|
+
keyBytes = base32Decode(secret)
|
|
89
|
+
} catch {
|
|
90
|
+
return { valid: false, step: null }
|
|
91
|
+
}
|
|
92
|
+
const current = Math.floor(time / 1000 / period)
|
|
93
|
+
let matched = null
|
|
94
|
+
// Every candidate is computed and compared, so timing doesn't reveal
|
|
95
|
+
// which step matched.
|
|
96
|
+
for (let offset = -window; offset <= window; offset++) {
|
|
97
|
+
const step = current + offset
|
|
98
|
+
const expected = await hotp(keyBytes, step, digits, algorithm)
|
|
99
|
+
if (timingSafeEqual(expected, normalized) && matched === null) matched = step
|
|
100
|
+
}
|
|
101
|
+
if (matched === null) return { valid: false, step: null }
|
|
102
|
+
if (lastUsedStep != null && matched <= Number(lastUsedStep)) return { valid: false, step: null, replay: true }
|
|
103
|
+
return { valid: true, step: matched }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// --- recovery codes ----------------------------------------------------
|
|
107
|
+
|
|
108
|
+
// No 0/O/1/I/L: codes are read off paper and typed by hand.
|
|
109
|
+
const RECOVERY_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'
|
|
110
|
+
|
|
111
|
+
function normalizeRecoveryCode(code) {
|
|
112
|
+
return String(code ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '')
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Fresh recovery codes. Show `codes` to the user once; store only `hashes`.
|
|
117
|
+
* Each code has ~50 bits of entropy (10 characters from 31).
|
|
118
|
+
*/
|
|
119
|
+
export async function generateRecoveryCodes(count = 10) {
|
|
120
|
+
const codes = []
|
|
121
|
+
// Rejection sampling: bytes >= 248 (31 * 8) are skipped, so every
|
|
122
|
+
// character is exactly equally likely.
|
|
123
|
+
const limit = RECOVERY_ALPHABET.length * Math.floor(256 / RECOVERY_ALPHABET.length)
|
|
124
|
+
for (let i = 0; i < count; i++) {
|
|
125
|
+
let raw = ''
|
|
126
|
+
while (raw.length < 10) {
|
|
127
|
+
for (const b of randomBytes(16)) {
|
|
128
|
+
if (b < limit && raw.length < 10) raw += RECOVERY_ALPHABET[b % RECOVERY_ALPHABET.length]
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
codes.push(`${raw.slice(0, 5)}-${raw.slice(5)}`)
|
|
132
|
+
}
|
|
133
|
+
const hashes = await Promise.all(codes.map((c) => sha256Hex(`tylix-recovery:${normalizeRecoveryCode(c)}`)))
|
|
134
|
+
return { codes, hashes }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Index of the stored hash this code matches, or -1. Remove that hash
|
|
139
|
+
* afterwards: every recovery code works once.
|
|
140
|
+
*/
|
|
141
|
+
export async function verifyRecoveryCode(code, hashes) {
|
|
142
|
+
const normalized = normalizeRecoveryCode(code)
|
|
143
|
+
if (normalized.length !== 10 || !Array.isArray(hashes)) return -1
|
|
144
|
+
const hash = await sha256Hex(`tylix-recovery:${normalized}`)
|
|
145
|
+
let found = -1
|
|
146
|
+
hashes.forEach((stored, index) => {
|
|
147
|
+
if (typeof stored === 'string' && timingSafeEqual(stored, hash) && found === -1) found = index
|
|
148
|
+
})
|
|
149
|
+
return found
|
|
150
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { base64urlEncode, randomToken, sha256, timingSafeEqual } from '../core/crypto.js'
|
|
2
|
+
import { serializeCookie, expireCookie } from '../http/cookies.js'
|
|
3
|
+
import { getCookie, getSearchParam, isSecureRequest } from '../http/request.js'
|
|
4
|
+
import { safeRedirectPath } from '../http/origin.js'
|
|
5
|
+
import { isProduction } from '../core/keys.js'
|
|
6
|
+
|
|
7
|
+
// "Sign in with GitHub / Google / ..." (OAuth 2.0 authorization code flow)
|
|
8
|
+
// done safely:
|
|
9
|
+
// - PKCE (S256) on every flow, even for confidential clients
|
|
10
|
+
// - a random `state`, kept in an encrypted, short-lived, httpOnly cookie
|
|
11
|
+
// and compared in constant time on the way back (stops login CSRF)
|
|
12
|
+
// - a random `nonce` for OpenID providers
|
|
13
|
+
// - the profile comes from the provider's API over TLS, server to server
|
|
14
|
+
// - an email is only marked verified when the provider says so: link
|
|
15
|
+
// accounts by email ONLY when profile.emailVerified is true
|
|
16
|
+
// - returnTo is restricted to same-site paths (no open redirects)
|
|
17
|
+
|
|
18
|
+
export class OAuthError extends Error {
|
|
19
|
+
constructor(code, message) {
|
|
20
|
+
super(message)
|
|
21
|
+
this.name = 'OAuthError'
|
|
22
|
+
this.code = code
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const STATE_COOKIE = 'auth.oauth'
|
|
27
|
+
|
|
28
|
+
export function createOAuth({ sealer, trustProxy = false, cookieName = STATE_COOKIE, fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
29
|
+
if (!sealer) throw new TypeError('createOAuth needs a sealer (use auth.oauth, or createSealer({ secret })).')
|
|
30
|
+
|
|
31
|
+
const cookieFor = (request) => {
|
|
32
|
+
const secure = isProduction() || (request ? isSecureRequest(request, { trustProxy }) : false)
|
|
33
|
+
return { name: secure ? `__Host-${cookieName}` : cookieName, secure }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Begins a flow. Redirect to `url` and send `cookies` with that redirect. */
|
|
37
|
+
async function start(provider, request, { returnTo = '/', scopes, params = {} } = {}) {
|
|
38
|
+
const state = randomToken(32)
|
|
39
|
+
const verifier = randomToken(48)
|
|
40
|
+
const nonce = provider.oidc ? randomToken(24) : null
|
|
41
|
+
const challenge = base64urlEncode(await sha256(verifier))
|
|
42
|
+
|
|
43
|
+
const url = new URL(provider.authorizationUrl)
|
|
44
|
+
url.searchParams.set('response_type', 'code')
|
|
45
|
+
url.searchParams.set('client_id', provider.clientId)
|
|
46
|
+
url.searchParams.set('redirect_uri', provider.redirectUri)
|
|
47
|
+
url.searchParams.set('scope', (scopes ?? provider.scopes).join(' '))
|
|
48
|
+
url.searchParams.set('state', state)
|
|
49
|
+
url.searchParams.set('code_challenge', challenge)
|
|
50
|
+
url.searchParams.set('code_challenge_method', 'S256')
|
|
51
|
+
if (nonce) url.searchParams.set('nonce', nonce)
|
|
52
|
+
for (const [k, v] of Object.entries({ ...provider.authorizationParams, ...params })) url.searchParams.set(k, v)
|
|
53
|
+
|
|
54
|
+
const { name, secure } = cookieFor(request)
|
|
55
|
+
const sealed = await sealer.seal(
|
|
56
|
+
{ p: provider.id, s: state, v: verifier, n: nonce, r: safeRedirectPath(returnTo) },
|
|
57
|
+
{ purpose: 'oauth-state', expiresIn: 600 },
|
|
58
|
+
)
|
|
59
|
+
const cookie = serializeCookie(name, sealed, { secure, httpOnly: true, sameSite: 'lax', path: '/', maxAge: 600 })
|
|
60
|
+
return { url: url.toString(), cookies: [cookie] }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Finishes a flow on the redirect_uri route. Resolves
|
|
65
|
+
* { profile, tokens, returnTo, cookies } or throws OAuthError.
|
|
66
|
+
*/
|
|
67
|
+
async function callback(provider, request) {
|
|
68
|
+
const { name, secure } = cookieFor(request)
|
|
69
|
+
const clear = [expireCookie(name, { secure, httpOnly: true, sameSite: 'lax', path: '/' })]
|
|
70
|
+
const fail = (code, message) => {
|
|
71
|
+
const error = new OAuthError(code, message)
|
|
72
|
+
error.cookies = clear
|
|
73
|
+
throw error
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const providerError = getSearchParam(request, 'error')
|
|
77
|
+
if (providerError) fail('provider_error', `The provider refused the sign-in (${providerError}).`)
|
|
78
|
+
|
|
79
|
+
const code = getSearchParam(request, 'code')
|
|
80
|
+
const state = getSearchParam(request, 'state')
|
|
81
|
+
if (!code || !state) fail('missing_params', 'The sign-in response is incomplete.')
|
|
82
|
+
|
|
83
|
+
const stored = await sealer.unseal(getCookie(request, name), { purpose: 'oauth-state' })
|
|
84
|
+
if (!stored || stored.p !== provider.id || !timingSafeEqual(stored.s, state)) {
|
|
85
|
+
fail('state_mismatch', 'This sign-in link is invalid or has expired. Please try again.')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const body = new URLSearchParams({
|
|
89
|
+
grant_type: 'authorization_code',
|
|
90
|
+
code,
|
|
91
|
+
redirect_uri: provider.redirectUri,
|
|
92
|
+
code_verifier: stored.v,
|
|
93
|
+
client_id: provider.clientId,
|
|
94
|
+
})
|
|
95
|
+
const headers = { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }
|
|
96
|
+
if (provider.clientAuth === 'basic') {
|
|
97
|
+
headers.Authorization = `Basic ${btoa(`${encodeURIComponent(provider.clientId)}:${encodeURIComponent(provider.clientSecret)}`)}`
|
|
98
|
+
} else if (provider.clientSecret) {
|
|
99
|
+
body.set('client_secret', provider.clientSecret)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let tokens
|
|
103
|
+
try {
|
|
104
|
+
const response = await fetchImpl(provider.tokenUrl, { method: 'POST', headers, body, signal: AbortSignal.timeout(10_000) })
|
|
105
|
+
tokens = await response.json()
|
|
106
|
+
if (!response.ok || tokens.error || !tokens.access_token) {
|
|
107
|
+
fail('token_exchange_failed', `The provider did not issue a token${tokens?.error ? ` (${tokens.error})` : ''}.`)
|
|
108
|
+
}
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof OAuthError) throw error
|
|
111
|
+
fail('token_exchange_failed', 'Could not reach the sign-in provider.')
|
|
112
|
+
}
|
|
113
|
+
if (tokens.token_type && String(tokens.token_type).toLowerCase() !== 'bearer') fail('token_exchange_failed', 'Unexpected token type.')
|
|
114
|
+
|
|
115
|
+
const get = async (url) => {
|
|
116
|
+
const response = await fetchImpl(url, {
|
|
117
|
+
headers: { Authorization: `Bearer ${tokens.access_token}`, Accept: 'application/json', 'User-Agent': '@tylix/auth' },
|
|
118
|
+
signal: AbortSignal.timeout(10_000),
|
|
119
|
+
})
|
|
120
|
+
if (!response.ok) fail('profile_failed', 'Could not load your profile from the provider.')
|
|
121
|
+
return response.json()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let profile
|
|
125
|
+
try {
|
|
126
|
+
profile = await provider.profile({ get, tokens })
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof OAuthError) throw error
|
|
129
|
+
fail('profile_failed', 'Could not load your profile from the provider.')
|
|
130
|
+
}
|
|
131
|
+
if (!profile?.id) fail('profile_failed', 'The provider returned no account id.')
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
profile: { provider: provider.id, ...profile, id: String(profile.id), emailVerified: profile.emailVerified === true },
|
|
135
|
+
tokens,
|
|
136
|
+
returnTo: safeRedirectPath(stored.r),
|
|
137
|
+
cookies: clear,
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { start, callback }
|
|
142
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// OAuth provider presets. Each returns a plain object, so a provider that
|
|
2
|
+
// isn't listed is just `oauthProvider({ id, authorizationUrl, tokenUrl,
|
|
3
|
+
// scopes, profile })`.
|
|
4
|
+
//
|
|
5
|
+
// profile() must return { id, email, emailVerified, name, avatarUrl }.
|
|
6
|
+
// emailVerified is only true when the provider vouches for the address.
|
|
7
|
+
|
|
8
|
+
function required(name, options) {
|
|
9
|
+
for (const key of ['clientId', 'clientSecret', 'redirectUri']) {
|
|
10
|
+
if (!options[key]) throw new TypeError(`${name}: missing ${key}`)
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function oauthProvider(definition) {
|
|
15
|
+
for (const key of ['id', 'authorizationUrl', 'tokenUrl', 'clientId', 'redirectUri', 'profile']) {
|
|
16
|
+
if (!definition[key]) throw new TypeError(`oauthProvider: missing ${key}`)
|
|
17
|
+
}
|
|
18
|
+
return { scopes: [], authorizationParams: {}, clientAuth: 'post', oidc: false, ...definition }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function github(options) {
|
|
22
|
+
required('github', options)
|
|
23
|
+
return oauthProvider({
|
|
24
|
+
id: 'github',
|
|
25
|
+
authorizationUrl: 'https://github.com/login/oauth/authorize',
|
|
26
|
+
tokenUrl: 'https://github.com/login/oauth/access_token',
|
|
27
|
+
scopes: ['read:user', 'user:email'],
|
|
28
|
+
...options,
|
|
29
|
+
async profile({ get }) {
|
|
30
|
+
const user = await get('https://api.github.com/user')
|
|
31
|
+
// The public profile email may be unverified; the emails API says.
|
|
32
|
+
let email = null
|
|
33
|
+
let emailVerified = false
|
|
34
|
+
try {
|
|
35
|
+
const emails = await get('https://api.github.com/user/emails')
|
|
36
|
+
const primary = Array.isArray(emails) ? emails.find((e) => e.primary) : null
|
|
37
|
+
if (primary) {
|
|
38
|
+
email = primary.email
|
|
39
|
+
emailVerified = primary.verified === true
|
|
40
|
+
}
|
|
41
|
+
} catch {}
|
|
42
|
+
return { id: user.id, email, emailVerified, name: user.name ?? user.login, avatarUrl: user.avatar_url ?? null, username: user.login }
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function google(options) {
|
|
48
|
+
required('google', options)
|
|
49
|
+
return oauthProvider({
|
|
50
|
+
id: 'google',
|
|
51
|
+
oidc: true,
|
|
52
|
+
authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
|
53
|
+
tokenUrl: 'https://oauth2.googleapis.com/token',
|
|
54
|
+
scopes: ['openid', 'email', 'profile'],
|
|
55
|
+
authorizationParams: { prompt: 'select_account' },
|
|
56
|
+
...options,
|
|
57
|
+
async profile({ get }) {
|
|
58
|
+
const u = await get('https://openidconnect.googleapis.com/v1/userinfo')
|
|
59
|
+
return { id: u.sub, email: u.email ?? null, emailVerified: u.email_verified === true, name: u.name ?? null, avatarUrl: u.picture ?? null }
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function discord(options) {
|
|
65
|
+
required('discord', options)
|
|
66
|
+
return oauthProvider({
|
|
67
|
+
id: 'discord',
|
|
68
|
+
authorizationUrl: 'https://discord.com/oauth2/authorize',
|
|
69
|
+
tokenUrl: 'https://discord.com/api/oauth2/token',
|
|
70
|
+
scopes: ['identify', 'email'],
|
|
71
|
+
...options,
|
|
72
|
+
async profile({ get }) {
|
|
73
|
+
const u = await get('https://discord.com/api/users/@me')
|
|
74
|
+
const avatarUrl = u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png` : null
|
|
75
|
+
return { id: u.id, email: u.email ?? null, emailVerified: u.verified === true, name: u.global_name ?? u.username, avatarUrl, username: u.username }
|
|
76
|
+
},
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function gitlab({ baseUrl = 'https://gitlab.com', ...options }) {
|
|
81
|
+
required('gitlab', options)
|
|
82
|
+
return oauthProvider({
|
|
83
|
+
id: 'gitlab',
|
|
84
|
+
oidc: true,
|
|
85
|
+
authorizationUrl: `${baseUrl}/oauth/authorize`,
|
|
86
|
+
tokenUrl: `${baseUrl}/oauth/token`,
|
|
87
|
+
scopes: ['openid', 'email', 'profile'],
|
|
88
|
+
...options,
|
|
89
|
+
async profile({ get }) {
|
|
90
|
+
const u = await get(`${baseUrl}/oauth/userinfo`)
|
|
91
|
+
return { id: u.sub, email: u.email ?? null, emailVerified: u.email_verified === true, name: u.name ?? u.nickname, avatarUrl: u.picture ?? null }
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function microsoft({ tenant = 'common', ...options }) {
|
|
97
|
+
required('microsoft', options)
|
|
98
|
+
return oauthProvider({
|
|
99
|
+
id: 'microsoft',
|
|
100
|
+
oidc: true,
|
|
101
|
+
authorizationUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/authorize`,
|
|
102
|
+
tokenUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`,
|
|
103
|
+
scopes: ['openid', 'email', 'profile', 'User.Read'],
|
|
104
|
+
...options,
|
|
105
|
+
async profile({ get }) {
|
|
106
|
+
const u = await get('https://graph.microsoft.com/oidc/userinfo')
|
|
107
|
+
// Entra ID lets tenant admins set any email on an account without
|
|
108
|
+
// verifying it ("nOAuth"), so it is never treated as verified.
|
|
109
|
+
return { id: u.sub, email: u.email ?? null, emailVerified: false, name: u.name ?? null, avatarUrl: null }
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
}
|
|
@@ -1,2 +1,6 @@
|
|
|
1
|
+
export declare const MAX_PASSWORD_BYTES: number
|
|
1
2
|
export declare function hashPassword(plainPassword: string): Promise<string>
|
|
2
|
-
|
|
3
|
+
/** Pass null/undefined as the hash for unknown accounts: the same work is done, so timing reveals nothing. */
|
|
4
|
+
export declare function verifyPassword(plainPassword: string, storedHash: string | null | undefined): Promise<boolean>
|
|
5
|
+
/** True when the hash uses an old format or weaker parameters: store a fresh hash after login. */
|
|
6
|
+
export declare function needsRehash(storedHash: string): boolean
|