-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathadapter.ts
More file actions
635 lines (564 loc) · 18.4 KB
/
adapter.ts
File metadata and controls
635 lines (564 loc) · 18.4 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
import { afterAll, beforeAll, expect, test } from "vitest"
import type { Adapter, VerificationToken } from "@auth/core/adapters"
import { createHash, randomInt, randomUUID } from "crypto"
export interface TestOptions {
adapter: Adapter
fixtures?: {
user?: any
session?: any
account?: any
sessionUpdateExpires?: Date
verificationTokenExpires?: Date
}
db: {
/** Generates UUID v4 by default. Use it to override how the test suite should generate IDs, like user id. */
id?: () => string | undefined
/**
* Manually disconnect database after all tests have been run,
* if your adapter doesn't do it automatically
*/
disconnect?: () => Promise<any>
/**
* Manually establishes a db connection before all tests,
* if your db doesn't do this automatically
*/
connect?: () => Promise<any>
/** A simple query function that returns a session directly from the db. */
session: (sessionToken: string) => any
/** A simple query function that returns a user directly from the db. */
user: (id: string) => any
/** A simple query function that returns an account directly from the db. */
account: (providerAccountId: {
provider: string
providerAccountId: string
}) => any
/**
* A simple query function that returns an verification token directly from the db,
* based on the user identifier and the verification token (hashed).
*/
verificationToken: (params: { identifier: string; token: string }) => any
/**
* A simple query function that returns an authenticator directly from the db.
*/
authenticator?: (credentialID: string) => any
}
skipTests?: string[]
/**
* Enables testing of WebAuthn methods.
*/
testWebAuthnMethods?: boolean
}
/**
* A wrapper to run the most basic tests.
* Run this at the top of your test file.
* You can add additional tests below, if you wish.
*/
export async function runBasicTests(options: TestOptions) {
const id = () => options.db.id?.() ?? randomUUID()
// Init
beforeAll(async () => {
await options.db.connect?.()
})
const {
adapter: _adapter,
db,
skipTests: skipTests = [],
testWebAuthnMethods,
} = options
const adapter = _adapter as Required<Adapter>
if (!testWebAuthnMethods) {
skipTests.push(
...[
"getAccount",
"getAuthenticator",
"createAuthenticator",
"listAuthenticatorsByUserId",
"updateAuthenticatorCounter",
]
)
}
const maybeTest = (
method: keyof Adapter,
...args: Parameters<typeof test> extends [any, ...infer U] ? U : never
) =>
skipTests.includes(method)
? test.skip(method, ...args)
: test(method, ...args)
afterAll(async () => {
// @ts-expect-error This is only used for the TypeORM adapter
await adapter.__disconnect?.()
await options.db.disconnect?.()
})
let user = options.fixtures?.user ?? {
id: id(),
email: "fill@murray.com",
image: "https://www.fillmurray.com/460/300",
name: "Fill Murray",
emailVerified: new Date(),
}
if (process.env.CUSTOM_MODEL === "1") {
user.role = "admin"
user.phone = "00000000000"
}
const session: any = options.fixtures?.session ?? {
sessionToken: id(),
expires: ONE_WEEK_FROM_NOW,
}
const account: any = options.fixtures?.account ?? {
provider: "github",
providerAccountId: id(),
type: "oauth",
access_token: id(),
expires_at: ONE_MONTH / 1000,
id_token: id(),
refresh_token: id(),
token_type: "bearer",
scope: "user",
session_state: id(),
}
// All adapters must define these methods
test("Required (User, Account, Session) methods exist", () => {
const requiredMethods = [
"createUser",
"getUser",
"getUserByEmail",
"getUserByAccount",
"updateUser",
"linkAccount",
"createSession",
"getSessionAndUser",
"updateSession",
"deleteSession",
]
requiredMethods.forEach((method) => {
expect(adapter).toHaveProperty(method)
})
})
test("createUser", async () => {
const { id } = await adapter.createUser(user)
const dbUser = await db.user(id)
expect(dbUser).toEqual({ ...user, id })
user = dbUser
session.userId = dbUser.id
account.userId = dbUser.id
})
test("getUser", async () => {
expect(await adapter.getUser(id())).toBeNull()
expect(await adapter.getUser(user.id)).toEqual(user)
})
test("getUserByEmail", async () => {
expect(await adapter.getUserByEmail("non-existent-email")).toBeNull()
expect(await adapter.getUserByEmail(user.email)).toEqual(user)
})
test("createSession", async () => {
const { sessionToken } = await adapter.createSession(session)
const dbSession = await db.session(sessionToken)
expect(dbSession).toEqual({ ...session, id: dbSession.id })
session.userId = dbSession.userId
session.id = dbSession.id
})
test("getSessionAndUser", async () => {
let sessionAndUser = await adapter.getSessionAndUser("invalid-token")
expect(sessionAndUser).toBeNull()
sessionAndUser = await adapter.getSessionAndUser(session.sessionToken)
if (!sessionAndUser) {
throw new Error("Session and User was not found, but they should exist")
}
expect(sessionAndUser).toEqual({
user,
session,
})
})
test("updateUser", async () => {
const newName = "Updated Name"
const returnedUser = await adapter.updateUser({
id: user.id,
name: newName,
})
expect(returnedUser.name).toBe(newName)
const dbUser = await db.user(user.id)
expect(dbUser.name).toBe(newName)
user.name = newName
})
test("updateSession", async () => {
let dbSession = await db.session(session.sessionToken)
const expires = options.fixtures?.sessionUpdateExpires ?? ONE_MONTH_FROM_NOW
expect(dbSession.expires.valueOf()).not.toBe(expires.valueOf())
await adapter.updateSession({
sessionToken: session.sessionToken,
expires,
})
dbSession = await db.session(session.sessionToken)
expect(dbSession.expires.valueOf()).toBe(expires.valueOf())
})
test("linkAccount", async () => {
await adapter.linkAccount(account)
const dbAccount = await db.account({
provider: account.provider,
providerAccountId: account.providerAccountId,
})
expect(dbAccount).toEqual({ ...account, id: dbAccount.id })
})
test("getUserByAccount", async () => {
let userByAccount = await adapter.getUserByAccount({
provider: "invalid-provider",
providerAccountId: "invalid-provider-account-id",
})
expect(userByAccount).toBeNull()
userByAccount = await adapter.getUserByAccount({
provider: account.provider,
providerAccountId: account.providerAccountId,
})
expect(userByAccount).toEqual(user)
})
test("deleteSession", async () => {
await adapter.deleteSession(session.sessionToken)
const dbSession = await db.session(session.sessionToken)
expect(dbSession).toBeNull()
})
// These are optional for custom adapters, but we require them for the official adapters
test("Verification Token methods exist", () => {
const requiredMethods = ["createVerificationToken", "useVerificationToken"]
requiredMethods.forEach((method) => {
expect(adapter).toHaveProperty(method)
})
})
test("createVerificationToken", async () => {
const identifier = "info@example.com"
const token = id()
const hashedToken = hashToken(token)
const verificationToken = {
token: hashedToken,
identifier,
expires:
options.fixtures?.verificationTokenExpires ?? FIFTEEN_MINUTES_FROM_NOW,
}
await adapter.createVerificationToken?.(verificationToken)
const dbVerificationToken = await db.verificationToken({
token: hashedToken,
identifier,
})
expect(dbVerificationToken).toEqual(verificationToken)
})
test("useVerificationToken", async () => {
const identifier = "info@example.com"
const token = id()
const hashedToken = hashToken(token)
const verificationToken = {
token: hashedToken,
identifier,
expires:
options.fixtures?.verificationTokenExpires ?? FIFTEEN_MINUTES_FROM_NOW,
} satisfies VerificationToken
await adapter.createVerificationToken?.(verificationToken)
const dbVerificationToken1 = await adapter.useVerificationToken?.({
identifier,
token: hashedToken,
})
if (!dbVerificationToken1) {
throw new Error("Verification Token was not found, but it should exist")
}
expect(dbVerificationToken1).toEqual(verificationToken)
const dbVerificationTokenSecondTry = await adapter.useVerificationToken?.({
identifier,
token: hashedToken,
})
expect(dbVerificationTokenSecondTry).toBeNull()
// Should only return if the identifier matches
const verificationToken2 = {
token: hashedToken,
identifier,
expires:
options.fixtures?.verificationTokenExpires ?? FIFTEEN_MINUTES_FROM_NOW,
} satisfies VerificationToken
await adapter.createVerificationToken?.(verificationToken2)
const dbVerificationToken2 = await adapter.useVerificationToken?.({
identifier: "invalid@identifier.com",
token: hashedToken,
})
expect(dbVerificationToken2).toBeNull()
})
// Future methods
// These methods are not yet invoked in the core, but built-in adapters must implement them
test("Future methods exist", () => {
const requiredMethods = ["unlinkAccount", "deleteUser"]
requiredMethods.forEach((method) => {
expect(adapter).toHaveProperty(method)
})
})
test("unlinkAccount", async () => {
let dbAccount = await db.account({
provider: account.provider,
providerAccountId: account.providerAccountId,
})
expect(dbAccount).toEqual({ ...account, id: dbAccount.id })
await adapter.unlinkAccount?.({
provider: account.provider,
providerAccountId: account.providerAccountId,
})
dbAccount = await db.account({
provider: account.provider,
providerAccountId: account.providerAccountId,
})
expect(dbAccount).toBeNull()
})
maybeTest("deleteUser", async () => {
let dbUser = await db.user(user.id)
expect(dbUser).toEqual(user)
// Re-populate db with session and account
delete session.id
await adapter.createSession(session)
await adapter.linkAccount(account)
await adapter.deleteUser?.(user.id)
dbUser = await db.user(user.id)
// User should not exist after it is deleted
expect(dbUser).toBeNull()
const dbSession = await db.session(session.sessionToken)
// Session should not exist after user is deleted
expect(dbSession).toBeNull()
const dbAccount = await db.account({
provider: account.provider,
providerAccountId: account.providerAccountId,
})
// Account should not exist after user is deleted
expect(dbAccount).toBeNull()
})
maybeTest("getAccount", async () => {
// Setup
const providerAccountId = randomUUID()
const provider = "auth0"
const localUser = await adapter.createUser({
id: id(),
email: "getAccount@example.com",
emailVerified: null,
})
await adapter.linkAccount({
provider,
providerAccountId,
type: "oauth",
userId: localUser.id,
})
// Test
const invalidBoth = await adapter.getAccount(
"invalid-provider-account-id",
"invalid-provider"
)
expect(invalidBoth).toBeNull()
const invalidProvider = await adapter.getAccount(
providerAccountId,
"invalid-provider"
)
expect(invalidProvider).toBeNull()
const invalidProviderAccountId = await adapter.getAccount(
"invalid-provider-account-id",
provider
)
expect(invalidProviderAccountId).toBeNull()
const validAccount = await adapter.getAccount(providerAccountId, provider)
expect(validAccount).not.toBeNull()
const dbAccount = await db.account({
provider,
providerAccountId,
})
expect(dbAccount).toMatchObject(validAccount || {})
})
maybeTest("createAuthenticator", async () => {
// Setup
const credentialID = randomUUID()
const localUser = await adapter.createUser({
id: id(),
email: "createAuthenticator@example.com",
emailVerified: null,
})
await adapter.linkAccount({
provider: "webauthn",
providerAccountId: credentialID,
type: "webauthn",
userId: localUser.id,
})
// Test
const authenticatorData = {
credentialID,
providerAccountId: credentialID,
userId: localUser.id,
counter: randomInt(100),
credentialBackedUp: true,
credentialDeviceType: "platform",
credentialPublicKey: randomUUID(),
transports: "usb,ble,nfc",
}
const newAuthenticator =
await adapter.createAuthenticator(authenticatorData)
expect(newAuthenticator).not.toBeNull()
expect(newAuthenticator).toMatchObject(authenticatorData)
const dbAuthenticator = db.authenticator
? await db.authenticator(credentialID)
: undefined
expect(dbAuthenticator).toMatchObject(newAuthenticator)
})
maybeTest("getAuthenticator", async () => {
// Setup
const credentialID = randomUUID()
const localUser = await adapter.createUser({
id: id(),
email: "getAuthenticator@example.com",
emailVerified: null,
})
await adapter.linkAccount({
provider: "webauthn",
providerAccountId: credentialID,
type: "webauthn",
userId: localUser.id,
})
await adapter.createAuthenticator({
credentialID,
providerAccountId: credentialID,
userId: localUser.id,
counter: randomInt(100),
credentialBackedUp: true,
credentialDeviceType: "platform",
credentialPublicKey: randomUUID(),
transports: "usb,ble,nfc",
})
// Test
const invalidAuthenticator = await adapter.getAuthenticator(
"invalid-credential-id"
)
expect(invalidAuthenticator).toBeNull()
const validAuthenticator = await adapter.getAuthenticator(credentialID)
expect(validAuthenticator).not.toBeNull()
const dbAuthenticator = db.authenticator
? await db.authenticator(credentialID)
: undefined
expect(dbAuthenticator).toMatchObject(validAuthenticator || {})
})
maybeTest("listAuthenticatorsByUserId", async () => {
// Setup
const user1 = await adapter.createUser({
id: id(),
email: "listAuthenticatorsByUserId1@example.com",
emailVerified: null,
})
const user2 = await adapter.createUser({
id: id(),
email: "listAuthenticatorsByUserId2@example.com",
emailVerified: null,
})
const credentialID1 = randomUUID()
const credentialID2 = randomUUID()
const credentialID3 = randomUUID()
await adapter.linkAccount({
provider: "webauthn",
providerAccountId: credentialID1,
type: "webauthn",
userId: user1.id,
})
await adapter.linkAccount({
provider: "webauthn",
providerAccountId: credentialID2,
type: "webauthn",
userId: user1.id,
})
await adapter.linkAccount({
provider: "webauthn",
providerAccountId: credentialID3,
type: "webauthn",
userId: user2.id,
})
const authenticator1 = await adapter.createAuthenticator({
credentialID: credentialID1,
providerAccountId: credentialID1,
userId: user1.id,
counter: randomInt(100),
credentialBackedUp: true,
credentialDeviceType: "platform",
credentialPublicKey: randomUUID(),
transports: "usb,ble,nfc",
})
const authenticator2 = await adapter.createAuthenticator({
credentialID: credentialID2,
providerAccountId: credentialID2,
userId: user1.id,
counter: randomInt(100),
credentialBackedUp: true,
credentialDeviceType: "platform",
credentialPublicKey: randomUUID(),
transports: "usb,nfc",
})
const authenticator3 = await adapter.createAuthenticator({
credentialID: credentialID3,
providerAccountId: credentialID3,
userId: user2.id,
counter: randomInt(100),
credentialBackedUp: true,
credentialDeviceType: "platform",
credentialPublicKey: randomUUID(),
transports: "usb,ble",
})
// Test
const authenticators0 =
await adapter.listAuthenticatorsByUserId("invalid-user-id")
expect(authenticators0).toEqual([])
const authenticators1 = await adapter.listAuthenticatorsByUserId(user1.id)
expect(authenticators1).not.toBeNull()
expect([authenticator2, authenticator1]).toEqual(
expect.arrayContaining(authenticators1 || [])
)
const authenticators2 = await adapter.listAuthenticatorsByUserId(user2.id)
expect(authenticators2).not.toBeNull()
expect([authenticator3]).toMatchObject(
expect.arrayContaining(authenticators2 || [])
)
})
maybeTest("updateAuthenticatorCounter", async () => {
// Setup
const credentialID = randomUUID()
const localUser = await adapter.createUser({
id: id(),
email: "updateAuthenticatorCounter@example.com",
emailVerified: null,
})
await adapter.linkAccount({
provider: "webauthn",
providerAccountId: credentialID,
type: "webauthn",
userId: localUser.id,
})
const newAuthenticator = await adapter.createAuthenticator({
credentialID,
providerAccountId: credentialID,
userId: localUser.id,
counter: randomInt(100),
credentialBackedUp: true,
credentialDeviceType: "platform",
credentialPublicKey: randomUUID(),
transports: "usb,ble,nfc",
})
// Test
await expect(() =>
adapter.updateAuthenticatorCounter(
"invalid-credential-id",
randomInt(100)
)
).rejects.toThrow()
const newCounter = newAuthenticator.counter + randomInt(100)
const updatedAuthenticator = await adapter.updateAuthenticatorCounter(
credentialID,
newCounter
)
expect(updatedAuthenticator).not.toBeNull()
expect(updatedAuthenticator.counter).toBe(newCounter)
})
}
// UTILS
export function hashToken(token: string) {
return createHash("sha256").update(`${token}anything`).digest("hex")
}
export { randomUUID }
export const ONE_WEEK_FROM_NOW = new Date(Date.now() + 1000 * 60 * 60 * 24 * 7)
ONE_WEEK_FROM_NOW.setMilliseconds(0)
export const FIFTEEN_MINUTES_FROM_NOW = new Date(Date.now() + 15 * 60 * 1000)
FIFTEEN_MINUTES_FROM_NOW.setMilliseconds(0)
export const ONE_MONTH = 1000 * 60 * 60 * 24 * 30
export const ONE_MONTH_FROM_NOW = new Date(Date.now() + ONE_MONTH)
ONE_MONTH_FROM_NOW.setMilliseconds(0)