-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
init.ts
232 lines (213 loc) · 6.16 KB
/
init.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import * as jwt from "../jwt.js"
import { createCallbackUrl } from "./utils/callback-url.js"
import * as cookie from "./utils/cookie.js"
import { createCSRFToken } from "./actions/callback/oauth/csrf-token.js"
import { AdapterError, EventError } from "../errors.js"
import parseProviders from "./utils/providers.js"
import { setLogger, type LoggerInstance } from "./utils/logger.js"
import { merge } from "./utils/merge.js"
import type { InternalOptions, RequestInternal } from "../types.js"
import type { AuthConfig } from "../index.js"
interface InitParams {
url: URL
authOptions: AuthConfig
providerId?: string
action: InternalOptions["action"]
/** Callback URL value extracted from the incoming request. */
callbackUrl?: string
/** CSRF token value extracted from the incoming request. From body if POST, from query if GET */
csrfToken?: string
/** Is the incoming request a POST request? */
csrfDisabled: boolean
isPost: boolean
cookies: RequestInternal["cookies"]
}
export const defaultCallbacks: InternalOptions["callbacks"] = {
signIn() {
return true
},
redirect({ url, baseUrl }) {
if (url.startsWith("/")) return `${baseUrl}${url}`
else if (new URL(url).origin === baseUrl) return url
return baseUrl
},
session({ session }) {
return {
user: {
name: session.user?.name,
email: session.user?.email,
image: session.user?.image,
},
expires: session.expires?.toISOString?.() ?? session.expires,
}
},
jwt({ token }) {
return token
},
}
/** Initialize all internal options and cookies. */
export async function init({
authOptions: config,
providerId,
action,
url,
cookies: reqCookies,
callbackUrl: reqCallbackUrl,
csrfToken: reqCsrfToken,
csrfDisabled,
isPost,
}: InitParams): Promise<{
options: InternalOptions
cookies: cookie.Cookie[]
}> {
const logger = setLogger(config)
const { providers, provider } = parseProviders({ url, providerId, config })
const maxAge = 30 * 24 * 60 * 60 // Sessions expire after 30 days of being idle by default
let isOnRedirectProxy = false
if (
(provider?.type === "oauth" || provider?.type === "oidc") &&
provider.redirectProxyUrl
) {
try {
isOnRedirectProxy =
new URL(provider.redirectProxyUrl).origin === url.origin
} catch {
throw new TypeError(
`redirectProxyUrl must be a valid URL. Received: ${provider.redirectProxyUrl}`
)
}
}
// User provided options are overridden by other options,
// except for the options with special handling above
const options: InternalOptions = {
debug: false,
pages: {},
theme: {
colorScheme: "auto",
logo: "",
brandColor: "",
buttonText: "",
},
// Custom options override defaults
...config,
// These computed settings can have values in userOptions but we override them
// and are request-specific.
url,
action,
// @ts-expect-errors
provider,
cookies: merge(
cookie.defaultCookies(
config.useSecureCookies ?? url.protocol === "https:"
),
config.cookies
),
providers,
// Session options
session: {
// If no adapter specified, force use of JSON Web Tokens (stateless)
strategy: config.adapter ? "database" : "jwt",
maxAge,
updateAge: 24 * 60 * 60,
generateSessionToken: () => crypto.randomUUID(),
...config.session,
},
// JWT options
jwt: {
secret: config.secret!, // Asserted in assert.ts
maxAge: config.session?.maxAge ?? maxAge, // default to same as `session.maxAge`
encode: jwt.encode,
decode: jwt.decode,
...config.jwt,
},
// Event messages
events: eventsErrorHandler(config.events ?? {}, logger),
adapter: adapterErrorHandler(config.adapter, logger),
// Callback functions
callbacks: { ...defaultCallbacks, ...config.callbacks },
logger,
callbackUrl: url.origin,
isOnRedirectProxy,
experimental: {
...config.experimental,
},
}
// Init cookies
const cookies: cookie.Cookie[] = []
if (csrfDisabled) {
options.csrfTokenVerified = true
} else {
const {
csrfToken,
cookie: csrfCookie,
csrfTokenVerified,
} = await createCSRFToken({
options,
cookieValue: reqCookies?.[options.cookies.csrfToken.name],
isPost,
bodyValue: reqCsrfToken,
})
options.csrfToken = csrfToken
options.csrfTokenVerified = csrfTokenVerified
if (csrfCookie) {
cookies.push({
name: options.cookies.csrfToken.name,
value: csrfCookie,
options: options.cookies.csrfToken.options,
})
}
}
const { callbackUrl, callbackUrlCookie } = await createCallbackUrl({
options,
cookieValue: reqCookies?.[options.cookies.callbackUrl.name],
paramValue: reqCallbackUrl,
})
options.callbackUrl = callbackUrl
if (callbackUrlCookie) {
cookies.push({
name: options.cookies.callbackUrl.name,
value: callbackUrlCookie,
options: options.cookies.callbackUrl.options,
})
}
return { options, cookies }
}
type Method = (...args: any[]) => Promise<any>
/** Wraps an object of methods and adds error handling. */
function eventsErrorHandler(
methods: Partial<InternalOptions["events"]>,
logger: LoggerInstance
): Partial<InternalOptions["events"]> {
return Object.keys(methods).reduce<any>((acc, name) => {
acc[name] = async (...args: any[]) => {
try {
const method: Method = methods[name as keyof Method]
return await method(...args)
} catch (e) {
logger.error(new EventError(e as Error))
}
}
return acc
}, {})
}
/** Handles adapter induced errors. */
function adapterErrorHandler(
adapter: AuthConfig["adapter"],
logger: LoggerInstance
) {
if (!adapter) return
return Object.keys(adapter).reduce<any>((acc, name) => {
acc[name] = async (...args: any[]) => {
try {
logger.debug(`adapter_${name}`, { args })
const method: Method = adapter[name as keyof Method]
return await method(...args)
} catch (e) {
const error = new AdapterError(e as Error)
logger.error(error)
throw error
}
}
return acc
}, {})
}