"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SupabaseAuthService = void 0;
const logger_1 = require("../utils/logger");
const log = (0, logger_1.createLogger)('SupabaseAuthService');
/**
 * Minimal, dependency-free verifier for Rivet (Supabase) JWTs.
 *
 * The proxy (`src/proxy`) verifies tokens with `@supabase/supabase-js`, but that
 * package and the whole `src/proxy` tree are excluded from the main `tsc` build.
 * The Prototype Preview Host is part of the main build, so it can't reuse that
 * service. Instead we hit Supabase's GoTrue REST endpoint directly with `fetch`
 * — exactly what `supabase.auth.getUser(token)` does under the hood — using the
 * same `SUPABASE_URL` / `SUPABASE_ANON_KEY` the proxy already holds.
 */
class SupabaseAuthService {
    url;
    anonKey;
    constructor(opts) {
        const url = opts?.url ?? process.env.SUPABASE_URL;
        const anonKey = opts?.anonKey ?? process.env.SUPABASE_ANON_KEY;
        if (!url || !anonKey) {
            throw new Error('SUPABASE_URL and SUPABASE_ANON_KEY must be set to verify auth tokens');
        }
        this.url = url.replace(/\/+$/, '');
        this.anonKey = anonKey;
    }
    /** Returns the user for a valid JWT, or null when the token is missing/invalid. */
    async verifyToken(token) {
        if (!token)
            return null;
        try {
            const res = await fetch(`${this.url}/auth/v1/user`, {
                headers: {
                    apikey: this.anonKey,
                    Authorization: `Bearer ${token}`,
                },
                signal: AbortSignal.timeout(10_000),
            });
            if (!res.ok) {
                log.debug(`Token verification failed (${res.status})`);
                return null;
            }
            const user = (await res.json());
            if (!user?.id)
                return null;
            return { id: user.id, email: user.email };
        }
        catch (err) {
            log.warn('Error verifying token', err);
            return null;
        }
    }
}
exports.SupabaseAuthService = SupabaseAuthService;
//# sourceMappingURL=SupabaseAuthService.js.map