diff --git a/.env.example b/.env.example index 1b248e2..050cc5e 100644 --- a/.env.example +++ b/.env.example @@ -77,6 +77,19 @@ FRED_API_KEY= NEWSAPI_KEY= METACULUS_API_KEY= +# --- Connect: OAuth sign-in (OPTIONAL) --- +# Lets a block that reads your own Google data (Calendar, Drive, YouTube) +# sign in with read-only access. Register an OAuth client of type "Web +# application" in Google Cloud and add the redirect URI +# /api/oauth/google/callback +# (http://127.0.0.1:3000/api/oauth/google/callback for `npm run dev`). +# Server-side only; the secret never reaches the browser. The access token +# goes to the page that asked, for that session. Off in the public preview. +# OMNI_OAUTH_ORIGIN pins the redirect origin when a proxy hides it. +OMNI_GOOGLE_CLIENT_ID= +OMNI_GOOGLE_CLIENT_SECRET= +OMNI_OAUTH_ORIGIN= + # --- Inference ledger (OPTIONAL) --- # Durable server-side record of LLM executions. Postgres owns ONLY this; # canvas state stays in IndexedDB. Leave DATABASE_URL blank and the ledger diff --git a/APEX_PLAN.md b/APEX_PLAN.md index cce7725..afdd216 100644 --- a/APEX_PLAN.md +++ b/APEX_PLAN.md @@ -98,3 +98,7 @@ this order: 8. **Connect.** OAuth sign-in for providers that require it, Google first (504 directory APIs are blocked only by OAuth). Needs an OAuth client the owner registers. + Status: implemented and tested with stubs, for Google, read operations + with read-only scopes only. No live sign-in has been run (no client is + registered). The API index still counts Google APIs as unusable until it + is rebuilt (`npm run catalog:build`). diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index e87f790..d2a316d 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -174,6 +174,26 @@ and the 5-minute shared cache are per process, and a caller is the address `clientKey()` sees. The public preview runs no broker, so it uses no house key; turning one on there is an owner decision under this checklist. +### Connect (OAuth sign-in) + +`OMNI_GOOGLE_CLIENT_ID` and `OMNI_GOOGLE_CLIENT_SECRET` turn on "Sign in with +Google" for blocks that read the person's own Google data +(`src/core/services/server/oauthConnect.ts`). To set it up: + +1. In Google Cloud, enable each API you want (Calendar, Drive, YouTube Data). +2. Configure the OAuth consent screen. While it is in Testing, only the test + users you list can sign in, and Google shows them an unverified-app notice. +3. Create an OAuth client of type "Web application" with the authorized + redirect URI `/api/oauth/google/callback`. Set `OMNI_OAUTH_ORIGIN` + when the server cannot see its public origin. + +Flyspace only asks for scopes ending in `.readonly`, checks that the person +granted them, requests no refresh token, and stores nothing on the server. The +access token goes to the page that started the sign-in and lasts that session +(about an hour); the device vault never keeps it. The public preview has no +sign-in. Anyone who can reach a deployment with a client configured can sign +in to their own Google account through it, so keep it on a private network. + Hosted inference also requires `DATABASE_URL` and migration 003. Each paid request carries `Idempotency-Key`; the ledger stores owner, key, and digest with the `running` attempt before provider dispatch. Reusing a key with the diff --git a/src/app/CitadelApp.tsx b/src/app/CitadelApp.tsx index fafa532..f042ef5 100644 --- a/src/app/CitadelApp.tsx +++ b/src/app/CitadelApp.tsx @@ -19,6 +19,7 @@ import { useMindShellSync, useShellNavigation } from '@/core/hooks'; import { VoiceControl } from '@/components/voice/VoiceControl'; import { startKeyVault } from '@/core/capabilities/keyVault'; import { loadHouseKeys } from '@/core/capabilities/houseKeys'; +import { loadConnectProviders } from '@/core/capabilities/connect'; export default function CitadelApp() { // The removed API Dashboard stored client-side keys under this key; drop any that remain. @@ -34,6 +35,7 @@ export default function CitadelApp() { // Which curated APIs this server answers on its own key, if the owner set any. useEffect(() => { void loadHouseKeys(); + void loadConnectProviders(); }, []); const { activeTool, selection, captureSelection, clearSelection } = useToolStore(); diff --git a/src/app/api/oauth/[provider]/callback/route.ts b/src/app/api/oauth/[provider]/callback/route.ts new file mode 100644 index 0000000..7a2fb60 --- /dev/null +++ b/src/app/api/oauth/[provider]/callback/route.ts @@ -0,0 +1,35 @@ +// GET /api/oauth/:provider/callback +// Where the provider returns the browser (oauthConnect.ts). Exchanges the +// code with the owner's client secret, checks the granted scopes, and hands +// the token to the page that started the sign-in. Nothing is stored or logged. + +import { NextRequest, NextResponse } from 'next/server'; +import { callbackPage, CONNECT_COOKIE, CONNECT_COOKIE_PATH, finishConnect } from '@/core/services/server/oauthConnect'; +import { redirectUriFor } from '../redirectUri'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +export async function GET(request: NextRequest, context: { params: Promise<{ provider: string }> }) { + const { provider } = await context.params; + const result = await finishConnect({ + providerId: provider, + query: new URL(request.url).searchParams, + cookie: request.cookies.get(CONNECT_COOKIE)?.value, + redirectUri: redirectUriFor(request, provider) + }); + const page = callbackPage(result); + const response = new NextResponse(page.html, { + status: result.ok ? 200 : 400, + headers: { + 'content-type': 'text/html; charset=utf-8', + 'content-security-policy': page.csp, + 'cache-control': 'no-store', + 'referrer-policy': 'no-referrer', + 'x-content-type-options': 'nosniff' + } + }); + // One flow per cookie: spent whether it worked or not. + response.cookies.set(CONNECT_COOKIE, '', { httpOnly: true, sameSite: 'lax', path: CONNECT_COOKIE_PATH, maxAge: 0 }); + return response; +} diff --git a/src/app/api/oauth/[provider]/redirectUri.test.ts b/src/app/api/oauth/[provider]/redirectUri.test.ts new file mode 100644 index 0000000..355d379 --- /dev/null +++ b/src/app/api/oauth/[provider]/redirectUri.test.ts @@ -0,0 +1,23 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { NextRequest } from 'next/server'; +import { redirectUriFor } from './redirectUri'; + +const saved = process.env.OMNI_OAUTH_ORIGIN; +afterEach(() => { + if (saved === undefined) delete process.env.OMNI_OAUTH_ORIGIN; + else process.env.OMNI_OAUTH_ORIGIN = saved; +}); + +describe('the OAuth redirect URI', () => { + it('stays on the host the browser used, where the flow cookie lives', () => { + delete process.env.OMNI_OAUTH_ORIGIN; + const request = new NextRequest('http://localhost:3000/api/oauth/google/start', { headers: { host: '127.0.0.1:3000' } }); + expect(redirectUriFor(request, 'google')).toBe('http://127.0.0.1:3000/api/oauth/google/callback'); + }); + + it('uses the pinned origin when one is set', () => { + process.env.OMNI_OAUTH_ORIGIN = 'https://flyspace.internal.example/'; + const request = new NextRequest('http://10.0.0.5:3000/api/oauth/google/start', { headers: { host: '10.0.0.5:3000' } }); + expect(redirectUriFor(request, 'google')).toBe('https://flyspace.internal.example/api/oauth/google/callback'); + }); +}); diff --git a/src/app/api/oauth/[provider]/redirectUri.ts b/src/app/api/oauth/[provider]/redirectUri.ts new file mode 100644 index 0000000..2c130b7 --- /dev/null +++ b/src/app/api/oauth/[provider]/redirectUri.ts @@ -0,0 +1,18 @@ +import type { NextRequest } from 'next/server'; + +/** + * The callback URL registered with the provider. It must be on the origin the + * browser started from, or the flow cookie set at start is not sent back. + * OMNI_OAUTH_ORIGIN pins it (behind a proxy that rewrites Host); otherwise it + * is the Host the browser sent, which can differ from the server's own idea + * of its URL (`next start` reports localhost for 127.0.0.1). The provider + * refuses any URL the owner did not register, so a forged Host header cannot + * send a code elsewhere. + */ +export function redirectUriFor(request: NextRequest, provider: string): string { + const pinned = process.env.OMNI_OAUTH_ORIGIN?.trim(); + const url = new URL(request.url); + const host = request.headers.get('host'); + const origin = pinned || (host ? `${url.protocol}//${host}` : url.origin); + return `${origin.replace(/\/+$/, '')}/api/oauth/${encodeURIComponent(provider)}/callback`; +} diff --git a/src/app/api/oauth/[provider]/start/route.ts b/src/app/api/oauth/[provider]/start/route.ts new file mode 100644 index 0000000..c707a39 --- /dev/null +++ b/src/app/api/oauth/[provider]/start/route.ts @@ -0,0 +1,39 @@ +// GET /api/oauth/:provider/start?scope=...&scope=...&nonce=... +// Starts a read-only sign-in (oauthConnect.ts): a redirect to the provider, +// and an httpOnly cookie that binds the flow to this browser. + +import { NextRequest, NextResponse } from 'next/server'; +import { CONNECT_COOKIE, CONNECT_COOKIE_PATH, startConnect } from '@/core/services/server/oauthConnect'; +import { redirectUriFor } from '../redirectUri'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +export async function GET(request: NextRequest, context: { params: Promise<{ provider: string }> }) { + // A top-level navigation from this app is same-origin; another site has no reason to start one. + if (request.headers.get('sec-fetch-site') === 'cross-site') { + return NextResponse.json({ error: 'Sign-in must start from this site.' }, { status: 403 }); + } + const { provider } = await context.params; + const url = new URL(request.url); + const started = startConnect({ + providerId: provider, + scopes: url.searchParams.getAll('scope'), + nonce: url.searchParams.get('nonce') ?? '', + redirectUri: redirectUriFor(request, provider) + }); + if (!started.ok) { + return new NextResponse(started.error, { status: started.status, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' } }); + } + const response = NextResponse.redirect(started.redirect, 302); + response.headers.set('cache-control', 'no-store'); + response.headers.set('referrer-policy', 'no-referrer'); + response.cookies.set(CONNECT_COOKIE, started.cookie, { + httpOnly: true, + sameSite: 'lax', + secure: url.protocol === 'https:', + path: CONNECT_COOKIE_PATH, + maxAge: 600 + }); + return response; +} diff --git a/src/app/api/oauth/route.ts b/src/app/api/oauth/route.ts new file mode 100644 index 0000000..10a2dee --- /dev/null +++ b/src/app/api/oauth/route.ts @@ -0,0 +1,13 @@ +// GET /api/oauth +// Which sign-in providers this server has an OAuth client for (connectProviders.ts). +// Names only. Empty in the public preview. + +import { NextResponse } from 'next/server'; +import { configuredProviders } from '@/core/services/server/oauthConnect'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +export async function GET() { + return NextResponse.json({ providers: configuredProviders() }, { headers: { 'cache-control': 'no-store' } }); +} diff --git a/src/blocks/capability/CapabilityBlock.tsx b/src/blocks/capability/CapabilityBlock.tsx index c0c358a..f98b19c 100644 --- a/src/blocks/capability/CapabilityBlock.tsx +++ b/src/blocks/capability/CapabilityBlock.tsx @@ -14,6 +14,7 @@ import type { OmniItem } from '@/core/gateway'; import { EffectPill } from '@/components/apis/ApiReview'; import { KeyField, keySlotOf, useHasKey, useHouseKeyCovers } from '@/components/apis/KeyField'; import { useRememberingKeys } from '@/components/apis/RememberKeys'; +import { SignInPrompt, useSignIn } from '@/components/apis/SignIn'; import { argumentsFrom, CapabilityInputs, constantOf, inputSummaryOf, missingInputs } from './CapabilityInputs'; import { CapabilityResult } from './CapabilityResult'; @@ -92,6 +93,10 @@ export function CapabilityBlockView({ instanceId }: { instanceId: string }) { const onHouseKey = houseKey && keySlot !== null && !hasKey; // Keys live for the session, so after a reload a keyed block asks again. const needsKey = keySlot !== null && !hasKey && !houseKey; + // An oauth API needs a sign-in instead (connect.ts), for this session. + const signIn = useSignIn(manifest); + const needsSignIn = signIn !== null && !signIn.signedIn; + const needsCredential = needsKey || needsSignIn; const sideEffect = manifest?.effect === 'write' || manifest?.effect === 'destructive'; const params = isPlainParams(block?.params) ? block.params : {}; @@ -101,7 +106,7 @@ export function CapabilityBlockView({ instanceId }: { instanceId: string }) { const trigger = manifest?.trigger ?? { kind: 'manual' as const }; const run = (idempotencyKey?: string, confirmedRun?: string) => { - if (!manifest || running || needsKey) return; + if (!manifest || running || needsCredential) return; if (sideEffect && (manifest.approval !== 'approved' || !confirmedRun)) return; const key = idempotencyKey ?? attemptKey.current ?? `click_${newId()}`; attemptKey.current = key; @@ -198,10 +203,16 @@ export function CapabilityBlockView({ instanceId }: { instanceId: string }) { ) : null} {/* What you look at after Run comes first: the error or the result. */} - {block?.error && !(needsKey && isUnboundKeyError(block.error)) ? ( + {needsSignIn && manifest && signIn ? : null} + + {block?.error && !(needsCredential && isUnboundKeyError(block.error)) ? (

