forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasskey.ts
More file actions
289 lines (247 loc) · 7.71 KB
/
Copy pathpasskey.ts
File metadata and controls
289 lines (247 loc) · 7.71 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
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/**
* Passkey helper utilities for WebAuthn credential handling.
*
* These helpers convert between ArrayBuffer and Base64URL encodings and
* normalise server-provided credential options into browser-compatible types.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Convert a base64url string to an ArrayBuffer.
*/
type NodeBufferCtor = {
from(input: string, encoding: string): { toString(encoding: string): string }
}
export function base64UrlToArrayBuffer(value?: string | null): ArrayBuffer {
if (!value) return new ArrayBuffer(0)
const padding = '='.repeat((4 - (value.length % 4)) % 4)
const base64 = (value + padding).replace(/-/g, '+').replace(/_/g, '/')
const globalRef = globalThis as typeof globalThis & {
Buffer?: NodeBufferCtor
}
const decode =
typeof globalRef.atob === 'function'
? globalRef.atob.bind(globalRef)
: (input: string) => {
if (typeof globalRef.Buffer !== 'undefined') {
return globalRef.Buffer.from(input, 'base64').toString('binary')
}
throw new Error(
'Base64 decoding is not supported in this environment'
)
}
const binary = decode(base64)
const buffer = new ArrayBuffer(binary.length)
const bytes = new Uint8Array(buffer)
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i)
}
return buffer
}
/**
* Convert an ArrayBuffer to a base64url string.
*/
export function arrayBufferToBase64Url(
buffer?: ArrayBuffer | ArrayBufferLike | null
): string {
if (!buffer) return ''
const globalRef = globalThis as typeof globalThis & {
Buffer?: NodeBufferCtor
}
const bytes = new Uint8Array(buffer)
let binary = ''
for (let i = 0; i < bytes.byteLength; i += 1) {
binary += String.fromCharCode(bytes[i])
}
const encode =
typeof globalRef.btoa === 'function'
? globalRef.btoa.bind(globalRef)
: (input: string) => {
if (typeof globalRef.Buffer !== 'undefined') {
return globalRef.Buffer.from(input, 'binary').toString('base64')
}
throw new Error(
'Base64 encoding is not supported in this environment'
)
}
return encode(binary)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '')
}
/**
* Prepare credential creation options returned by the backend.
*/
export function prepareCredentialCreationOptions(
payload: any
): PublicKeyCredentialCreationOptions {
const options =
payload?.publicKey ??
payload?.PublicKey ??
payload?.response ??
payload?.Response
if (!options) {
throw new Error(
'Unable to parse Passkey registration options from response'
)
}
const publicKey: PublicKeyCredentialCreationOptions & Record<string, any> = {
...options,
challenge: base64UrlToArrayBuffer(options.challenge),
user: {
...options.user,
id: base64UrlToArrayBuffer(options.user?.id),
},
}
if (Array.isArray(options.excludeCredentials)) {
publicKey.excludeCredentials = options.excludeCredentials.map(
(item: any) => ({
...item,
id: base64UrlToArrayBuffer(item.id),
})
)
}
if (
Array.isArray(options.attestationFormats) &&
options.attestationFormats.length === 0
) {
delete publicKey.attestationFormats
}
return publicKey
}
/**
* Prepare credential request options returned by the backend.
*/
export function prepareCredentialRequestOptions(
payload: any
): PublicKeyCredentialRequestOptions {
const options =
payload?.publicKey ??
payload?.PublicKey ??
payload?.response ??
payload?.Response
if (!options) {
throw new Error('Unable to parse Passkey login options from response')
}
const publicKey: PublicKeyCredentialRequestOptions & Record<string, any> = {
...options,
challenge: base64UrlToArrayBuffer(options.challenge),
}
if (Array.isArray(options.allowCredentials)) {
publicKey.allowCredentials = options.allowCredentials.map((item: any) => ({
...item,
id: base64UrlToArrayBuffer(item.id),
}))
}
return publicKey
}
/**
* Build payload for registering a new credential.
*/
export function buildRegistrationResult(
credential: PublicKeyCredential | null
): Record<string, any> | null {
if (!credential) return null
const response = credential.response as AuthenticatorAttestationResponse & {
getTransports?: () => string[]
}
const transports =
typeof response.getTransports === 'function'
? response.getTransports()
: undefined
return {
id: credential.id,
rawId: arrayBufferToBase64Url(credential.rawId),
type: credential.type,
authenticatorAttachment: credential.authenticatorAttachment,
response: {
attestationObject: arrayBufferToBase64Url(response.attestationObject),
clientDataJSON: arrayBufferToBase64Url(response.clientDataJSON),
transports,
},
clientExtensionResults: credential.getClientExtensionResults?.() ?? {},
}
}
/**
* Build payload for verifying an existing credential.
*/
export function buildAssertionResult(
credential: PublicKeyCredential | null
): Record<string, any> | null {
if (!credential) return null
const response = credential.response as AuthenticatorAssertionResponse
return {
id: credential.id,
rawId: arrayBufferToBase64Url(credential.rawId),
type: credential.type,
authenticatorAttachment: credential.authenticatorAttachment,
response: {
authenticatorData: arrayBufferToBase64Url(response.authenticatorData),
clientDataJSON: arrayBufferToBase64Url(response.clientDataJSON),
signature: arrayBufferToBase64Url(response.signature),
userHandle: response.userHandle
? arrayBufferToBase64Url(response.userHandle)
: null,
},
clientExtensionResults: credential.getClientExtensionResults?.() ?? {},
}
}
/**
* Check if current environment supports Passkey/WebAuthn.
*/
export async function isPasskeySupported(): Promise<boolean> {
if (typeof window === 'undefined') return false
const { PublicKeyCredential } = window
if (!PublicKeyCredential) return false
if (
typeof PublicKeyCredential.isConditionalMediationAvailable === 'function'
) {
try {
const available =
await PublicKeyCredential.isConditionalMediationAvailable()
if (available) return true
} catch {
// ignore
}
}
if (
typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable ===
'function'
) {
try {
return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()
} catch {
return false
}
}
return true
}
/**
* Execute an async Passkey credential creation flow.
*/
export async function createCredential(
options: PublicKeyCredentialCreationOptions
) {
return navigator.credentials.create({ publicKey: options })
}
/**
* Execute an async Passkey credential request flow.
*/
export async function getCredential(
options: PublicKeyCredentialRequestOptions
) {
return navigator.credentials.get({ publicKey: options })
}