// 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(';')) { // Spaces and tabs come off a pair and nothing else, so a name is read as it stands. let from = 0; let to = part.length; while (from < to && (part.charCodeAt(from) === 0x20 || part.charCodeAt(from) === 0x09)) from += 1; while (to > from && (part.charCodeAt(to - 1) === 0x20 || part.charCodeAt(to - 1) === 0x09)) to -= 1; const pair = part.slice(from, to); const at = pair.indexOf('='); if (at > 0 && pair.slice(0, at) === SESSION_COOKIE) return pair.slice(at + 1); } 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; }; }