// src/session.mjs: the signed-in user who sent a request, as the guide Add // sign-in to your app shows it. import { makeVerifyClient } from '@turnzero/account'; // The cookie a signed-in browser sends with each request to the application's address. const SESSION_COOKIE = '__Host-turnzero_cloud_realm'; // The live client, which only the process entry opens. A deployed copy // receives all three settings. A local run has no TURNZERO_CLOUD_REALM_KEYS, // so the client is built without keys there and verifies through the // platform's route. Where the credential is not set, the start stops and // says which line writes it. export function openLiveAccounts() { const keys = process.env.TURNZERO_CLOUD_REALM_KEYS; if (!process.env.TURNZERO_CLOUD_APP_TOKEN) throw new Error('TURNZERO_CLOUD_APP_TOKEN is not set, so no session can be verified. Run the provision line again, then start the app again.'); return makeVerifyClient({ baseUrl: process.env.TURNZERO_CLOUD_API, credential: process.env.TURNZERO_CLOUD_APP_TOKEN, ...(keys ? { realmKeys: keys } : {}), }); } // The session token: the cookie's value from a browser, or the bearer from a // native app or a local run. export function sessionOf(request) { const auth = request.headers.authorization ?? ''; if (auth.startsWith('Bearer ')) return auth.slice('Bearer '.length); for (const part of (request.headers.cookie ?? '').split(';')) { const at = part.indexOf('='); if (at > 0 && part.slice(0, at).trim() === SESSION_COOKIE) return part.slice(at + 1).trim(); } return null; } // The reader of a request's user: the signed-in user's id, or null with no // live session. The token is verified by the Account package's client, with // the x-turnzero-cloud-session header the serving router sets on each // request it forwards. export function createUserReader(accounts) { return async (request) => { const verdict = await accounts.verifySession(sessionOf(request), { sessionHeader: request.headers['x-turnzero-cloud-session'] ?? null, }); return 'user' in verdict ? verdict.user.id : null; }; }