aboutsummaryrefslogtreecommitdiff
path: root/supabase/functions/validate-api-key/index.ts
blob: d426b7efdb857cafc3488341d66f4f855183053f (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
import { createClient } from "jsr:@supabase/supabase-js@2";

const corsHeaders = {
	"Access-Control-Allow-Origin": "*",
	"Access-Control-Allow-Headers":
		"authorization, x-client-info, apikey, content-type",
};

Deno.serve(async (request) => {
	if (request.method === "OPTIONS") {
		return new Response("ok", { headers: corsHeaders });
	}

	try {
		const { apiKey } = await request.json();

		if (!apiKey || !apiKey.startsWith("imemio_")) {
			return new Response(JSON.stringify({ error: "Invalid API key format" }), {
				status: 400,
				headers: { ...corsHeaders, "Content-Type": "application/json" },
			});
		}

		const encoder = new TextEncoder();
		const data = encoder.encode(apiKey);
		const hashBuffer = await crypto.subtle.digest("SHA-256", data);
		const hashArray = Array.from(new Uint8Array(hashBuffer));
		const keyHash = hashArray
			.map((byte) => byte.toString(16).padStart(2, "0"))
			.join("");
		const supabaseUrl = Deno.env.get("SUPABASE_URL");
		const supabaseServiceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");

		if (!supabaseUrl || !supabaseServiceKey) {
			return new Response(
				JSON.stringify({ error: "Server configuration error" }),
				{
					status: 500,
					headers: { ...corsHeaders, "Content-Type": "application/json" },
				},
			);
		}

		const supabase = createClient(supabaseUrl, supabaseServiceKey);
		const { data: result, error } = await supabase.rpc("validate_api_key", {
			api_key_hash: keyHash,
		});

		if (error || !result || result.length === 0) {
			return new Response(
				JSON.stringify({ error: "Invalid or revoked API key" }),
				{
					status: 401,
					headers: { ...corsHeaders, "Content-Type": "application/json" },
				},
			);
		}

		const { user_id: userId, api_key_id: apiKeyId } = result[0];

		supabase.rpc("update_api_key_last_used", { p_api_key_id: apiKeyId });

		return new Response(JSON.stringify({ userId, apiKeyId }), {
			status: 200,
			headers: { ...corsHeaders, "Content-Type": "application/json" },
		});
	} catch {
		return new Response(JSON.stringify({ error: "Internal server error" }), {
			status: 500,
			headers: { ...corsHeaders, "Content-Type": "application/json" },
		});
	}
});