-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
305 lines (273 loc) · 7.99 KB
/
auth.js
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
/* eslint-disable unicorn/no-null */
import * as ed from '@noble/ed25519'
import * as odd from '@oddjs/odd'
import { publicKeyToDid } from '@oddjs/odd/did/index'
import * as Session from '@oddjs/odd/session'
import { base64url } from 'iso-base/rfc4648'
import { utf8 } from 'iso-base/utf8'
import { u8 } from 'iso-base/utils'
import { credentialsCreate, credentialsGet } from 'iso-passkeys'
import * as Crypto from './crypto.js'
import { get, set } from 'idb-keyval'
/**
* Create an encryption key from passkey material
*
* @param {BufferSource} keyMaterial
*/
export async function createEncryptionKey(keyMaterial) {
const inputKeyMaterial = u8(keyMaterial)
// import key material
const keyDerivationKey = await crypto.subtle.importKey(
'raw',
inputKeyMaterial,
'HKDF',
false,
['deriveKey']
)
const encryptionKey = await crypto.subtle.deriveKey(
{
name: 'HKDF',
info: utf8.decode('webnative-passkey'),
salt: new Uint8Array(), // TODO more salt
hash: 'SHA-256',
},
keyDerivationKey,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
)
return encryptionKey
}
/**
*
* @param {import('@oddjs/odd').Configuration} config
*/
function rpFromConfig(config) {
const host = document.location.host
const id = host.split(':')[0]
return typeof config.namespace === 'string'
? {
name: config.namespace,
id,
}
: {
name: config.namespace.name,
id,
}
}
/**
* Register passkey
*
* @param {string} username
* @param {import('@oddjs/odd').Storage.Implementation} storage
* @param {import('@oddjs/odd').Configuration} config
*/
async function registerPasskey(username, storage, config) {
const rp = rpFromConfig(config)
const credential = await credentialsCreate({
publicKey: {
challenge: base64url.encode(rp.id),
rp,
user: {
id: username,
name: username,
displayName: username,
},
attestation: 'none',
authenticatorSelection: {
userVerification: 'required',
requireResidentKey: true,
residentKey: 'required',
},
extensions: {
credProps: true,
largeBlob: {
support: 'preferred',
},
prf: {
eval: {
first: utf8.decode(rp.id + 'signing').buffer,
second: utf8.decode(rp.id + 'encryption').buffer,
},
},
},
},
})
if (
!credential.clientExtensionResults.prf ||
credential.clientExtensionResults.prf?.enabled === false
) {
throw new Error(
'This browser does not support the Webauthn extensions (PRF) needed for this demo.'
)
}
await set('passkeys', [credential])
return credential
}
/**
* Get passkey
*
* @param {import('@oddjs/odd').Configuration} config
* @param {import('@oddjs/odd/components/storage/implementation').Implementation} storage
* @param {import('iso-passkeys/types').CredentialMediationRequirement} [mediation]
*/
async function getPasskey(config, storage, mediation) {
const rp = rpFromConfig(config)
const credentials = await get('passkeys')
const assertion = await credentialsGet({
mediation,
publicKey: {
challenge: base64url.encode(rp.id),
allowCredentials: mediation === 'conditional' ? [] : credentials,
userVerification: 'required',
rpId: rp.id,
extensions: {
// largeBlob: {
// // read: true,
// write: utf8.decode('hello world').buffer,
// },
prf: {
eval: {
first: utf8.decode(rp.id + 'signing').buffer,
second: utf8.decode(rp.id + 'encryption').buffer,
},
},
},
},
})
if (
!assertion.clientExtensionResults.prf ||
!assertion.clientExtensionResults.prf.results
) {
throw new Error(
'This browser does not support the Webauthn extensions (PRF) needed for this demo.'
)
}
// @ts-ignore
const secret1 = assertion.clientExtensionResults.prf.results.first
const secret2 = assertion.clientExtensionResults.prf.results.second
const publicKey = await ed.getPublicKeyAsync(u8(secret1))
if (!secret2) {
throw new Error('PRF second secret not supported.')
}
const encryptionKey = await createEncryptionKey(secret2)
await storage.setItem('passkey/encryption-key', encryptionKey)
return {
publicKey,
assertion,
privateKey: u8(secret1),
userHandle: assertion.userHandle,
}
}
/**
* Login
*
* @param {import('@oddjs/odd/components/auth/implementation/base').Dependencies & {config: import('@oddjs/odd').Configuration;}} deps
* @param {Awaited<ReturnType<getPasskey>>} [passkey]
* @param {string} [username]
*/
export async function login(deps, passkey, username) {
if (!passkey) {
passkey = await getPasskey(
deps.config,
deps.storage,
username ? undefined : 'conditional'
)
}
const { privateKey, publicKey, userHandle } = passkey
if (!username && !userHandle) {
throw new Error('Username is required')
}
const crypto = await Crypto.implementation(deps.config, publicKey, privateKey)
// Create an account UCAN
const accountUcan = await odd.ucan.build({
dependencies: {
crypto,
},
potency: 'APPEND',
resource: '*',
lifetimeInSeconds: 60 * 60 * 24 * 30 * 12 * 1000, // a lot of time
audience: await odd.did.ucan(deps.crypto),
issuer: publicKeyToDid(crypto, publicKey, 'ed25519'),
})
// Save account UCAN
await deps.storage.setItem(
deps.storage.KEYS.ACCOUNT_UCAN,
odd.ucan.encode(accountUcan)
)
await Session.provide(deps.storage, {
type: 'Passkey',
// @ts-ignore
username: username || userHandle,
})
return passkey
}
/**
* Register
*
* @param {import('@oddjs/odd/components/auth/implementation/base').Dependencies & {config: import('@oddjs/odd').Configuration;}} deps
* @param {string} username
*/
export async function register(deps, username) {
await registerPasskey(username, deps.storage, deps.config)
const passkey = await getPasskey(deps.config, deps.storage)
const registeAuth = odd.defaultAuthComponent({
crypto: await Crypto.implementation(
deps.config,
passkey.publicKey,
passkey.privateKey
),
reference: deps.reference,
storage: deps.storage,
})
const { success } = await registeAuth.register({ username })
if (success) {
return await login(deps, passkey, username)
}
}
/**
* Odd auth implementation
*
* @param {import('@oddjs/odd/components/auth/implementation/base').Dependencies & {config: import('@oddjs/odd').Configuration}} deps
* @returns {import('@oddjs/odd/components/auth/implementation').Implementation<import('@oddjs/odd').Components>}
*/
export function implementation(deps) {
const defaultAuth = odd.defaultAuthComponent(deps)
return {
type: 'Passkey',
canDelegateAccount: defaultAuth.canDelegateAccount,
createChannel: defaultAuth.createChannel,
delegateAccount: defaultAuth.delegateAccount,
isUsernameAvailable: defaultAuth.isUsernameAvailable,
isUsernameValid: defaultAuth.isUsernameValid,
linkDevice: defaultAuth.linkDevice,
register: async ({ username }) => {
if (!username) {
await login(deps, undefined, username)
return { success: true }
}
const isValid = await defaultAuth.isUsernameValid(username)
if (isValid) {
const isAvailable = await defaultAuth.isUsernameAvailable(username)
if (isAvailable) {
const passkey = await register(deps, username)
return passkey ? { success: true } : { success: false }
} else {
await login(deps, undefined, username)
return { success: true }
}
}
return { success: false }
},
session: async (components, username, config, eventEmitters) => {
// Check passkey signed UCAN
const proof = await deps.storage.getItem(
components.storage.KEYS.ACCOUNT_UCAN
)
if (!proof) {
return null
}
return defaultAuth.session(components, username, config, eventEmitters)
},
}
}