Files
accounted/app/api/settings/api-keys/route.ts
T
MattssonandClaude Opus 4.6 bb473e2c57 Worktree api key scopes (#139)
* feat: add read/write scopes to API keys

API keys now require explicit scopes (e.g. transactions:read,
invoices:write) instead of having implicit full access. The create
dialog shows grouped checkboxes per domain with read/write split.
Legacy keys with null scopes default to read-only. MCP tools/list
is filtered by scope and tools/call rejects unauthorized calls.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Enhance API key scopes with suppliers and update descriptions for better clarity

* fix: drop function before recreating with changed return type

PostgreSQL cannot change return type via CREATE OR REPLACE.
Drop the existing function first to avoid SQLSTATE 42P13.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add new migration to drop and recreate function with scopes return type

The original migration was already applied, so a new migration is needed
to DROP the function first before recreating with the updated return type.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add DROP FUNCTION to original migration, remove redundant fix migration

Preview branches replay all migrations from scratch. The original migration
must DROP the function before recreating it with a changed return type,
otherwise PostgreSQL rejects the CREATE OR REPLACE. The separate fix
migration is no longer needed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: rename migration to avoid duplicate version in schema_migrations

Version 20260325120000 is already recorded in the preview DB from a
prior failed apply. Renaming to 20260326130000 so Supabase treats it
as a new migration.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 13:30:26 +01:00

97 lines
2.5 KiB
TypeScript

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateApiKey, hashApiKey, DEFAULT_SCOPES, validateScopes } from '@/lib/auth/api-keys'
import type { ApiKeyScope } from '@/lib/auth/api-keys'
/**
* GET /api/settings/api-keys — List user's API keys (never exposes the key itself)
*/
export async function GET() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { data, error } = await supabase
.from('api_keys')
.select('id, key_prefix, name, scopes, rate_limit_rpm, last_used_at, revoked_at, created_at')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json({ data })
}
/**
* POST /api/settings/api-keys — Create a new API key
* Returns the full key ONCE. After this, only the prefix is available.
*/
export async function POST(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
let name = 'Unnamed key'
let scopes: ApiKeyScope[] = DEFAULT_SCOPES
try {
const body = await request.json()
if (body.name && typeof body.name === 'string') {
name = body.name.slice(0, 100)
}
const parsed = validateScopes(body.scopes)
if (parsed) {
scopes = parsed
}
} catch {
// Empty body is fine, use defaults
}
// Limit to 10 active keys per user
const { count } = await supabase
.from('api_keys')
.select('id', { count: 'exact', head: true })
.eq('user_id', user.id)
.is('revoked_at', null)
if (count !== null && count >= 10) {
return NextResponse.json(
{ error: 'Maximum 10 active API keys allowed' },
{ status: 400 }
)
}
const { key, hash, prefix } = generateApiKey()
const { data, error } = await supabase
.from('api_keys')
.insert({
user_id: user.id,
key_hash: hash,
key_prefix: prefix,
name,
scopes,
})
.select('id, key_prefix, name, scopes, created_at')
.single()
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
// Return the full key exactly once
return NextResponse.json({
data: {
...data,
key, // Only time the full key is returned
},
})
}