|
| 1 | +import * as jose from 'jose'; |
| 2 | +import * as fs from 'node:fs/promises'; |
| 3 | +import * as yaml from 'yaml'; |
| 4 | + |
| 5 | +export interface CredentialsOptions { |
| 6 | + token?: string; |
| 7 | + endpoint?: string; |
| 8 | + config?: string; |
| 9 | + sub?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export async function getCredentials(options: CredentialsOptions): Promise<{ endpoint: string; token: string }> { |
| 13 | + if (options.token != null) { |
| 14 | + if (options.endpoint != null) { |
| 15 | + return { token: options.token, endpoint: options.endpoint }; |
| 16 | + } else { |
| 17 | + const parsed = jose.decodeJwt(options.token); |
| 18 | + const aud = Array.isArray(parsed.aud) ? parsed.aud[0] : parsed.aud; |
| 19 | + if (!(aud ?? '').startsWith('http')) { |
| 20 | + throw new Error(`Specify endpoint, or aud in the token`); |
| 21 | + } |
| 22 | + return { |
| 23 | + token: options.token, |
| 24 | + endpoint: aud! |
| 25 | + }; |
| 26 | + } |
| 27 | + } else if (options.config != null) { |
| 28 | + const file = await fs.readFile(options.config, 'utf-8'); |
| 29 | + const parsed = await yaml.parse(file); |
| 30 | + const keys = (parsed.client_auth?.jwks?.keys ?? []).filter((key: any) => key.alg == 'HS256'); |
| 31 | + if (keys.length == 0) { |
| 32 | + throw new Error('No HS256 key found in the config'); |
| 33 | + } |
| 34 | + |
| 35 | + let endpoint = options.endpoint; |
| 36 | + if (endpoint == null) { |
| 37 | + endpoint = `http://127.0.0.1:${parsed.port ?? 8080}`; |
| 38 | + } |
| 39 | + |
| 40 | + const aud = parsed.client_auth?.audience?.[0] ?? endpoint; |
| 41 | + |
| 42 | + const rawKey = keys[0]; |
| 43 | + const key = await jose.importJWK(rawKey); |
| 44 | + |
| 45 | + const sub = options.sub ?? 'test_user'; |
| 46 | + |
| 47 | + const token = await new jose.SignJWT({}) |
| 48 | + .setProtectedHeader({ alg: rawKey.alg, kid: rawKey.kid }) |
| 49 | + .setSubject(sub) |
| 50 | + .setIssuedAt() |
| 51 | + .setIssuer('test-client') |
| 52 | + .setAudience(aud) |
| 53 | + .setExpirationTime('1h') |
| 54 | + .sign(key); |
| 55 | + |
| 56 | + return { token, endpoint }; |
| 57 | + } else { |
| 58 | + throw new Error(`Specify token or config path`); |
| 59 | + } |
| 60 | +} |
0 commit comments