server.ts65 lines · main
| 1 | /** |
| 2 | * @briven/auth/engine server helpers — briven-engine session on the server. |
| 3 | * |
| 4 | * import { getBrivenEngineServerSession } from '@briven/auth/engine/server'; |
| 5 | */ |
| 6 | |
| 7 | import { BRIVEN_ENGINE_ID } from './index.js'; |
| 8 | |
| 9 | export type BrivenEngineServerSession = |
| 10 | | { |
| 11 | authenticated: true; |
| 12 | userId: string; |
| 13 | sessionHandle?: string; |
| 14 | accessTokenPayload?: Record<string, unknown>; |
| 15 | engine: typeof BRIVEN_ENGINE_ID; |
| 16 | } |
| 17 | | { |
| 18 | authenticated: false; |
| 19 | engine: typeof BRIVEN_ENGINE_ID; |
| 20 | }; |
| 21 | |
| 22 | /** |
| 23 | * Validate session cookie via Briven API briven-engine session endpoint. |
| 24 | */ |
| 25 | export async function getBrivenEngineServerSession(opts: { |
| 26 | cookieHeader: string | null; |
| 27 | apiOrigin?: string; |
| 28 | projectId: string; |
| 29 | fetch?: typeof globalThis.fetch; |
| 30 | }): Promise<BrivenEngineServerSession | null> { |
| 31 | if (!opts.cookieHeader) return null; |
| 32 | const origin = (opts.apiOrigin ?? 'https://api.briven.tech').replace(/\/$/, ''); |
| 33 | const fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis); |
| 34 | try { |
| 35 | const res = await fetchFn(`${origin}/v1/auth-core/session/me`, { |
| 36 | method: 'GET', |
| 37 | headers: { |
| 38 | cookie: opts.cookieHeader, |
| 39 | 'x-briven-project-id': opts.projectId, |
| 40 | 'x-briven-engine': BRIVEN_ENGINE_ID, |
| 41 | }, |
| 42 | }); |
| 43 | if (!res.ok) { |
| 44 | return { authenticated: false, engine: BRIVEN_ENGINE_ID }; |
| 45 | } |
| 46 | const body = (await res.json()) as { |
| 47 | authenticated?: boolean; |
| 48 | userId?: string; |
| 49 | sessionHandle?: string; |
| 50 | accessTokenPayload?: Record<string, unknown>; |
| 51 | }; |
| 52 | if (body.authenticated && body.userId) { |
| 53 | return { |
| 54 | authenticated: true, |
| 55 | userId: body.userId, |
| 56 | sessionHandle: body.sessionHandle, |
| 57 | accessTokenPayload: body.accessTokenPayload, |
| 58 | engine: BRIVEN_ENGINE_ID, |
| 59 | }; |
| 60 | } |
| 61 | return { authenticated: false, engine: BRIVEN_ENGINE_ID }; |
| 62 | } catch { |
| 63 | return null; |
| 64 | } |
| 65 | } |