Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
12 changes: 12 additions & 0 deletions packages/shared/src/oauth-messages.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,14 @@
export const invalidRedirectUriMessage =
'Invalid redirect URI. The redirect URI provided does not match any registered URI for this client.'

Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
export const invalidClientIdMismatchMessage =
'Invalid client. The clientId provided does not match to this client.'

export function canResetStoredClientForMessage(
message: string | null | undefined,
) {
return (
message === invalidRedirectUriMessage ||
message === invalidClientIdMismatchMessage
)
}
150 changes: 85 additions & 65 deletions packages/worker/client/routes/oauth-authorize.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
sectionTitleCss,
stackedPageCss,
} from '#client/styles/style-primitives.ts'
import { invalidRedirectUriMessage } from '@kody-internal/shared/oauth-messages.ts'
import { canResetStoredClientForMessage } from '@kody-internal/shared/oauth-messages.ts'

type OAuthAuthorizeInfo = {
client: { id: string; name: string }
Expand All @@ -35,10 +35,6 @@ type OAuthAuthorizeStatus = 'idle' | 'loading' | 'ready' | 'error'
type OAuthAuthorizeMessage = { type: 'error' | 'info'; text: string }
type OAuthAuthorizeDecision = 'approve' | 'deny' | 'reset-client'

function isInvalidRedirectUriMessage(message: string | null | undefined) {
return message === invalidRedirectUriMessage
}

function getSearchParams() {
return typeof window === 'undefined'
? new URLSearchParams()
Expand Down Expand Up @@ -68,6 +64,15 @@ export function OAuthAuthorizeRoute(handle: Handle) {
return error ? `Authorization error: ${error}` : null
}

function readResetErrorDescription() {
const queryError = readQueryError()
if (canResetStoredClientForMessage(queryError)) {
return queryError
}
const messageText = message?.text
return canResetStoredClientForMessage(messageText) ? messageText : null
}

async function loadInfo() {
status = 'loading'

Expand Down Expand Up @@ -151,7 +156,18 @@ export function OAuthAuthorizeRoute(handle: Handle) {
body.set('email', email)
body.set('password', password)
}
const response = await fetch(window.location.href, {
let submitUrl = window.location.href
if (decision === 'reset-client') {
const resetErrorDescription = readResetErrorDescription()
if (resetErrorDescription) {
const url = new URL(submitUrl)
if (!url.searchParams.get('error_description')) {
url.searchParams.set('error_description', resetErrorDescription)
submitUrl = url.toString()
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
}
const response = await fetch(submitUrl, {
method: 'POST',
headers: {
Accept: 'application/json',
Expand Down Expand Up @@ -218,16 +234,14 @@ export function OAuthAuthorizeRoute(handle: Handle) {
const scopes = info?.scopes ?? []
const scopeLabel =
scopes.length > 0 ? scopes.join(', ') : 'No scopes requested.'
const queryError = readQueryError()
const resetErrorDescription = readResetErrorDescription()
const sessionEmail = session?.email ?? ''
const isSessionReady = sessionStatus === 'ready'
const isSessionLoading =
sessionStatus === 'loading' || sessionStatus === 'idle'
const isLoggedIn = isSessionReady && Boolean(sessionEmail)
const showResetClientCard =
(isInvalidRedirectUriMessage(queryError) ||
isInvalidRedirectUriMessage(message?.text)) &&
!resetCompleted
const showResetClientCard = Boolean(resetErrorDescription) && !resetCompleted
const showAuthorizeForm = !resetCompleted
const actionsDisabled =
status !== 'ready' || Boolean(submittingDecision) || isSessionLoading
const resetClientDisabled =
Expand Down Expand Up @@ -270,7 +284,11 @@ export function OAuthAuthorizeRoute(handle: Handle) {
>
Signed in as {sessionEmail}
</p>
<p css={descriptionCss}>Approve to continue with this account.</p>
<p css={descriptionCss}>
{resetCompleted
? 'Start the connection again from your client to continue with this account.'
: 'Approve to continue with this account.'}
</p>
</section>
) : null}
{status === 'loading' ? (
Expand Down Expand Up @@ -308,59 +326,61 @@ export function OAuthAuthorizeRoute(handle: Handle) {
) : null}
</section>
) : null}
<form
css={{
...cardCss,
opacity: formReady ? 1 : 0.7,
}}
on={{ submit: handleSubmit }}
>
{!isLoggedIn && isSessionReady ? (
<>
<label css={fieldCss}>
<span css={fieldLabelCss}>Email</span>
<input
type="email"
name="email"
required
autoComplete="email"
placeholder="you@example.com"
disabled={actionsDisabled}
css={inputCss}
/>
</label>
<label css={fieldCss}>
<span css={fieldLabelCss}>Password</span>
<input
type="password"
name="password"
required
autoComplete="current-password"
placeholder="Enter your password"
disabled={actionsDisabled}
css={inputCss}
/>
</label>
</>
) : null}
<div css={{ display: 'flex', gap: spacing.sm, flexWrap: 'wrap' }}>
<button
type="submit"
disabled={actionsDisabled}
css={primaryButtonCss}
>
{authorizeLabel}
</button>
<button
type="button"
disabled={actionsDisabled}
on={{ click: () => submitDecision('deny') }}
css={secondaryButtonCss}
>
Deny
</button>
</div>
</form>
{showAuthorizeForm ? (
<form
css={{
...cardCss,
opacity: formReady ? 1 : 0.7,
}}
on={{ submit: handleSubmit }}
>
{!isLoggedIn && isSessionReady ? (
<>
<label css={fieldCss}>
<span css={fieldLabelCss}>Email</span>
<input
type="email"
name="email"
required
autoComplete="email"
placeholder="you@example.com"
disabled={actionsDisabled}
css={inputCss}
/>
</label>
<label css={fieldCss}>
<span css={fieldLabelCss}>Password</span>
<input
type="password"
name="password"
required
autoComplete="current-password"
placeholder="Enter your password"
disabled={actionsDisabled}
css={inputCss}
/>
</label>
</>
) : null}
<div css={{ display: 'flex', gap: spacing.sm, flexWrap: 'wrap' }}>
<button
type="submit"
disabled={actionsDisabled}
css={primaryButtonCss}
>
{authorizeLabel}
</button>
<button
type="button"
disabled={actionsDisabled}
on={{ click: () => submitDecision('deny') }}
css={secondaryButtonCss}
>
Deny
</button>
</div>
</form>
) : null}
<a href="/" css={mutedLinkCss}>
Back home
</a>
Expand Down
15 changes: 13 additions & 2 deletions packages/worker/src/oauth-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { render } from '#app/render.ts'
import { createDb, usersTable } from './db.ts'
import { wantsJson } from './utils.ts'
import { verifyPassword } from '@kody-internal/shared/password-hash.ts'
import { canResetStoredClientForMessage } from '@kody-internal/shared/oauth-messages.ts'

export const oauthPaths = {
authorize: '/oauth/authorize',
Expand Down Expand Up @@ -91,6 +92,13 @@ function readClientIdFromAuthorizeRequest(request: Request) {
return clientId ? clientId : null
}

function readAuthorizeErrorDescription(request: Request) {
const errorDescription = new URL(request.url).searchParams
.get('error_description')
?.trim()
return errorDescription ? errorDescription : null
}

function isLoopbackHostname(hostname: string) {
return (
hostname === 'localhost' ||
Expand Down Expand Up @@ -182,10 +190,13 @@ async function handleResetClientRequest(
helpers,
request,
)
if (!redirectUriMismatch) {
const queryErrorDescription = readAuthorizeErrorDescription(request)
const canResetStoredClient =
redirectUriMismatch || canResetStoredClientForMessage(queryErrorDescription)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
if (!canResetStoredClient) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return respondAuthorizeError(
request,
'Stored client cleanup is only available for redirect URI mismatches.',
'Stored client cleanup is only available for stale or mismatched client registrations.',
400,
'invalid_request',
)
Expand Down
71 changes: 70 additions & 1 deletion packages/worker/src/oauth-handlers.workers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from '@cloudflare/workers-oauth-provider'
import { createAuthCookie, setAuthSessionSecret } from '#app/auth-session.ts'
import { createPasswordHash } from '@kody-internal/shared/password-hash.ts'
import { invalidClientIdMismatchMessage } from '@kody-internal/shared/oauth-messages.ts'
import {
handleAuthorizeInfo,
handleAuthorizeRequest,
Expand Down Expand Up @@ -332,6 +333,74 @@ test('reset client deletes matching grants and client registration', async () =>
expect(deletedClientIds).toEqual(['client-123'])
})

test('reset client deletes stale client registrations after invalid client mismatch', async () => {
const revokedGrantIds = new Array<string>()
const deletedClientIds = new Array<string>()
const userId = await createStableUserIdFromEmail('user@example.com')
const helpers = createHelpers({
listUserGrants: async (requestedUserId) => {
expect(requestedUserId).toBe(userId)
return {
items: [
{
id: 'grant-1',
clientId: 'client-123',
userId,
scope: ['profile'],
metadata: {},
createdAt: 0,
},
{
id: 'grant-2',
clientId: 'client-123',
userId,
scope: ['email'],
metadata: {},
createdAt: 0,
},
],
}
},
revokeGrant: async (grantId, requestedUserId) => {
expect(requestedUserId).toBe(userId)
revokedGrantIds.push(grantId)
},
deleteClient: async (clientId) => {
deletedClientIds.push(clientId)
},
})
setAuthSessionSecret(cookieSecret)
const cookie = await createAuthCookie(
{ id: 'session-id', email: 'user@example.com', rememberMe: false },
false,
)

const response = await handleAuthorizeRequest(
new Request(
`https://example.com/oauth/authorize?client_id=client-123&redirect_uri=${encodeURIComponent('https://example.com/callback')}&error_description=${encodeURIComponent(invalidClientIdMismatchMessage)}`,
{
method: 'POST',
headers: {
Accept: 'application/json',
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ decision: 'reset-client' }),
},
),
createEnv(helpers),
)

expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual({
ok: true,
message:
'Deleted the stored client records for this connection. Start the connection again from your client to create a fresh trusted client.',
})
expect(revokedGrantIds).toEqual(['grant-1', 'grant-2'])
expect(deletedClientIds).toEqual(['client-123'])
})

test('reset client is rejected when the request is not a redirect mismatch', async () => {
const response = await handleAuthorizeRequest(
new Request(
Expand All @@ -352,7 +421,7 @@ test('reset client is rejected when the request is not a redirect mismatch', asy
await expect(response.json()).resolves.toEqual({
ok: false,
error:
'Stored client cleanup is only available for redirect URI mismatches.',
'Stored client cleanup is only available for stale or mismatched client registrations.',
code: 'invalid_request',
})
})
Expand Down
Loading