summaryrefslogtreecommitdiff
path: root/apps/web/lib/api-auth.ts
blob: 7c1d009afe828fcea42524bb948f60216ec6757a (plain) (blame)
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
import { createSupabaseAdminClient } from "@/lib/supabase/admin"
import { hashApiKey } from "@/lib/api-key"
import { rateLimit } from "@/lib/rate-limit"

interface AuthenticatedApiUser {
  userIdentifier: string
  tier: string
}

export async function authenticateApiRequest(
  request: Request
): Promise<
  | { authenticated: true; user: AuthenticatedApiUser }
  | { authenticated: false; status: number; error: string }
> {
  const authorizationHeader = request.headers.get("authorization")

  if (!authorizationHeader?.startsWith("Bearer ")) {
    return {
      authenticated: false,
      status: 401,
      error: "missing or invalid authorization header",
    }
  }

  const apiKey = authorizationHeader.slice(7)

  if (!apiKey.startsWith("asa_")) {
    return { authenticated: false, status: 401, error: "invalid api key format" }
  }

  const keyHash = hashApiKey(apiKey)
  const adminClient = createSupabaseAdminClient()

  const { data: keyRow } = await adminClient
    .from("api_keys")
    .select("user_id")
    .eq("key_hash", keyHash)
    .is("revoked_at", null)
    .single()

  if (!keyRow) {
    return { authenticated: false, status: 401, error: "invalid or revoked api key" }
  }

  const { data: userProfile } = await adminClient
    .from("user_profiles")
    .select("tier")
    .eq("id", keyRow.user_id)
    .single()

  if (!userProfile || userProfile.tier !== "developer") {
    return {
      authenticated: false,
      status: 403,
      error: "api access requires the developer plan",
    }
  }

  const rateLimitResult = await rateLimit(`api:${keyRow.user_id}`, 100, 60_000)

  if (!rateLimitResult.success) {
    return {
      authenticated: false,
      status: 429,
      error: `rate limit exceeded. ${rateLimitResult.remaining} requests remaining.`,
    }
  }

  adminClient
    .from("api_keys")
    .update({ last_used_at: new Date().toISOString() })
    .eq("key_hash", keyHash)
    .then(({ error: updateError }) => {
      if (updateError) {
        console.error("failed to update api key last_used_at:", updateError)
      }
    })

  return {
    authenticated: true,
    user: { userIdentifier: keyRow.user_id, tier: userProfile.tier },
  }
}