briven-ai.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Briven AI agent tokens (brai_…) — server only.
  3. * GET /v1/auth-core/ai/me
  4. * Never put brai_ in NEXT_PUBLIC_* or the browser.
  5. */
  6. function apiOrigin(): string {
  7. return (
  8. process.env.BRIVEN_API_ORIGIN?.trim() ||
  9. process.env.NEXT_PUBLIC_BRIVEN_API_ORIGIN?.trim() ||
  10. "https://api.briven.tech"
  11. );
  12. }
  13. export function isAiAgentConfigured(): boolean {
  14. const key = process.env.BRIVEN_AI_AGENT_KEY?.trim() ?? "";
  15. return key.startsWith("brai_");
  16. }
  17. export type AiAgentMe = {
  18. ok: boolean;
  19. status: number;
  20. /** Safe subset for UI / logs */
  21. summary: Record<string, unknown>;
  22. error?: string;
  23. };
  24. export async function getBrivenAiAgentMe(): Promise<AiAgentMe> {
  25. const key = process.env.BRIVEN_AI_AGENT_KEY?.trim();
  26. if (!key?.startsWith("brai_")) {
  27. return {
  28. ok: false,
  29. status: 0,
  30. summary: {},
  31. error: "BRIVEN_AI_AGENT_KEY missing or invalid shape",
  32. };
  33. }
  34. const res = await fetch(`${apiOrigin()}/v1/auth-core/ai/me`, {
  35. headers: {
  36. authorization: `Bearer ${key}`,
  37. accept: "application/json",
  38. },
  39. cache: "no-store",
  40. });
  41. const text = await res.text();
  42. let data: Record<string, unknown> = {};
  43. try {
  44. data = JSON.parse(text) as Record<string, unknown>;
  45. } catch {
  46. data = { raw: text.slice(0, 120) };
  47. }
  48. // Strip anything that looks like a secret
  49. const summary: Record<string, unknown> = {};
  50. for (const [k, v] of Object.entries(data)) {
  51. if (/secret|token|key|password/i.test(k)) continue;
  52. if (typeof v === "string" && v.length > 80) {
  53. summary[k] = `${v.slice(0, 24)}…`;
  54. } else {
  55. summary[k] = v;
  56. }
  57. }
  58. return {
  59. ok: res.ok,
  60. status: res.status,
  61. summary,
  62. error: res.ok ? undefined : text.slice(0, 200),
  63. };
  64. }