-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathkms.ts
More file actions
495 lines (425 loc) · 11 KB
/
Copy pathkms.ts
File metadata and controls
495 lines (425 loc) · 11 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
/**
* OAuth3 KMS Service - Secure key management for authentication
*
* Uses DWS KMS for signing and encryption.
*/
import { getKMSServiceFromEnv, type KMSServiceClient } from '@jejunetwork/shared'
import type { Address, Hex } from 'viem'
import { isHex, keccak256, toBytes, toHex, verifyMessage } from 'viem'
import { z } from 'zod'
interface OAuth3KMSConfig {
jwtSigningKeyId: string
jwtSignerAddress: Address
serviceAgentId: string
chainId: string
}
let kmsConfig: OAuth3KMSConfig | null = null
let kmsInitialized = false
let kmsService: KMSServiceClient | null = null
function getKmsService(): KMSServiceClient {
if (!kmsService) {
kmsService = getKMSServiceFromEnv()
}
return kmsService
}
function getConfig(): OAuth3KMSConfig {
if (!kmsConfig) {
throw new Error('KMS not configured')
}
return kmsConfig
}
/**
* Initialize KMS for OAuth3 service.
*/
export async function initializeKMS(config: OAuth3KMSConfig): Promise<void> {
if (kmsInitialized) return
kmsConfig = config
const healthy = await getKmsService().isHealthy()
if (!healthy) {
throw new Error('KMS is not healthy')
}
console.log('[OAuth3/KMS] Connected to DWS KMS')
kmsInitialized = true
}
// ============ JWT Token Operations ============
export interface JWTPayload {
sub: string
iat: number
exp: number
iss?: string
aud?: string
scopes?: string[]
jti?: string
}
function base64urlEncode(str: string): string {
const base64 = Buffer.from(str).toString('base64')
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
}
function base64urlDecode(str: string): string {
let base64 = str.replace(/-/g, '+').replace(/_/g, '/')
while (base64.length % 4) {
base64 += '='
}
return Buffer.from(base64, 'base64').toString()
}
/**
* Generate a secure JWT token signed with DWS KMS.
*/
export async function generateSecureToken(
userId: string,
options?: {
expiresInSeconds?: number
issuer?: string
audience?: string
scopes?: string[]
},
): Promise<string> {
const now = Math.floor(Date.now() / 1000)
const jti = crypto.randomUUID()
const expiresInSeconds = options?.expiresInSeconds ?? 3600
const expiration = now + expiresInSeconds
const claims = {
sub: userId,
iss: options?.issuer ?? 'jeju:oauth3',
aud: options?.audience ?? 'gateway',
scopes: options?.scopes,
iat: now,
jti,
exp: expiration,
}
const config = getConfig()
const headerB64 = base64urlEncode(
JSON.stringify({ alg: 'ES256K', typ: 'JWT', kid: config.jwtSigningKeyId }),
)
const payloadB64 = base64urlEncode(JSON.stringify(claims))
const signingInput = `${headerB64}.${payloadB64}`
const messageHash = keccak256(toBytes(signingInput))
const signature = await getKmsService().sign(
messageHash,
config.jwtSignerAddress,
)
if (!isHex(signature)) {
throw new Error('KMS returned non-hex signature')
}
const signatureB64 = base64urlEncode(signature)
return `${headerB64}.${payloadB64}.${signatureB64}`
}
/**
* Verify a JWT token signed with DWS KMS.
* Returns the user ID (sub claim) if valid, null otherwise.
*/
export async function verifySecureToken(token: string): Promise<string | null> {
const parts = token.split('.')
if (parts.length !== 3) {
return null
}
const [headerB64, payloadB64, signatureB64] = parts
let claims: { sub?: string; iss?: string; exp?: number }
try {
const header = JSON.parse(base64urlDecode(headerB64))
if (header?.alg && header.alg !== 'ES256K') {
return null
}
claims = JSON.parse(base64urlDecode(payloadB64))
} catch {
return null
}
if (claims.iss !== 'jeju:oauth3') {
return null
}
if (claims.exp && claims.exp < Math.floor(Date.now() / 1000)) {
return null
}
const signingInput = `${headerB64}.${payloadB64}`
if (!kmsConfig) {
return null
}
const messageHash = keccak256(toBytes(signingInput))
const signature = base64urlDecode(signatureB64)
if (!isHex(signature)) {
return null
}
const isValid = await verifyMessage({
address: kmsConfig.jwtSignerAddress,
message: { raw: toBytes(messageHash) },
signature,
})
if (!isValid || !claims.sub) {
return null
}
return claims.sub
}
// ============ Secret Sealing ============
interface SealedSecret {
encrypted: string
sealedAt: number
}
/**
* Seal (encrypt) a secret using DWS KMS.
*/
export async function sealSecret(plaintext: string): Promise<SealedSecret> {
const config = getConfig()
const encrypted = await getKmsService().encrypt(
plaintext,
config.jwtSignerAddress,
)
return {
encrypted,
sealedAt: Date.now(),
}
}
/**
* Unseal (decrypt) a previously sealed secret.
*/
export async function unsealSecret(sealed: SealedSecret): Promise<string> {
const config = getConfig()
return getKmsService().decrypt(sealed.encrypted, config.jwtSignerAddress)
}
// ============ Session Data Encryption ============
interface EncryptedSessionData {
encrypted: string
}
/**
* Encrypt session data using DWS KMS.
*/
export async function encryptSessionData(
plaintext: string,
): Promise<EncryptedSessionData> {
const config = getConfig()
const encrypted = await getKmsService().encrypt(
plaintext,
config.jwtSignerAddress,
)
return { encrypted }
}
/**
* Decrypt session data.
*/
export async function decryptSessionData(
encrypted: EncryptedSessionData,
): Promise<string> {
const config = getConfig()
return getKmsService().decrypt(encrypted.encrypted, config.jwtSignerAddress)
}
// ============ Challenge Generation ============
/**
* Generate a cryptographic challenge for wallet authentication.
*/
export async function generateChallenge(
address: Address,
clientId: string,
): Promise<{
challenge: string
expiresAt: number
}> {
const nonce = crypto.randomUUID()
const timestamp = Date.now()
const expiresAt = timestamp + 5 * 60 * 1000 // 5 minutes
// Create challenge message that user will sign
const challenge = [
`Sign this message to authenticate with ${clientId}`,
'',
`Address: ${address}`,
`Nonce: ${nonce}`,
`Timestamp: ${timestamp}`,
`Expires: ${new Date(expiresAt).toISOString()}`,
].join('\n')
return { challenge, expiresAt }
}
/**
* Verify a signed challenge.
*/
export async function verifyChallenge(
address: Address,
challenge: string,
signature: Hex,
): Promise<boolean> {
// Verify the signature matches the address
const isValid = await verifyMessage({
address,
message: challenge,
signature,
})
if (!isValid) {
return false
}
// Extract and verify expiration from challenge
const expiresMatch = challenge.match(/Expires: (.+)/)
if (expiresMatch) {
const expiresAt = new Date(expiresMatch[1]).getTime()
if (Date.now() > expiresAt) {
return false
}
}
return true
}
// ============ Client Secret Hashing ============
export interface HashedClientSecret {
hash: string
salt: string
algorithm: 'argon2id' | 'pbkdf2'
version: number
}
/**
* Hash a client secret using PBKDF2.
*/
export async function hashClientSecret(
secret: string,
): Promise<HashedClientSecret> {
const salt = crypto.randomUUID()
const encoder = new TextEncoder()
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
'PBKDF2',
false,
['deriveBits'],
)
const hashBuffer = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt: encoder.encode(salt),
iterations: 100000,
hash: 'SHA-256',
},
keyMaterial,
256,
)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const hash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
return {
hash,
salt,
algorithm: 'pbkdf2' as const,
version: 1,
}
}
/**
* Verify a client secret against its hash.
*/
export async function verifyClientSecret(
secret: string,
storedHash: { hash: string; salt: string },
): Promise<boolean> {
const encoder = new TextEncoder()
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
'PBKDF2',
false,
['deriveBits'],
)
const hashBuffer = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt: encoder.encode(storedHash.salt),
iterations: 100000,
hash: 'SHA-256',
},
keyMaterial,
256,
)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const computedHash = hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
return computedHash === storedHash.hash
}
/**
* Alias for verifyClientSecret for backward compatibility.
*/
export const verifyClientSecretHash = verifyClientSecret
// ============ PKCE Code Verifier Encryption ============
const EncryptedVerifierSchema = z.object({
state: z.string(),
codeVerifier: z.string(),
})
/**
* Encrypt a PKCE code verifier before storing in database.
* Uses DWS KMS.
*/
export async function encryptCodeVerifier(
codeVerifier: string,
state: string,
): Promise<string> {
const config = getConfig()
const payload = JSON.stringify({ state, codeVerifier })
return getKmsService().encrypt(payload, config.jwtSignerAddress)
}
/**
* Decrypt a PKCE code verifier using the state parameter.
*/
export async function decryptCodeVerifier(
encryptedVerifier: string,
state: string,
): Promise<string> {
const config = getConfig()
const decrypted = await getKmsService().decrypt(
encryptedVerifier,
config.jwtSignerAddress,
)
const parsed = EncryptedVerifierSchema.parse(JSON.parse(decrypted))
if (parsed.state !== state) {
throw new Error('PKCE state mismatch')
}
return parsed.codeVerifier
}
// ============ Ephemeral Keys ============
interface EphemeralKey {
keyId: string
publicKey: Hex
createdAt: number
expiresAt: number
}
// Ephemeral key storage (per-session keys)
const ephemeralKeys = new Map<string, EphemeralKey>()
/**
* Get or create an ephemeral key for a session.
*/
export async function getEphemeralKey(
sessionId: string,
): Promise<EphemeralKey> {
// Check if we already have a key for this session
const existing = ephemeralKeys.get(sessionId)
if (existing && existing.expiresAt > Date.now()) {
return existing
}
// Create new ephemeral key with random public key
const keyId = `ephemeral-${sessionId}-${Date.now()}`
const now = Date.now()
const keyBytes = crypto.getRandomValues(new Uint8Array(32))
const ephemeralKey: EphemeralKey = {
keyId,
publicKey: toHex(keyBytes),
createdAt: now,
expiresAt: now + 24 * 60 * 60 * 1000, // 24 hours
}
ephemeralKeys.set(sessionId, ephemeralKey)
return ephemeralKey
}
/**
* Invalidate an ephemeral key.
*/
export function invalidateEphemeralKey(sessionId: string): void {
ephemeralKeys.delete(sessionId)
}
// ============ KMS Health ============
/**
* Get KMS health status.
*/
export function getKMSStatus(): {
healthy: boolean
mode: string
network: string
keys: number
initialized: boolean
} {
const config = kmsConfig
return {
healthy: kmsInitialized,
mode: 'dws',
network: config?.chainId ?? 'unknown',
keys: 0,
initialized: kmsInitialized,
}
}