{block.error} {errorHint(block.error) ? {errorHint(block.error)} : null} + {signIn?.signedIn && isRefusal(block.error) && !changingKey ? ( + + ) : null} {keySlot && hasKey && isRefusal(block.error) && !changingKey ? ( @@ -214,6 +225,9 @@ export function CapabilityBlockView({ instanceId }: { instanceId: string }) {

) : null} + {changingKey && manifest && signIn?.signedIn ? ( + setChangingKey(false)} /> + ) : null} {changingKey && manifest && (hasKey || onHouseKey) ? ( setChangingKey(false)} onCancel={() => setChangingKey(false)} /> ) : null} @@ -294,7 +308,7 @@ export function CapabilityBlockView({ instanceId }: { instanceId: string }) { + ) : ( +

+ {title} sign-in is not set up on this server. Its owner registers an OAuth client (DEPLOYMENT.md, "Connect"). +

+ )} + {error ?

{error}

: null} + + ); +} diff --git a/src/core/capabilities/DESIGN.md b/src/core/capabilities/DESIGN.md index a953481..aec60c6 100644 --- a/src/core/capabilities/DESIGN.md +++ b/src/core/capabilities/DESIGN.md @@ -58,9 +58,13 @@ execution fails `ASYNC_START_REJECTED`. Only the run lookup by id is implemented `providers/managedProvider.ts` is a `managed_integration` provider: a Pipedream- or Composio-style catalog entry becomes an http proposal against the SaaS API itself, with `oauth` auth. An `oauth` binding carries scopes and a -slot (one slot per origin and scope set); the token enters the slot through a -host connect flow that does not exist yet, so until then execution is -`AUTH_UNBOUND`. `oauth` is http-only and never rides `server_broker`. +slot (one slot per origin and scope set); the token enters the slot through the +host connect flow (`connect.ts`, `server/oauthConnect.ts`), and until then +execution is `AUTH_UNBOUND`. `oauth` is http-only and never rides +`server_broker`. `compileOpenApi` binds an OpenAPI oauth2 scheme only for a +provider in `connectProviders.ts` (Google), only when the API is on that +provider's own hosts, and only for a read operation with a read-only scope; +a write that needs a sign-in is refused. `providers/managed.decision.ts` rejects both vendors as dependencies. Admission does not place blocks or wires. The OpenAPI install panel still calls diff --git a/src/core/capabilities/connect.compile.test.ts b/src/core/capabilities/connect.compile.test.ts new file mode 100644 index 0000000..c87efc6 --- /dev/null +++ b/src/core/capabilities/connect.compile.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest'; +import { credentialSlot } from './identity'; +import { compileOpenApi } from './openapi'; + +const READ = 'https://www.googleapis.com/auth/calendar.readonly'; +const EVENTS_READ = 'https://www.googleapis.com/auth/calendar.events.readonly'; +const FULL = 'https://www.googleapis.com/auth/calendar'; + +/** Google's shape: an implicit and an authorizationCode scheme, paired in every requirement. */ +function googleSpec(options: { server?: string; authorizationUrl?: string; getScopes?: string[][]; post?: boolean } = {}) { + const authorizationUrl = options.authorizationUrl ?? 'https://accounts.google.com/o/oauth2/auth'; + const scopes = { [FULL]: 'all', [READ]: 'read', [EVENTS_READ]: 'read events' }; + const pair = (list: string[]) => ({ Oauth2: list, Oauth2c: list }); + const ok = { '200': { description: 'ok', content: { 'application/json': { schema: { type: 'object', properties: { summary: { type: 'string' } } } } } } }; + return { + openapi: '3.0.0', + info: { title: 'Calendar', version: 'v3' }, + servers: [{ url: options.server ?? 'https://www.googleapis.com/calendar/v3' }], + components: { + securitySchemes: { + Oauth2: { type: 'oauth2', flows: { implicit: { authorizationUrl, scopes } } }, + Oauth2c: { type: 'oauth2', flows: { authorizationCode: { authorizationUrl, tokenUrl: 'https://accounts.google.com/o/oauth2/token', scopes } } } + } + }, + paths: { + '/calendars/{calendarId}': { + get: { + operationId: 'calendar.calendars.get', + parameters: [{ name: 'calendarId', in: 'path', required: true, schema: { type: 'string' } }], + security: (options.getScopes ?? [[FULL], [EVENTS_READ, READ], [READ]]).map(pair), + responses: ok + }, + ...(options.post ? { + post: { + operationId: 'calendar.calendars.update', + parameters: [{ name: 'calendarId', in: 'path', required: true, schema: { type: 'string' } }], + security: [pair([FULL])], + responses: ok + } + } : {}) + } + } + }; +} + +describe('compiling a Google sign-in', () => { + it('binds a read operation to its narrowest read-only scope, browser direct, in its own slot', () => { + const { manifests, errors } = compileOpenApi(googleSpec()); + expect(errors).toEqual([]); + const [manifest] = manifests; + expect(manifest.effect).toBe('read'); + expect(manifest.auth).toEqual({ + kind: 'oauth', + scopes: [READ], + secretRef: credentialSlot('https://www.googleapis.com/calendar/v3', { kind: 'oauth', scopes: [READ] }) + }); + expect(manifest.transport.kind === 'http' && manifest.transport.access).toBe('browser_direct'); + }); + + it('never routes a sign-in through the broker, even for a host the app brokers', () => { + const [manifest] = compileOpenApi(googleSpec(), { brokerOrigins: ['https://www.googleapis.com'] }).manifests; + expect(manifest.transport.kind === 'http' && manifest.transport.access).toBe('browser_direct'); + }); + + it('refuses a write operation that needs a sign-in', () => { + const { manifests, errors } = compileOpenApi(googleSpec({ post: true })); + expect(manifests.map(manifest => manifest.source.operationId)).toEqual(['calendar.calendars.get']); + expect(errors.map(error => error.message)).toContain('Signed-in operations are read-only in Flyspace; this one can change data'); + }); + + it('refuses a read operation whose only scopes can change data', () => { + const { manifests, errors } = compileOpenApi(googleSpec({ getScopes: [[FULL]] })); + expect(manifests).toEqual([]); + expect(errors[0].message).toBe('It needs a sign-in that can change your data; Flyspace only asks for read-only access'); + }); + + it('refuses a Google sign-in declared for a server that is not Google\'s', () => { + const { manifests, errors } = compileOpenApi(googleSpec({ server: 'https://collector.example.test/v3' })); + expect(manifests).toEqual([]); + expect(errors[0].message).toMatch(/declared for a server that is not Google's/); + }); + + it('refuses a sign-in with a provider Flyspace cannot connect to', () => { + const { manifests, errors } = compileOpenApi(googleSpec({ authorizationUrl: 'https://login.example.test/authorize' })); + expect(manifests).toEqual([]); + expect(errors[0].message).toMatch(/OAuth sign-in Flyspace cannot connect to/); + }); +}); diff --git a/src/core/capabilities/connect.test.ts b/src/core/capabilities/connect.test.ts new file mode 100644 index 0000000..0b3ba65 --- /dev/null +++ b/src/core/capabilities/connect.test.ts @@ -0,0 +1,105 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { connectSignIn, signInSlotOf, type ConnectDeps } from './connect'; +import { credentialSlot } from './identity'; +import { sealManifest, type CapabilityManifest } from './manifest'; +import { compileOpenApi } from './openapi'; +import { capabilitySecrets } from './secrets'; + +const READ = 'https://www.googleapis.com/auth/calendar.readonly'; +const NONCE = 'n'.repeat(32); + +function calendarGet(): CapabilityManifest { + const scopes = { [READ]: 'read' }; + const [manifest] = compileOpenApi({ + openapi: '3.0.0', + info: { title: 'Calendar', version: 'v3' }, + servers: [{ url: 'https://www.googleapis.com/calendar/v3' }], + components: { securitySchemes: { Oauth2c: { type: 'oauth2', flows: { authorizationCode: { authorizationUrl: 'https://accounts.google.com/o/oauth2/auth', tokenUrl: 'https://oauth2.googleapis.com/token', scopes } } } } }, + paths: { '/colors': { get: { operationId: 'calendar.colors.get', security: [{ Oauth2c: [READ] }], responses: { '200': { description: 'ok', content: { 'application/json': { schema: { type: 'object' } } } } } } } } + }).manifests; + return manifest; +} + +/** A channel the test can speak on, standing in for the callback page. */ +function fakeChannel() { + const channel: { onmessage: ((event: MessageEvent) => void) | null; close: () => void; closed: boolean } = { + onmessage: null, + closed: false, + close() { this.closed = true; } + }; + const say = (data: unknown) => channel.onmessage?.({ data } as MessageEvent); + return { channel, say }; +} + +function deps(channel: ReturnType['channel'], opened: string[] = []): ConnectDeps { + return { + open: url => { opened.push(url); return {}; }, + channel: () => channel as unknown as BroadcastChannel, + nonce: () => NONCE + }; +} + +const granted = { type: 'flyspace-connect', ok: true, provider: 'google', nonce: NONCE, scopes: [READ], accessToken: 'ya29.token', expiresIn: 3600 }; + +beforeEach(() => capabilitySecrets.clear()); +afterEach(() => { + vi.useRealTimers(); + capabilitySecrets.clear(); +}); + +describe('signing in from the browser', () => { + it('knows the slot and scopes of a Google manifest, and offers nothing for one re-pointed elsewhere', () => { + const manifest = calendarGet(); + expect(signInSlotOf(manifest)).toMatchObject({ slot: manifest.auth.secretRef, scopes: [READ] }); + if (manifest.transport.kind !== 'http') throw new Error('expected http'); + const elsewhere = sealManifest({ + ...manifest, + transport: { ...manifest.transport, baseUrl: 'https://collector.example.test' }, + auth: { ...manifest.auth, secretRef: credentialSlot('https://collector.example.test', manifest.auth) } + }); + expect(signInSlotOf(elsewhere)).toBeNull(); + }); + + it('opens the start URL for its scopes, ignores other nonces, and keeps the token in the slot', async () => { + const manifest = calendarGet(); + const { channel, say } = fakeChannel(); + const opened: string[] = []; + const outcome = connectSignIn(manifest, deps(channel, opened)); + expect(opened[0]).toBe(`/api/oauth/google/start?nonce=${NONCE}&scope=${encodeURIComponent(READ)}`); + say({ ...granted, nonce: 'someone-else', accessToken: 'not-mine' }); + say(granted); + await expect(outcome).resolves.toEqual({ ok: true }); + expect(capabilitySecrets.get(manifest.auth.secretRef!)).toBe('ya29.token'); + // The device vault is never offered a sign-in token. + expect(capabilitySecrets.refs()).not.toContain(manifest.auth.secretRef); + expect(channel.closed).toBe(true); + }); + + it('refuses a token for other scopes', async () => { + const manifest = calendarGet(); + const { channel, say } = fakeChannel(); + const outcome = connectSignIn(manifest, deps(channel)); + say({ ...granted, scopes: ['https://www.googleapis.com/auth/drive.readonly'] }); + await expect(outcome).resolves.toEqual({ ok: false, error: 'The sign-in answered for something else' }); + expect(capabilitySecrets.has(manifest.auth.secretRef!)).toBe(false); + }); + + it('says so when the window is blocked', async () => { + const { channel } = fakeChannel(); + const outcome = await connectSignIn(calendarGet(), { ...deps(channel), open: () => null }); + expect(outcome).toMatchObject({ ok: false, error: expect.stringMatching(/blocked/) }); + }); + + it('drops the token a minute before it expires, so the block asks again', async () => { + vi.useFakeTimers(); + const manifest = calendarGet(); + const { channel, say } = fakeChannel(); + const outcome = connectSignIn(manifest, deps(channel)); + say({ ...granted, expiresIn: 600 }); + await outcome; + vi.advanceTimersByTime(539_000); + expect(capabilitySecrets.has(manifest.auth.secretRef!)).toBe(true); + vi.advanceTimersByTime(2_000); + expect(capabilitySecrets.has(manifest.auth.secretRef!)).toBe(false); + }); +}); diff --git a/src/core/capabilities/connect.ts b/src/core/capabilities/connect.ts new file mode 100644 index 0000000..58c09ca --- /dev/null +++ b/src/core/capabilities/connect.ts @@ -0,0 +1,138 @@ +// Connect, in the browser: sign in to a provider for one oauth manifest +// (src/core/services/server/oauthConnect.ts runs the flow). The token goes +// into the manifest's own slot, in session memory like a typed key, and is +// dropped when it expires. Only a manifest on the provider's own hosts gets +// a Connect button, and its slot is per origin and scope set, so a token +// never reaches another host. + +import { CONNECT_CHANNEL, connectProvider, providerForBaseUrl, type ConnectProvider, type ConnectProviderId } from './connectProviders'; +import type { CapabilityManifest } from './manifest'; +import { capabilitySecrets } from './secrets'; + +const CONNECT_TIMEOUT_MS = 5 * 60_000; + +export interface SignInSlot { + provider: ConnectProvider; + slot: string; + scopes: string[]; +} + +/** The sign-in a manifest needs, when Flyspace can connect it. */ +export function signInSlotOf(manifest: CapabilityManifest | undefined): SignInSlot | null { + if (!manifest || manifest.auth.kind !== 'oauth' || !manifest.auth.secretRef || manifest.transport.kind !== 'http') return null; + const provider = providerForBaseUrl(manifest.transport.baseUrl); + const scopes = manifest.auth.scopes ?? []; + if (!provider || scopes.length === 0 || !scopes.every(scope => provider.isReadOnlyScope(scope))) return null; + return { provider, slot: manifest.auth.secretRef, scopes: [...scopes].sort() }; +} + +let configured: ReadonlySet = new Set(); +const listeners = new Set<() => void>(); + +function publish(next: Iterable): void { + configured = new Set(next); + for (const listener of listeners) listener(); +} + +export function isConnectConfigured(id: ConnectProviderId): boolean { + return configured.has(id); +} + +export function subscribeConnect(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Ask the server which providers it has an OAuth client for. Any failure: none. */ +export async function loadConnectProviders(fetchImpl: typeof fetch = fetch): Promise { + try { + const response = await fetchImpl('/api/oauth', { headers: { accept: 'application/json' } }); + if (!response.ok) return; + const body = await response.json() as { providers?: unknown }; + if (!Array.isArray(body.providers)) return; + publish(body.providers.filter((id): id is ConnectProviderId => typeof id === 'string' && connectProvider(id) !== undefined)); + } catch { + // No server: nobody can sign in. + } +} + +export function setConnectProvidersForTests(next: Iterable): void { + publish(next); +} + +interface ConnectMessage { + type?: unknown; + ok?: unknown; + nonce?: unknown; + provider?: unknown; + scopes?: unknown; + accessToken?: unknown; + expiresIn?: unknown; + error?: unknown; +} + +const expiries = new Map>(); + +function randomNonce(): string { + const bytes = new Uint8Array(24); + crypto.getRandomValues(bytes); + return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); +} + +export interface ConnectDeps { + open?: (url: string) => { closed?: boolean } | null; + channel?: (name: string) => Pick; + nonce?: () => string; +} + +/** + * Sign in for one manifest. Call it from the click itself: the window opens + * synchronously, before any await, so a popup blocker lets it through. + */ +export function connectSignIn(manifest: CapabilityManifest, deps: ConnectDeps = {}): Promise<{ ok: true } | { ok: false; error: string }> { + const signIn = signInSlotOf(manifest); + if (!signIn) return Promise.resolve({ ok: false, error: 'This API has no sign-in Flyspace can connect' }); + const nonce = (deps.nonce ?? randomNonce)(); + const query = new URLSearchParams({ nonce }); + for (const scope of signIn.scopes) query.append('scope', scope); + const url = `/api/oauth/${signIn.provider.id}/start?${query.toString()}`; + const channel = (deps.channel ?? (name => new BroadcastChannel(name)))(CONNECT_CHANNEL); + const popup = (deps.open ?? (target => window.open(target, 'flyspace-connect', 'popup,width=520,height=680')))(url); + if (!popup) { + channel.close(); + return Promise.resolve({ ok: false, error: 'The sign-in window was blocked. Allow pop-ups for this site and try again.' }); + } + return new Promise(resolve => { + const done = (outcome: { ok: true } | { ok: false; error: string }) => { + clearTimeout(timer); + channel.onmessage = null; + channel.close(); + resolve(outcome); + }; + const timer = setTimeout(() => done({ ok: false, error: 'Sign-in did not finish' }), CONNECT_TIMEOUT_MS); + channel.onmessage = (event: MessageEvent) => { + const message = event.data as ConnectMessage; + if (!message || message.type !== 'flyspace-connect' || message.nonce !== nonce) return; + if (message.ok !== true) { + done({ ok: false, error: typeof message.error === 'string' ? message.error : 'Sign-in did not finish' }); + return; + } + const scopes = Array.isArray(message.scopes) ? [...message.scopes].sort() : []; + if (message.provider !== signIn.provider.id || scopes.join(' ') !== signIn.scopes.join(' ') + || typeof message.accessToken !== 'string' || message.accessToken.length === 0) { + done({ ok: false, error: 'The sign-in answered for something else' }); + return; + } + // Session only: the device vault never keeps a sign-in. + capabilitySecrets.set(signIn.slot, message.accessToken, { sessionOnly: true }); + const seconds = typeof message.expiresIn === 'number' && message.expiresIn > 0 ? message.expiresIn : 3600; + clearTimeout(expiries.get(signIn.slot)); + // Drop it a minute early, so a block asks to sign in again instead of failing. + expiries.set(signIn.slot, setTimeout(() => { + expiries.delete(signIn.slot); + if (capabilitySecrets.get(signIn.slot) === message.accessToken) capabilitySecrets.revoke(signIn.slot); + }, Math.max(0, seconds - 60) * 1000)); + done({ ok: true }); + }; + }); +} diff --git a/src/core/capabilities/connectProviders.ts b/src/core/capabilities/connectProviders.ts new file mode 100644 index 0000000..765f073 --- /dev/null +++ b/src/core/capabilities/connectProviders.ts @@ -0,0 +1,66 @@ +// Providers Flyspace can sign in to with OAuth (APEX_PLAN 6.8, "Connect"). +// The compiler binds an OpenAPI oauth2 scheme only when its authorization +// URL belongs to one of these, and only for a read operation with a +// read-only scope: a token Flyspace asks for can read, never change, the +// person's data. Write and destructive OAuth surface is not built (AGENTS.md +// stop condition 3). +// +// Whether the owner registered an OAuth client for a provider is a server +// fact (GET /api/oauth); this list is what the compiler may bind. + +export interface ConnectProvider { + id: 'google'; + title: string; + /** Hosts an OpenAPI `authorizationUrl` may name for this provider. */ + authorizationHosts: readonly string[]; + /** Whether an API base URL belongs to this provider. */ + servesApi(host: string): boolean; + /** Whether a scope only lets a token read. */ + isReadOnlyScope(scope: string): boolean; +} + +export const CONNECT_PROVIDERS: readonly ConnectProvider[] = [ + { + id: 'google', + title: 'Google', + authorizationHosts: ['accounts.google.com'], + servesApi: host => host === 'googleapis.com' || host.endsWith('.googleapis.com'), + // Google names its read-only scopes with a `.readonly` suffix + // (calendar.readonly, drive.metadata.readonly, youtube.readonly). + isReadOnlyScope: scope => /^https:\/\/www\.googleapis\.com\/auth\/[a-z0-9._-]+\.readonly$/i.test(scope) + } +]; + +/** The same-origin BroadcastChannel a sign-in's callback page answers on. */ +export const CONNECT_CHANNEL = 'flyspace-connect'; + +export type ConnectProviderId = ConnectProvider['id']; + +export function connectProvider(id: string): ConnectProvider | undefined { + return CONNECT_PROVIDERS.find(provider => provider.id === id); +} + +/** The provider an OpenAPI authorization URL belongs to, if Flyspace can connect to it. */ +export function providerForAuthorizationUrl(url: unknown): ConnectProvider | undefined { + if (typeof url !== 'string') return undefined; + let host: string; + try { + const parsed = new URL(url); + if (parsed.protocol !== 'https:') return undefined; + host = parsed.hostname; + } catch { + return undefined; + } + return CONNECT_PROVIDERS.find(provider => provider.authorizationHosts.includes(host)); +} + +/** The provider whose API a manifest's base URL is on, for its Connect button. */ +export function providerForBaseUrl(baseUrl: string): ConnectProvider | undefined { + let host: string; + try { + host = new URL(baseUrl).hostname; + } catch { + return undefined; + } + return CONNECT_PROVIDERS.find(provider => provider.servesApi(host)); +} diff --git a/src/core/capabilities/openapi.ts b/src/core/capabilities/openapi.ts index 95189c2..af08d69 100644 --- a/src/core/capabilities/openapi.ts +++ b/src/core/capabilities/openapi.ts @@ -4,6 +4,7 @@ import { isKeyParameter, looksLikeKey } from './credentialName'; import { canonicalCapabilityId, credentialSlot } from './identity'; +import { connectProvider, providerForAuthorizationUrl, providerForBaseUrl } from './connectProviders'; import { fromJsonSchema } from './jsonSchema'; import { approvalForEffect, @@ -176,7 +177,7 @@ function compileOperation(args: { const effectChoice = chooseEffect(args.method, args.operation); if ('error' in effectChoice) return effectChoice; - const auth = resolveAuth(args.spec, args.operation, args.baseUrl); + const auth = resolveAuth(args.spec, args.operation, args.baseUrl, effectChoice.effect); if ('error' in auth) return auth; const collected = collectInputs(args.spec, args.path, args.pathItem, args.operation, args.method); @@ -294,7 +295,8 @@ function stripTrailingSlash(url: string): string { function resolveAuth( spec: Record, operation: Record, - baseUrl: string + baseUrl: string, + effect: CapabilityManifest['effect'] ): { auth: CapabilityManifest['auth'] } | { error: string } { const requirements = operation.security !== undefined ? operation.security : spec.security; if (!Array.isArray(requirements) || requirements.length === 0) return { auth: { kind: 'none' } }; @@ -304,9 +306,18 @@ function resolveAuth( : {}; let refused: string | undefined; + // Sign-in alternatives, bound only if no key scheme is offered. + const signIns: string[][] = []; + let signInRefused: string | undefined; for (const requirement of requirements) { if (!isRecord(requirement)) continue; const names = Object.keys(requirement); + const signIn = oauthRequirement(names, requirement, schemes, baseUrl); + if (signIn) { + if ('error' in signIn) signInRefused ??= signIn.error; + else signIns.push(signIn.scopes); + continue; + } if (names.length !== 1) return { error: 'requirements that combine several schemes are unsupported' }; const name = names[0]; const scheme = schemes[name]; @@ -318,10 +329,63 @@ function resolveAuth( } return binding; } + if (signIns.length > 0 || signInRefused) return oauthBinding(signIns, signInRefused, baseUrl, effect); // A scheme refused for a stated reason says more than "none supported". return { error: refused && /must be signed/.test(refused) ? refused : 'no supported security scheme (apiKey, http bearer, http basic)' }; } +/** + * One security requirement made only of oauth2 schemes. Google's specs pair an + * implicit and an authorizationCode scheme over the same scopes in every + * requirement; both are the same sign-in, so they bind as one. Null: not + * oauth2. The provider must be one Flyspace can connect to, and the API must + * be on that provider's own hosts, so its token never goes anywhere else. + */ +function oauthRequirement( + names: string[], + requirement: Record, + schemes: Record, + baseUrl: string +): { scopes: string[] } | { error: string } | null { + if (names.length === 0 || !names.every(name => isRecord(schemes[name]) && (schemes[name] as Record).type === 'oauth2')) return null; + const providers = new Set(); + for (const name of names) { + const flows = (schemes[name] as Record).flows; + const urls = isRecord(flows) + ? [flows.authorizationCode, flows.implicit].filter(isRecord).map(flow => flow.authorizationUrl) + : []; + const provider = urls.map(providerForAuthorizationUrl).find(Boolean); + if (!provider) return { error: 'It needs an OAuth sign-in Flyspace cannot connect to yet' }; + providers.add(provider.id); + } + const provider = providers.size === 1 ? connectProvider([...providers][0]) : undefined; + if (!provider) return { error: 'requirements that combine several schemes are unsupported' }; + if (providerForBaseUrl(baseUrl)?.id !== provider.id) { + return { error: `its ${provider.title} sign-in is declared for a server that is not ${provider.title}'s` }; + } + const scopes = [...new Set(names.flatMap(name => Array.isArray(requirement[name]) ? requirement[name] as unknown[] : []))] + .filter((scope): scope is string => typeof scope === 'string'); + if (scopes.length === 0) return { error: 'its OAuth requirement names no scope' }; + if (!scopes.every(scope => provider.isReadOnlyScope(scope))) return { error: READ_ONLY_SIGN_IN }; + return { scopes: scopes.sort() }; +} + +const READ_ONLY_SIGN_IN = 'It needs a sign-in that can change your data; Flyspace only asks for read-only access'; + +/** The narrowest read-only alternative, for a read operation only (AGENTS.md stop condition 3). */ +function oauthBinding( + alternatives: string[][], + refused: string | undefined, + baseUrl: string, + effect: CapabilityManifest['effect'] +): { auth: CapabilityManifest['auth'] } | { error: string } { + if (effect !== 'read') return { error: 'Signed-in operations are read-only in Flyspace; this one can change data' }; + const narrowest = [...alternatives].sort((a, b) => a.length - b.length || a.join(' ').localeCompare(b.join(' ')))[0]; + if (!narrowest) return { error: refused ?? READ_ONLY_SIGN_IN }; + const auth = { kind: 'oauth' as const, scopes: narrowest }; + return { auth: { ...auth, secretRef: credentialSlot(baseUrl, auth) } }; +} + /** HTTP auth scheme names that carry a static key, sent as `Authorization: `. */ const STATIC_TOKEN_SCHEMES = new Set(['token', 'apikey', 'api-key', 'key']); diff --git a/src/core/capabilities/secrets.ts b/src/core/capabilities/secrets.ts index a742634..2e57569 100644 --- a/src/core/capabilities/secrets.ts +++ b/src/core/capabilities/secrets.ts @@ -2,6 +2,8 @@ // name (secretRef). Nothing in this module is persisted. const slots = new Map(); +/** Slots the device vault never keeps: a sign-in token lasts one session (connect.ts). */ +const sessionOnly = new Set(); const listeners = new Set<() => void>(); function changed(): void { @@ -20,13 +22,15 @@ export function secretByteLength(value: string): number { } export const capabilitySecrets = { - set(ref: string, value: string): void { + set(ref: string, value: string, options: { sessionOnly?: boolean } = {}): void { if (!ref || typeof value !== 'string' || value.length === 0) { throw new Error('A secret slot needs a name and a value'); } if (secretByteLength(value) > MAX_SECRET_BYTES) { throw new Error(`A secret value is at most ${MAX_SECRET_BYTES} bytes`); } + if (options.sessionOnly) sessionOnly.add(ref); + else sessionOnly.delete(ref); slots.set(ref, value); changed(); }, @@ -38,13 +42,14 @@ export const capabilitySecrets = { /** Unbind one slot. The capability stays installed; its next run is AUTH_UNBOUND. */ revoke(ref: string): boolean { const removed = slots.delete(ref); + sessionOnly.delete(ref); if (removed) changed(); return removed; }, - /** The slots that hold a value, for the opt-in device vault (keyVault.ts). */ + /** The slots the opt-in device vault may keep (keyVault.ts): every one but a sign-in. */ refs(): string[] { - return [...slots.keys()]; + return [...slots.keys()].filter(ref => !sessionOnly.has(ref)); }, /** Whether a slot holds a value. The value itself is never handed to a view. */ @@ -62,6 +67,7 @@ export const capabilitySecrets = { clear(): void { slots.clear(); + sessionOnly.clear(); changed(); } }; diff --git a/src/core/secrets.ts b/src/core/secrets.ts index 2d626f3..c0bac49 100644 --- a/src/core/secrets.ts +++ b/src/core/secrets.ts @@ -31,6 +31,8 @@ export const SECRET_ENV_VARS = [ 'BLS_API_KEY', 'ALPHA_VANTAGE_API_KEY', 'METACULUS_API_KEY', + // Connect: the OAuth client secret (oauthConnect.ts) + 'OMNI_GOOGLE_CLIENT_SECRET', // The inference ledger's connection string, which rides along on pg errors 'DATABASE_URL', // Test-only scratch database. Never set in production, but it is still a diff --git a/src/core/services/server/oauthConnect.test.ts b/src/core/services/server/oauthConnect.test.ts new file mode 100644 index 0000000..6d14407 --- /dev/null +++ b/src/core/services/server/oauthConnect.test.ts @@ -0,0 +1,124 @@ +import { createHash } from 'node:crypto'; +import { describe, expect, it, vi } from 'vitest'; +import { callbackPage, configuredProviders, finishConnect, startConnect } from './oauthConnect'; + +const ENV = { OMNI_GOOGLE_CLIENT_ID: 'client-123.apps.googleusercontent.com', OMNI_GOOGLE_CLIENT_SECRET: 'shh-client-secret' }; +const READ = 'https://www.googleapis.com/auth/calendar.readonly'; +const REDIRECT = 'http://127.0.0.1:3000/api/oauth/google/callback'; +const NONCE = 'a'.repeat(32); + +function started(now = 1_000) { + const result = startConnect({ providerId: 'google', scopes: [READ], nonce: NONCE, redirectUri: REDIRECT, env: ENV, now }); + if (!result.ok) throw new Error(result.error); + const url = new URL(result.redirect); + return { cookie: result.cookie, url, state: url.searchParams.get('state')! }; +} + +function tokenFetch(body: unknown, status = 200) { + return vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); +} + +const finish = (overrides: Partial[0]> & { state: string; cookie: string | undefined }) => finishConnect({ + providerId: 'google', + query: new URLSearchParams({ state: overrides.state, code: 'auth-code' }), + redirectUri: REDIRECT, + env: ENV, + now: 2_000, + fetch: tokenFetch({ access_token: 'ya29.token', expires_in: 3599, scope: READ, token_type: 'Bearer' }) as unknown as typeof fetch, + ...overrides +}); + +describe('Connect: starting a sign-in', () => { + it('is not offered until the owner configures a client, and never in the public preview', () => { + expect(configuredProviders({})).toEqual([]); + expect(configuredProviders(ENV)).toEqual(['google']); + expect(configuredProviders({ ...ENV, OMNI_PUBLIC_DEMO: '1' })).toEqual([]); + const refused = startConnect({ providerId: 'google', scopes: [READ], nonce: NONCE, redirectUri: REDIRECT, env: {} }); + expect(refused).toMatchObject({ ok: false, status: 503 }); + }); + + it('refuses a scope that can change data, and an unknown provider', () => { + expect(startConnect({ providerId: 'google', scopes: ['https://www.googleapis.com/auth/calendar'], nonce: NONCE, redirectUri: REDIRECT, env: ENV })) + .toMatchObject({ ok: false, status: 400 }); + expect(startConnect({ providerId: 'github', scopes: [READ], nonce: NONCE, redirectUri: REDIRECT, env: ENV })) + .toMatchObject({ ok: false, status: 404 }); + }); + + it('sends the browser to Google with PKCE, the read-only scope, and no refresh token', () => { + const { url, cookie } = started(); + expect(url.origin + url.pathname).toBe('https://accounts.google.com/o/oauth2/v2/auth'); + expect(url.searchParams.get('client_id')).toBe(ENV.OMNI_GOOGLE_CLIENT_ID); + expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT); + expect(url.searchParams.get('scope')).toBe(READ); + expect(url.searchParams.get('code_challenge_method')).toBe('S256'); + expect(url.searchParams.get('access_type')).toBe('online'); + expect(url.toString()).not.toContain(ENV.OMNI_GOOGLE_CLIENT_SECRET); + expect(cookie).not.toContain(ENV.OMNI_GOOGLE_CLIENT_SECRET); + }); +}); + +describe('Connect: finishing a sign-in', () => { + it('exchanges the code with the verifier and client secret, and returns the token for the nonce', async () => { + const { cookie, state, url } = started(); + const fetchMock = tokenFetch({ access_token: 'ya29.token', expires_in: 3599, scope: READ, token_type: 'Bearer' }); + const result = await finish({ state, cookie, fetch: fetchMock as unknown as typeof fetch }); + expect(result).toEqual({ ok: true, providerId: 'google', nonce: NONCE, scopes: [READ], accessToken: 'ya29.token', expiresIn: 3599 }); + const [target, init] = fetchMock.mock.calls[0]; + expect(String(target)).toBe('https://oauth2.googleapis.com/token'); + const form = new URLSearchParams(String(init?.body)); + expect(form.get('client_secret')).toBe(ENV.OMNI_GOOGLE_CLIENT_SECRET); + expect(form.get('redirect_uri')).toBe(REDIRECT); + // The verifier answers the challenge that went to Google. + const challenge = createHash('sha256').update(form.get('code_verifier')!).digest('base64url'); + expect(challenge).toBe(url.searchParams.get('code_challenge')); + }); + + it('refuses a callback this browser did not start', async () => { + const { state } = started(); + expect(await finish({ state, cookie: undefined })).toMatchObject({ ok: false, error: 'This sign-in was not started in this browser' }); + }); + + it('refuses a tampered cookie and a mismatched state', async () => { + const { cookie, state } = started(); + const [body, mac] = cookie.split('.'); + const forged = Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(body, 'base64url').toString()), scopes: ['https://www.googleapis.com/auth/calendar'] })).toString('base64url'); + expect(await finish({ state, cookie: `${forged}.${mac}` })).toMatchObject({ ok: false }); + expect(await finish({ state: `${state.slice(0, -1)}x`, cookie })).toMatchObject({ ok: false, error: 'This sign-in was not started in this browser' }); + }); + + it('refuses a flow older than ten minutes', async () => { + const { cookie, state } = started(0); + expect(await finish({ state, cookie, now: 10 * 60_000 + 1 })).toMatchObject({ ok: false, nonce: NONCE, error: 'This sign-in took too long; try again' }); + }); + + it('refuses when the person unticked a scope on the consent screen', async () => { + const { cookie, state } = started(); + const result = await finish({ state, cookie, fetch: tokenFetch({ access_token: 'ya29.token', scope: 'openid', token_type: 'Bearer' }) as unknown as typeof fetch }); + expect(result).toMatchObject({ ok: false, error: `Access was not granted for: ${READ}` }); + }); + + it('passes no provider error text on, and reports a cancelled sign-in plainly', async () => { + const { cookie, state } = started(); + const refused = await finish({ state, cookie, fetch: tokenFetch({ error: 'invalid_grant', error_description: ENV.OMNI_GOOGLE_CLIENT_ID }, 400) as unknown as typeof fetch }); + expect(refused).toMatchObject({ ok: false, error: 'The provider refused the code (HTTP 400)' }); + const cancelled = await finish({ state, cookie, query: new URLSearchParams({ state, error: 'access_denied' }) }); + expect(cancelled).toMatchObject({ ok: false, error: 'Sign-in was cancelled' }); + }); +}); + +describe('Connect: the callback page', () => { + it('allows only its own script, by hash', () => { + const page = callbackPage({ ok: true, providerId: 'google', nonce: NONCE, scopes: [READ], accessToken: 'ya29.token', expiresIn: 3599 }); + const script = /' }); + expect(page.html.match(/<\/script>/g)).toHaveLength(1); + expect(page.html).not.toContain(' = { + google: { + authorize: 'https://accounts.google.com/o/oauth2/v2/auth', + token: 'https://oauth2.googleapis.com/token', + clientIdEnv: 'OMNI_GOOGLE_CLIENT_ID', + clientSecretEnv: 'OMNI_GOOGLE_CLIENT_SECRET' + } +}; + +type Env = Record; + +interface Client { + id: string; + secret: string; +} + +function clientFor(providerId: ConnectProviderId, env: Env): Client | null { + // The public preview has no sign-in: its visitors are not the owner. + if (env.OMNI_PUBLIC_DEMO === '1') return null; + const endpoints = ENDPOINTS[providerId]; + const id = env[endpoints.clientIdEnv]?.trim(); + const secret = env[endpoints.clientSecretEnv]?.trim(); + return id && secret ? { id, secret } : null; +} + +/** Providers whose OAuth client the owner configured. */ +export function configuredProviders(env: Env = process.env): ConnectProviderId[] { + return (Object.keys(ENDPOINTS) as ConnectProviderId[]).filter(id => clientFor(id, env) !== null); +} + +interface FlowCookie { + v: 1; + provider: ConnectProviderId; + state: string; + verifier: string; + scopes: string[]; + nonce: string; + exp: number; +} + +function base64url(buffer: Buffer): string { + return buffer.toString('base64url'); +} + +function signingKey(client: Client): Buffer { + return createHash('sha256').update('flyspace-connect-cookie\0').update(client.secret).digest(); +} + +function seal(flow: FlowCookie, client: Client): string { + const body = base64url(Buffer.from(JSON.stringify(flow), 'utf8')); + const mac = base64url(createHmac('sha256', signingKey(client)).update(body).digest()); + return `${body}.${mac}`; +} + +function unseal(value: string | undefined, client: Client): FlowCookie | null { + if (!value) return null; + const [body, mac, extra] = value.split('.'); + if (!body || !mac || extra !== undefined) return null; + const expected = createHmac('sha256', signingKey(client)).update(body).digest(); + const given = Buffer.from(mac, 'base64url'); + if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null; + try { + const flow = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as FlowCookie; + return flow && flow.v === 1 ? flow : null; + } catch { + return null; + } +} + +export type StartResult = + | { ok: true; redirect: string; cookie: string } + | { ok: false; status: number; error: string }; + +/** Begin a sign-in: where to send the browser, and the cookie that binds the flow to it. */ +export function startConnect(args: { + providerId: string; + scopes: string[]; + nonce: string; + redirectUri: string; + env?: Env; + now?: number; +}): StartResult { + const provider = connectProvider(args.providerId); + if (!provider) return { ok: false, status: 404, error: 'Unknown sign-in provider' }; + const client = clientFor(provider.id, args.env ?? process.env); + if (!client) return { ok: false, status: 503, error: `${provider.title} sign-in is not set up on this server` }; + const scopes = [...new Set(args.scopes)].sort(); + if (scopes.length === 0 || scopes.length > MAX_SCOPES) return { ok: false, status: 400, error: 'Ask for 1 to 20 scopes' }; + if (!scopes.every(scope => provider.isReadOnlyScope(scope))) { + return { ok: false, status: 400, error: 'Flyspace only asks for read-only access' }; + } + if (!/^[A-Za-z0-9_-]{16,64}$/.test(args.nonce)) return { ok: false, status: 400, error: 'nonce is invalid' }; + + const state = base64url(randomBytes(24)); + const verifier = base64url(randomBytes(48)); + const challenge = base64url(createHash('sha256').update(verifier).digest()); + const exp = (args.now ?? Date.now()) + FLOW_TTL_MS; + const authorize = new URL(ENDPOINTS[provider.id].authorize); + authorize.search = new URLSearchParams({ + client_id: client.id, + redirect_uri: args.redirectUri, + response_type: 'code', + scope: scopes.join(' '), + state, + code_challenge: challenge, + code_challenge_method: 'S256', + access_type: 'online', + include_granted_scopes: 'false', + prompt: 'consent' + }).toString(); + const cookie = seal({ v: 1, provider: provider.id, state, verifier, scopes, nonce: args.nonce, exp }, client); + return { ok: true, redirect: authorize.toString(), cookie }; +} + +export type CallbackResult = + | { ok: true; providerId: ConnectProviderId; nonce: string; scopes: string[]; accessToken: string; expiresIn: number } + | { ok: false; nonce?: string; error: string }; + +/** Finish a sign-in: check the flow, exchange the code, and check what was granted. */ +export async function finishConnect(args: { + providerId: string; + query: URLSearchParams; + cookie: string | undefined; + redirectUri: string; + fetch?: typeof fetch; + env?: Env; + now?: number; +}): Promise { + const provider = connectProvider(args.providerId); + if (!provider) return { ok: false, error: 'Unknown sign-in provider' }; + const client = clientFor(provider.id, args.env ?? process.env); + if (!client) return { ok: false, error: `${provider.title} sign-in is not set up on this server` }; + const flow = unseal(args.cookie, client); + // The cookie is httpOnly and SameSite=Lax, set by this server when this + // browser started the flow: a callback without it was not started here. + if (!flow || flow.provider !== provider.id) return { ok: false, error: 'This sign-in was not started in this browser' }; + if ((args.now ?? Date.now()) > flow.exp) return { ok: false, nonce: flow.nonce, error: 'This sign-in took too long; try again' }; + const state = args.query.get('state') ?? ''; + const stateMatches = state.length === flow.state.length && timingSafeEqual(Buffer.from(state), Buffer.from(flow.state)); + if (!stateMatches) return { ok: false, nonce: flow.nonce, error: 'This sign-in was not started in this browser' }; + if (args.query.get('error')) { + return { ok: false, nonce: flow.nonce, error: args.query.get('error') === 'access_denied' ? 'Sign-in was cancelled' : 'The provider refused the sign-in' }; + } + const code = args.query.get('code'); + if (!code) return { ok: false, nonce: flow.nonce, error: 'The provider sent no authorization code' }; + + let payload: { access_token?: unknown; expires_in?: unknown; scope?: unknown; token_type?: unknown }; + try { + const response = await (args.fetch ?? fetch)(ENDPOINTS[provider.id].token, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code, + client_id: client.id, + client_secret: client.secret, + redirect_uri: args.redirectUri, + code_verifier: flow.verifier + }).toString(), + redirect: 'error', + signal: AbortSignal.timeout(15_000) + }); + // The provider's error body can echo the client id; none of it is passed on. + if (!response.ok) return { ok: false, nonce: flow.nonce, error: `The provider refused the code (HTTP ${response.status})` }; + payload = await response.json() as typeof payload; + } catch { + return { ok: false, nonce: flow.nonce, error: 'Could not reach the provider to finish signing in' }; + } + if (typeof payload.access_token !== 'string' || payload.access_token.length === 0 || payload.access_token.length > 4096) { + return { ok: false, nonce: flow.nonce, error: 'The provider sent no access token' }; + } + if (typeof payload.token_type === 'string' && payload.token_type.toLowerCase() !== 'bearer') { + return { ok: false, nonce: flow.nonce, error: 'The provider sent a token Flyspace cannot use' }; + } + // A person can untick a scope on the consent screen. Without all of them + // the block would fail later with a refusal that does not say why. + const granted = new Set(typeof payload.scope === 'string' ? payload.scope.split(/\s+/) : []); + const missing = flow.scopes.filter(scope => !granted.has(scope)); + if (missing.length > 0) return { ok: false, nonce: flow.nonce, error: `Access was not granted for: ${missing.join(', ')}` }; + const expiresIn = typeof payload.expires_in === 'number' && payload.expires_in > 0 ? Math.min(payload.expires_in, 24 * 3600) : 3600; + return { ok: true, providerId: provider.id, nonce: flow.nonce, scopes: flow.scopes, accessToken: payload.access_token, expiresIn }; +} + +/** + * The callback page: hands the outcome to the page that started the sign-in + * over a BroadcastChannel (same origin only, and unlike window.opener it + * survives the provider's Cross-Origin-Opener-Policy), then closes. The + * starting page accepts only its own nonce. The one inline script is allowed + * by hash, and nothing else loads. + */ +export function callbackPage(result: CallbackResult): { html: string; csp: string } { + const message = result.ok + ? { type: 'flyspace-connect', ok: true, provider: result.providerId, nonce: result.nonce, scopes: result.scopes, accessToken: result.accessToken, expiresIn: result.expiresIn } + : { type: 'flyspace-connect', ok: false, nonce: result.nonce ?? null, error: result.error }; + // JSON inside a script: escape what could end it or start markup. + const data = JSON.stringify(message).replace(//g, '\\u003e').replace(/&/g, '\\u0026') + .replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); + const script = `(function(){var m=${data};var s=document.getElementById('s');try{var c=new BroadcastChannel(${JSON.stringify(CONNECT_CHANNEL)});c.postMessage(m);c.close();}catch(e){}s.textContent=m.ok?'Signed in. You can close this window.':m.error;if(m.ok){setTimeout(function(){window.close();},300);}})();`; + const hash = createHash('sha256').update(script).digest('base64'); + const text = result.ok ? 'Signed in. Returning to Flyspace…' : 'Sign-in did not finish.'; + const html = `Flyspace sign-in

${text}

`; + const csp = `default-src 'none'; script-src 'sha256-${hash}'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`; + return { html, csp }; +}