Repository navigation
Connect: read-only Google sign-in for blocks that need OAuth #156
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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' } }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| // @vitest-environment happy-dom | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import { act, fireEvent, render, screen } from '@testing-library/react'; | ||
| import { CapabilityBlockView } from './CapabilityBlock'; | ||
| import { setConnectProvidersForTests } from '@/core/capabilities/connect'; | ||
| import type { CapabilityManifest } from '@/core/capabilities/manifest'; | ||
| import { compileOpenApi } from '@/core/capabilities/openapi'; | ||
| import { clearCapabilities, installProposal } from '@/core/capabilities/registry'; | ||
| import { capabilitySecrets } from '@/core/capabilities/secrets'; | ||
| import { blockRegistry } from '@/core/registry/BlockRegistry'; | ||
| import { useBlockStore, useWireStore } from '@/core/stores'; | ||
|
|
||
| const READ = 'https://www.googleapis.com/auth/calendar.readonly'; | ||
|
|
||
| function placeColors(): { manifest: CapabilityManifest; instanceId: string } { | ||
| 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: { [READ]: 'read' } } } } } }, | ||
| paths: { '/colors': { get: { operationId: 'calendar.colors.get', summary: 'Calendar colors', security: [{ Oauth2c: [READ] }], responses: { '200': { description: 'ok', content: { 'application/json': { schema: { type: 'object', properties: { kind: { type: 'string' } } } } } } } } } } | ||
| }).manifests; | ||
| expect(installProposal(manifest).ok).toBe(true); | ||
| const instanceId = useBlockStore.getState().addBlock(blockRegistry.get(manifest.id)!, { x: 0, y: 0 }); | ||
| return { manifest, instanceId }; | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| clearCapabilities(); | ||
| capabilitySecrets.clear(); | ||
| setConnectProvidersForTests([]); | ||
| useBlockStore.setState({ blocks: [], activeShellId: 'root' }); | ||
| useWireStore.setState({ wires: [] }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllGlobals(); | ||
| setConnectProvidersForTests([]); | ||
| clearCapabilities(); | ||
| capabilitySecrets.clear(); | ||
| useBlockStore.setState({ blocks: [] }); | ||
| }); | ||
|
|
||
| describe('a block that needs a sign-in', () => { | ||
| it('says the server has no sign-in set up, and does not run', () => { | ||
| const { instanceId } = placeColors(); | ||
| render(<CapabilityBlockView instanceId={instanceId} />); | ||
| expect(screen.getByText('This API needs you to sign in to Google.')).toBeTruthy(); | ||
| expect(screen.getByText(/Google sign-in is not set up on this server/)).toBeTruthy(); | ||
| expect(screen.getByText(/Read-only access: calendar\.readonly/)).toBeTruthy(); | ||
| expect((screen.getByRole('button', { name: 'Sign in first' }) as HTMLButtonElement).disabled).toBe(true); | ||
| }); | ||
|
|
||
| it('opens the sign-in window from the click when the server has a Google client', () => { | ||
| const { instanceId } = placeColors(); | ||
| setConnectProvidersForTests(['google']); | ||
| const open = vi.fn(() => ({})); | ||
| vi.stubGlobal('open', open); | ||
| render(<CapabilityBlockView instanceId={instanceId} />); | ||
| fireEvent.click(screen.getByRole('button', { name: 'Sign in with Google' })); | ||
| expect(open).toHaveBeenCalledTimes(1); | ||
| expect(String((open.mock.calls[0] as unknown[])[0])).toMatch(/^\/api\/oauth\/google\/start\?nonce=[0-9a-f]{48}&scope=/); | ||
| expect(screen.getByText('Waiting for the sign-in window…')).toBeTruthy(); | ||
| }); | ||
|
|
||
| it('runs once the session holds a token for its slot', () => { | ||
| const { manifest, instanceId } = placeColors(); | ||
| render(<CapabilityBlockView instanceId={instanceId} />); | ||
| act(() => capabilitySecrets.set(manifest.auth.secretRef!, 'ya29.token')); | ||
| expect(screen.queryByText('This API needs you to sign in to Google.')).toBeNull(); | ||
| expect((screen.getByRole('button', { name: 'Run' }) as HTMLButtonElement).disabled).toBe(false); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.