Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 6 additions & 22 deletions client/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import {
OAuthCallbackRoute,
} from './client-routes.tsx'
import { Router } from './client-router.tsx'
import {
fetchSessionInfo,
type SessionInfo,
type SessionStatus,
} from './session.ts'
import { colors, spacing, typography } from './styles/tokens.ts'

type SessionInfo = {
email: string
}

type SessionStatus = 'idle' | 'loading' | 'ready'

type NavLink = {
href: string
label: string
Expand All @@ -27,22 +26,7 @@ export function App(handle: Handle) {
if (sessionStatus !== 'idle') return
sessionStatus = 'loading'

try {
const response = await fetch('/session', {
headers: { Accept: 'application/json' },
credentials: 'include',
})
const payload = await response.json().catch(() => null)
const email =
response.ok &&
payload?.ok &&
typeof payload?.session?.email === 'string'
? payload.session.email.trim()
: ''
session = email ? { email } : null
} catch {
session = null
}
session = await fetchSessionInfo()

sessionStatus = 'ready'
handle.update()
Expand Down
179 changes: 123 additions & 56 deletions client/client-routes.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { type Handle } from 'remix/component'
import { navigate } from './client-router.tsx'
import { Counter } from './counter.tsx'
import {
fetchSessionInfo,
type SessionInfo,
type SessionStatus,
} from './session.ts'
import {
colors,
radius,
Expand Down Expand Up @@ -354,6 +359,8 @@ function OAuthAuthorizeForm(handle: Handle) {
let message: OAuthAuthorizeMessage | null = null
let submitting = false
let lastSearch = ''
let session: SessionInfo | null = null
let sessionStatus: SessionStatus = 'idle'

function setMessage(next: OAuthAuthorizeMessage | null) {
message = next
Expand Down Expand Up @@ -420,6 +427,16 @@ function OAuthAuthorizeForm(handle: Handle) {
}
}

async function loadSession() {
if (sessionStatus !== 'idle') return
sessionStatus = 'loading'

session = await fetchSessionInfo()

sessionStatus = 'ready'
handle.update()
}
Comment thread
cursor[bot] marked this conversation as resolved.

async function submitDecision(
decision: 'approve' | 'deny',
form?: HTMLFormElement,
Expand Down Expand Up @@ -486,7 +503,11 @@ function OAuthAuthorizeForm(handle: Handle) {
async function handleSubmit(event: SubmitEvent) {
event.preventDefault()
if (!(event.currentTarget instanceof HTMLFormElement)) return
await submitDecision('approve', event.currentTarget)
const hasSession = Boolean(session?.email)
await submitDecision(
'approve',
hasSession ? undefined : event.currentTarget,
)
}

return () => {
Expand All @@ -496,12 +517,26 @@ function OAuthAuthorizeForm(handle: Handle) {
lastSearch = currentSearch
void loadInfo()
}
if (sessionStatus === 'idle') {
void loadSession()
}

const clientLabel = info?.client?.name ?? 'Unknown client'
const scopes = info?.scopes ?? []
const scopeLabel =
scopes.length > 0 ? scopes.join(', ') : 'No scopes requested.'
const actionsDisabled = status !== 'ready' || submitting
const sessionEmail = session?.email ?? ''
const isSessionReady = sessionStatus === 'ready'
const isSessionLoading =
sessionStatus === 'loading' || sessionStatus === 'idle'
const isLoggedIn = isSessionReady && Boolean(sessionEmail)
const actionsDisabled = status !== 'ready' || submitting || isSessionLoading
const formReady = status === 'ready' && !isSessionLoading
const authorizeLabel = submitting
? 'Submitting...'
: isLoggedIn
? 'Approve connection'
: 'Authorize'

return (
<section
Expand Down Expand Up @@ -548,6 +583,34 @@ function OAuthAuthorizeForm(handle: Handle) {
</p>
<p css={{ margin: 0, color: colors.textMuted }}>{scopeLabel}</p>
</section>
{isSessionLoading ? (
<p css={{ color: colors.textMuted }}>Checking your session…</p>
) : null}
{isLoggedIn ? (
<section
css={{
padding: spacing.md,
borderRadius: radius.md,
border: `1px solid ${colors.border}`,
backgroundColor: colors.surface,
display: 'grid',
gap: spacing.xs,
}}
>
<p
css={{
margin: 0,
fontWeight: typography.fontWeight.medium,
color: colors.text,
}}
>
Signed in as {sessionEmail}
</p>
<p css={{ margin: 0, color: colors.textMuted }}>
Approve to continue with this account.
</p>
</section>
) : null}
{status === 'loading' ? (
<p css={{ color: colors.textMuted }}>
Loading authorization details…
Expand All @@ -573,62 +636,66 @@ function OAuthAuthorizeForm(handle: Handle) {
border: `1px solid ${colors.border}`,
backgroundColor: colors.surface,
boxShadow: shadows.sm,
opacity: status === 'ready' ? 1 : 0.7,
opacity: formReady ? 1 : 0.7,
}}
on={{ submit: handleSubmit }}
>
<label css={{ display: 'grid', gap: spacing.xs }}>
<span
css={{
color: colors.text,
fontWeight: typography.fontWeight.medium,
fontSize: typography.fontSize.sm,
}}
>
Email
</span>
<input
type="email"
name="email"
required
autoComplete="email"
placeholder="you@example.com"
disabled={actionsDisabled}
css={{
padding: spacing.sm,
borderRadius: radius.md,
border: `1px solid ${colors.border}`,
fontSize: typography.fontSize.base,
fontFamily: typography.fontFamily,
}}
/>
</label>
<label css={{ display: 'grid', gap: spacing.xs }}>
<span
css={{
color: colors.text,
fontWeight: typography.fontWeight.medium,
fontSize: typography.fontSize.sm,
}}
>
Password
</span>
<input
type="password"
name="password"
required
autoComplete="current-password"
placeholder="Enter your password"
disabled={actionsDisabled}
css={{
padding: spacing.sm,
borderRadius: radius.md,
border: `1px solid ${colors.border}`,
fontSize: typography.fontSize.base,
fontFamily: typography.fontFamily,
}}
/>
</label>
{!isLoggedIn && isSessionReady ? (
<>
<label css={{ display: 'grid', gap: spacing.xs }}>
<span
css={{
color: colors.text,
fontWeight: typography.fontWeight.medium,
fontSize: typography.fontSize.sm,
}}
>
Email
</span>
<input
type="email"
name="email"
required
autoComplete="email"
placeholder="you@example.com"
disabled={actionsDisabled}
css={{
padding: spacing.sm,
borderRadius: radius.md,
border: `1px solid ${colors.border}`,
fontSize: typography.fontSize.base,
fontFamily: typography.fontFamily,
}}
/>
</label>
<label css={{ display: 'grid', gap: spacing.xs }}>
<span
css={{
color: colors.text,
fontWeight: typography.fontWeight.medium,
fontSize: typography.fontSize.sm,
}}
>
Password
</span>
<input
type="password"
name="password"
required
autoComplete="current-password"
placeholder="Enter your password"
disabled={actionsDisabled}
css={{
padding: spacing.sm,
borderRadius: radius.md,
border: `1px solid ${colors.border}`,
fontSize: typography.fontSize.base,
fontFamily: typography.fontFamily,
}}
/>
</label>
</>
) : null}
<div css={{ display: 'flex', gap: spacing.sm, flexWrap: 'wrap' }}>
<button
type="submit"
Expand All @@ -645,7 +712,7 @@ function OAuthAuthorizeForm(handle: Handle) {
opacity: actionsDisabled ? 0.7 : 1,
}}
>
{submitting ? 'Submitting...' : 'Authorize'}
{authorizeLabel}
</button>
<button
type="button"
Expand Down
22 changes: 22 additions & 0 deletions client/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export type SessionInfo = {
email: string
}

export type SessionStatus = 'idle' | 'loading' | 'ready'

export async function fetchSessionInfo(): Promise<SessionInfo | null> {
try {
const response = await fetch('/session', {
headers: { Accept: 'application/json' },
credentials: 'include',
})
const payload = await response.json().catch(() => null)
const email =
response.ok && payload?.ok && typeof payload?.session?.email === 'string'
? payload.session.email.trim()
: ''
return email ? { email } : null
} catch {
return null
}
}
48 changes: 46 additions & 2 deletions worker/oauth-handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import type {
CompleteAuthorizationOptions,
OAuthHelpers,
} from '@cloudflare/workers-oauth-provider'
import {
createAuthCookie,
setAuthSessionSecret,
} from '../server/auth-session.ts'
import {
handleAuthorizeInfo,
handleAuthorizeRequest,
Expand All @@ -27,6 +31,7 @@ const baseClient: ClientInfo = {
clientName: 'epicflare Demo',
tokenEndpointAuthMethod: 'client_secret_basic',
}
const cookieSecret = 'test-secret'

function createHelpers(overrides: Partial<OAuthHelpers> = {}): OAuthHelpers {
return {
Expand Down Expand Up @@ -104,8 +109,16 @@ async function createDatabase(password: string) {
} as unknown as D1Database
}

function createEnv(helpers: OAuthHelpers, appDb?: D1Database) {
return { OAUTH_PROVIDER: helpers, APP_DB: appDb } as unknown as Env
function createEnv(
helpers: OAuthHelpers,
appDb?: D1Database,
cookieSecretValue: string = cookieSecret,
) {
return {
OAUTH_PROVIDER: helpers,
APP_DB: appDb,
COOKIE_SECRET: cookieSecretValue,
} as unknown as Env
}

function createFormRequest(
Expand Down Expand Up @@ -186,6 +199,37 @@ test('authorize requires email and password for approval', async () => {
})
})

test('authorize allows approval with an existing session', async () => {
let capturedOptions: CompleteAuthorizationOptions | null = null
const helpers = createHelpers({
async completeAuthorization(options) {
capturedOptions = options
return { redirectTo: 'https://example.com/callback?code=session' }
},
})
setAuthSessionSecret(cookieSecret)
const cookie = await createAuthCookie(
{ id: 'session-id', email: 'user@example.com' },
false,
)

const response = await handleAuthorizeRequest(
createFormRequest(
{ decision: 'approve' },
{ Accept: 'application/json', Cookie: cookie },
),
createEnv(helpers),
)

expect(response.status).toBe(200)
const payload = await response.json()
expect(payload).toEqual({
ok: true,
redirectTo: 'https://example.com/callback?code=session',
})
expect(capturedOptions).not.toBeNull()
})

test('authorize uses default scopes when none requested', async () => {
let resolveCapturedOptions:
| ((value: CompleteAuthorizationOptions) => void)
Expand Down
Loading
Loading