|
| 1 | +import { Router, Response } from 'express'; |
| 2 | +import crypto from 'crypto'; |
| 3 | +import { supabase } from '../config/database'; |
| 4 | +import { authenticate, AuthenticatedRequest, requireScope } from '../middleware/auth'; |
| 5 | +import logger from '../config/logger'; |
| 6 | + |
| 7 | +const router = Router(); |
| 8 | + |
| 9 | +// All endpoints are for authenticated users (JWT or API key edit rights via user auth). |
| 10 | +router.use(authenticate); |
| 11 | + |
| 12 | +const VALID_SCOPES = new Set(["subscriptions:read", "subscriptions:write", "webhooks:write", "analytics:read"]); |
| 13 | + |
| 14 | +function normalizeScopes(scopes: unknown): string[] { |
| 15 | + if (Array.isArray(scopes)) { |
| 16 | + return scopes |
| 17 | + .map((scope) => String(scope || '').trim()) |
| 18 | + .filter((scope) => scope && VALID_SCOPES.has(scope)); |
| 19 | + } |
| 20 | + |
| 21 | + if (typeof scopes === 'string') { |
| 22 | + return scopes |
| 23 | + .split(',') |
| 24 | + .map((scope) => scope.trim()) |
| 25 | + .filter((scope) => scope && VALID_SCOPES.has(scope)); |
| 26 | + } |
| 27 | + |
| 28 | + return []; |
| 29 | +} |
| 30 | + |
| 31 | +function generateApiKey(): { key: string; hash: string } { |
| 32 | + const key = `sk_${crypto.randomBytes(32).toString('hex')}`; |
| 33 | + const hash = crypto.createHash('sha256').update(key).digest('hex'); |
| 34 | + return { key, hash }; |
| 35 | +} |
| 36 | + |
| 37 | +router.post('/', requireScope('subscriptions:write'), async (req: AuthenticatedRequest, res: Response) => { |
| 38 | + try { |
| 39 | + if (!req.user?.id) { |
| 40 | + return res.status(401).json({ error: 'Unauthorized' }); |
| 41 | + } |
| 42 | + |
| 43 | + const { name, scopes } = req.body || {}; |
| 44 | + |
| 45 | + const serviceName = String(name || 'default').trim(); |
| 46 | + if (!serviceName) { |
| 47 | + return res.status(400).json({ error: 'service name is required' }); |
| 48 | + } |
| 49 | + |
| 50 | + const normalizedScopes = normalizeScopes(scopes); |
| 51 | + if (normalizedScopes.length === 0) { |
| 52 | + return res.status(400).json({ error: 'at least one valid scope is required' }); |
| 53 | + } |
| 54 | + |
| 55 | + const { key, hash } = generateApiKey(); |
| 56 | + |
| 57 | + let insertResult: any; |
| 58 | + try { |
| 59 | + insertResult = await supabase.from('api_keys').insert([ |
| 60 | + { |
| 61 | + user_id: req.user.id, |
| 62 | + service_name: serviceName, |
| 63 | + key_hash: hash, |
| 64 | + scopes: normalizedScopes, |
| 65 | + revoked: false, |
| 66 | + last_used_at: null, |
| 67 | + request_count: 0, |
| 68 | + }, |
| 69 | + ]); |
| 70 | + } catch (dbError) { |
| 71 | + logger.error('insert call threw', dbError); |
| 72 | + throw dbError; |
| 73 | + } |
| 74 | + |
| 75 | + const error = (insertResult as any).error; |
| 76 | + |
| 77 | + if (error) { |
| 78 | + logger.error('Failed to create API key', { error }); |
| 79 | + return res.status(500).json({ error: 'Failed to create API key' }); |
| 80 | + } |
| 81 | + |
| 82 | + console.log('about to send success response'); |
| 83 | + return res.status(201).json({ success: true, key, scopes: normalizedScopes }); |
| 84 | + } catch (error) { |
| 85 | + logger.error('Create API key error:', error); |
| 86 | + console.error('Create API key error:', error); |
| 87 | + return res.status(500).json({ error: String(error) || 'Internal server error' }); |
| 88 | + } |
| 89 | +}); |
| 90 | + |
| 91 | +router.get('/', requireScope('subscriptions:read'), async (req: AuthenticatedRequest, res: Response) => { |
| 92 | + try { |
| 93 | + if (!req.user?.id) { |
| 94 | + return res.status(401).json({ error: 'Unauthorized' }); |
| 95 | + } |
| 96 | + |
| 97 | + const { data, error } = await supabase |
| 98 | + .from('api_keys') |
| 99 | + .select('id, service_name, scopes, revoked, created_at, updated_at, last_used_at, request_count') |
| 100 | + .eq('user_id', req.user.id) |
| 101 | + .order('created_at', { ascending: false }); |
| 102 | + |
| 103 | + if (error) { |
| 104 | + logger.error('Failed to list API keys', { error }); |
| 105 | + return res.status(500).json({ error: 'Failed to list API keys' }); |
| 106 | + } |
| 107 | + |
| 108 | + return res.json({ success: true, data }); |
| 109 | + } catch (error) { |
| 110 | + logger.error('List API keys error:', error); |
| 111 | + return res.status(500).json({ error: 'Internal server error' }); |
| 112 | + } |
| 113 | +}); |
| 114 | + |
| 115 | +router.delete('/:id', requireScope('subscriptions:write'), async (req: AuthenticatedRequest, res: Response) => { |
| 116 | + try { |
| 117 | + if (!req.user?.id) { |
| 118 | + return res.status(401).json({ error: 'Unauthorized' }); |
| 119 | + } |
| 120 | + |
| 121 | + const keyId = req.params.id; |
| 122 | + |
| 123 | + const { data: existingKey, error: fetchError } = await supabase |
| 124 | + .from('api_keys') |
| 125 | + .select('id') |
| 126 | + .eq('id', keyId) |
| 127 | + .eq('user_id', req.user.id) |
| 128 | + .single(); |
| 129 | + |
| 130 | + if (fetchError || !existingKey) { |
| 131 | + return res.status(404).json({ error: 'API key not found' }); |
| 132 | + } |
| 133 | + |
| 134 | + const { error } = await supabase |
| 135 | + .from('api_keys') |
| 136 | + .update({ revoked: true, updated_at: new Date().toISOString() }) |
| 137 | + .eq('id', keyId) |
| 138 | + .eq('user_id', req.user.id); |
| 139 | + |
| 140 | + if (error) { |
| 141 | + logger.error('Failed to revoke API key', { error }); |
| 142 | + return res.status(500).json({ error: 'Failed to revoke API key' }); |
| 143 | + } |
| 144 | + |
| 145 | + return res.json({ success: true }); |
| 146 | + } catch (error) { |
| 147 | + logger.error('Revoke API key error:', error); |
| 148 | + return res.status(500).json({ error: 'Internal server error' }); |
| 149 | + } |
| 150 | +}); |
| 151 | + |
| 152 | +router.get('/:id/usage', requireScope('subscriptions:read'), async (req: AuthenticatedRequest, res: Response) => { |
| 153 | + try { |
| 154 | + if (!req.user?.id) { |
| 155 | + return res.status(401).json({ error: 'Unauthorized' }); |
| 156 | + } |
| 157 | + |
| 158 | + const keyId = req.params.id; |
| 159 | + |
| 160 | + const { data, error } = await supabase |
| 161 | + .from('api_keys') |
| 162 | + .select('id, service_name, scopes, revoked, created_at, updated_at, last_used_at, request_count') |
| 163 | + .eq('id', keyId) |
| 164 | + .eq('user_id', req.user.id) |
| 165 | + .single(); |
| 166 | + |
| 167 | + if (error || !data) { |
| 168 | + logger.error('Failed to fetch API key usage', { error }); |
| 169 | + return res.status(404).json({ error: 'API key not found' }); |
| 170 | + } |
| 171 | + |
| 172 | + return res.json({ success: true, data }); |
| 173 | + } catch (error) { |
| 174 | + logger.error('API key usage error:', error); |
| 175 | + return res.status(500).json({ error: 'Internal server error' }); |
| 176 | + } |
| 177 | +}); |
| 178 | + |
| 179 | +export default router; |
0 commit comments