auth.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { createBrivenAuth, type BrivenAuthClient } from "@briven/auth";
  2. import {
  3. getBrivenAuthPublicKey,
  4. getBrivenProjectId,
  5. isBrivenAuthConfigured,
  6. } from "@/lib/auth-config";
  7. /**
  8. * First-party origin for the browser SDK.
  9. * Browser must NOT call api.briven.tech directly (CORS → "network error").
  10. * Calls go: same host /api/auth/* → route proxy → Briven FDI.
  11. */
  12. function getAuthApiOrigin(): string {
  13. // Browser: same origin + /api/auth (route handler proxies FDI)
  14. if (typeof window !== "undefined") {
  15. const optOut =
  16. process.env.NEXT_PUBLIC_BRIVEN_AUTH_FIRST_PARTY === "0";
  17. if (!optOut) {
  18. return `${window.location.origin}/api/auth`;
  19. }
  20. }
  21. // Server-side SDK use (rare): talk to Briven directly
  22. return (
  23. process.env.BRIVEN_API_ORIGIN ||
  24. process.env.NEXT_PUBLIC_BRIVEN_API_ORIGIN ||
  25. "https://api.briven.tech"
  26. ).replace(/\/$/, "");
  27. }
  28. /**
  29. * Stateless Briven client. Session cookies set via first-party proxy.
  30. * https://docs.briven.tech/auth
  31. */
  32. export function getBrivenAuth(): BrivenAuthClient | null {
  33. if (!isBrivenAuthConfigured()) return null;
  34. const projectId = getBrivenProjectId()!;
  35. const publicKey = getBrivenAuthPublicKey()!;
  36. return createBrivenAuth({
  37. projectId,
  38. publicKey,
  39. apiOrigin: getAuthApiOrigin(),
  40. });
  41. }
  42. /** Scaffold-compatible export — may be null until keys are set. */
  43. export const auth = getBrivenAuth();