|
| 1 | +import { sql } from './client'; |
| 2 | + |
| 3 | +export interface ApiKey { |
| 4 | + id: string; |
| 5 | + userId: string; |
| 6 | + name: string; |
| 7 | + tokenPrefix: string; |
| 8 | + lastUsedAt: Date | null; |
| 9 | + expiresAt: Date | null; |
| 10 | + createdAt: Date; |
| 11 | +} |
| 12 | + |
| 13 | +interface ApiKeyRow { |
| 14 | + id: string; |
| 15 | + user_id: string; |
| 16 | + name: string; |
| 17 | + token_prefix: string; |
| 18 | + last_used_at: string | null; |
| 19 | + expires_at: string | null; |
| 20 | + created_at: string; |
| 21 | +} |
| 22 | + |
| 23 | +function rowToApiKey(row: ApiKeyRow): ApiKey { |
| 24 | + return { |
| 25 | + id: row.id, |
| 26 | + userId: row.user_id, |
| 27 | + name: row.name, |
| 28 | + tokenPrefix: row.token_prefix, |
| 29 | + lastUsedAt: row.last_used_at ? new Date(row.last_used_at) : null, |
| 30 | + expiresAt: row.expires_at ? new Date(row.expires_at) : null, |
| 31 | + createdAt: new Date(row.created_at) |
| 32 | + }; |
| 33 | +} |
| 34 | + |
| 35 | +// Generate a random API key token |
| 36 | +function generateToken(): string { |
| 37 | + const bytes = new Uint8Array(24); |
| 38 | + crypto.getRandomValues(bytes); |
| 39 | + const random = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''); |
| 40 | + return `ow_${random}`; |
| 41 | +} |
| 42 | + |
| 43 | +// Hash token using SHA-256 |
| 44 | +async function hashToken(token: string): Promise<string> { |
| 45 | + const encoder = new TextEncoder(); |
| 46 | + const data = encoder.encode(token); |
| 47 | + const hashBuffer = await crypto.subtle.digest('SHA-256', data); |
| 48 | + const hashArray = Array.from(new Uint8Array(hashBuffer)); |
| 49 | + return hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); |
| 50 | +} |
| 51 | + |
| 52 | +// Create a new API key - returns the full token (only time it's available) |
| 53 | +export async function createApiKey( |
| 54 | + userId: string, |
| 55 | + name: string, |
| 56 | + expiresAt?: Date |
| 57 | +): Promise<{ apiKey: ApiKey; token: string }> { |
| 58 | + const token = generateToken(); |
| 59 | + const tokenPrefix = token.substring(0, 12); |
| 60 | + const tokenHash = await hashToken(token); |
| 61 | + |
| 62 | + const rows = await sql<ApiKeyRow>( |
| 63 | + `INSERT INTO api_keys (user_id, name, token_prefix, token_hash, expires_at) |
| 64 | + VALUES ($1::uuid, $2, $3, $4, $5::timestamptz) |
| 65 | + RETURNING id, user_id, name, token_prefix, last_used_at, expires_at, created_at`, |
| 66 | + [userId, name, tokenPrefix, tokenHash, expiresAt?.toISOString() ?? null] |
| 67 | + ); |
| 68 | + |
| 69 | + return { |
| 70 | + apiKey: rowToApiKey(rows[0]!), |
| 71 | + token |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +// Find API key by token (for authentication) |
| 76 | +export async function findApiKeyByToken(token: string): Promise<ApiKey | null> { |
| 77 | + const tokenHash = await hashToken(token); |
| 78 | + |
| 79 | + const rows = await sql<ApiKeyRow>( |
| 80 | + `SELECT id, user_id, name, token_prefix, last_used_at, expires_at, created_at |
| 81 | + FROM api_keys |
| 82 | + WHERE token_hash = $1 AND (expires_at IS NULL OR expires_at > NOW())`, |
| 83 | + [tokenHash] |
| 84 | + ); |
| 85 | + |
| 86 | + return rows[0] ? rowToApiKey(rows[0]) : null; |
| 87 | +} |
| 88 | + |
| 89 | +// List user's API keys |
| 90 | +export async function listApiKeys(userId: string): Promise<ApiKey[]> { |
| 91 | + const rows = await sql<ApiKeyRow>( |
| 92 | + `SELECT id, user_id, name, token_prefix, last_used_at, expires_at, created_at |
| 93 | + FROM api_keys |
| 94 | + WHERE user_id = $1::uuid |
| 95 | + ORDER BY created_at DESC`, |
| 96 | + [userId] |
| 97 | + ); |
| 98 | + |
| 99 | + return rows.map(rowToApiKey); |
| 100 | +} |
| 101 | + |
| 102 | +// Delete an API key |
| 103 | +export async function deleteApiKey(userId: string, keyId: string): Promise<boolean> { |
| 104 | + const result = await sql<{ count: string }>( |
| 105 | + `WITH deleted AS ( |
| 106 | + DELETE FROM api_keys WHERE id = $1::uuid AND user_id = $2::uuid RETURNING * |
| 107 | + ) |
| 108 | + SELECT COUNT(*) as count FROM deleted`, |
| 109 | + [keyId, userId] |
| 110 | + ); |
| 111 | + |
| 112 | + return parseInt(result[0]?.count ?? '0', 10) > 0; |
| 113 | +} |
| 114 | + |
| 115 | +// Update last used timestamp |
| 116 | +export async function updateApiKeyLastUsed(keyId: string): Promise<void> { |
| 117 | + await sql( |
| 118 | + `UPDATE api_keys SET last_used_at = NOW() WHERE id = $1::uuid`, |
| 119 | + [keyId] |
| 120 | + ); |
| 121 | +} |
0 commit comments