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
81 changes: 57 additions & 24 deletions apps/docs/content/_partials/oauth_pkce_flow.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,58 @@ await supabase.auth.signInWithOAuth({

In the server, you need to handle the redirect to the OAuth provider's authentication endpoint. The `signInWithOAuth` method returns the endpoint URL, which you can redirect to.

```js
import { createClient, type Provider } from '@supabase/supabase-js'
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
const provider = 'provider' as Provider
const redirect = (url: string) => {}
<Admonition type="caution">

// ---cut---
const { data, error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: 'http://example.com/auth/callback',
},
})
Use a [server client](/docs/guides/auth/server-side/creating-a-client) from `@supabase/ssr`, and send its cookies with the redirect. `signInWithOAuth` stores the PKCE code verifier in a cookie. When that `Set-Cookie` header doesn't reach the browser, the callback can't exchange the code for a session.

</Admonition>

```ts
import { createServerClient, parseCookieHeader, serializeCookieHeader } from '@supabase/ssr'
import type { Provider } from '@supabase/supabase-js'

// A route handler that receives the incoming Request
async function handler(request: Request) {
const headers = new Headers()
const provider = 'provider' as Provider

const supabase = createServerClient('https://your-project-id.supabase.co', 'sb_publishable_...', {
cookies: {
getAll() {
return parseCookieHeader(request.headers.get('Cookie') ?? '') as {
name: string
value: string
}[]
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) =>
headers.append('Set-Cookie', serializeCookieHeader(name, value, options))
)
Object.entries(cacheHeaders).forEach(([key, value]) => headers.set(key, value))
},
},
})

if (data.url) {
redirect(data.url) // use the redirect API for your server framework
const { data, error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: 'http://example.com/auth/callback',
},
})

if (error) {
throw error
}

// Redirect with `headers` so the browser stores the code verifier cookie.
// Frameworks usually wrap this, for example `redirect(data.url, { headers })` in Remix.
headers.set('Location', data.url)
return new Response(null, { status: 303, headers })
}
```

When your framework sets cookies on the response for you, such as `cookies()` in Next.js or `event.cookies` in SvelteKit, write to that API in `setAll` instead. The cookie is then already on the response, and the redirect needs no extra headers.

</TabPanel>

</Tabs>
Expand Down Expand Up @@ -111,26 +144,26 @@ export async function GET(request: Request) {
Create a new file at `src/routes/auth/callback/+server.js` and populate with the following:

```js name=src/routes/auth/callback/+server.js
import { redirect } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit'

export const GET = async (event) => {
const {
url,
locals: { supabase }
} = event;
const code = url.searchParams.get('code') as string;
const next = url.searchParams.get('next') ?? '/';
const {
url,
locals: { supabase },
} = event
const code = url.searchParams.get('code')
const next = url.searchParams.get('next') ?? '/'

if (code) {
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (!error) {
redirect(303, `/${next.slice(1)}`);
redirect(303, `/${next.slice(1)}`)
}
}

// return the user to an error page with instructions
redirect(303, '/auth/auth-code-error');
};
redirect(303, '/auth/auth-code-error')
}
```

</TabPanel>
Expand Down
2 changes: 2 additions & 0 deletions apps/docs/content/guides/self-hosting/docker.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ The script supports Linux only (Debian/Ubuntu and RHEL/CentOS/Fedora) and will:

The shortened link points to [setup.sh](https://raw.githubusercontent.com/supabase/supabase/refs/heads/master/docker/setup.sh) - you can inspect it before running. Use `-y` to run non-interactively with default values.

When the script installs Docker for you, it also adds the user to the `docker` group. Log out and back in before continuing, otherwise the `docker` commands below need `sudo`.

After the script finishes, start the stack:

```sh
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ database_id = "3e9246cb-d592-4051-93c8-53e4e555711c"

The reason behind this limitation is that the auth helpers library lacks a direct mechanism for performing server-side redirects, as each framework handles redirects differently. However, the library does offer a URL through the data property it returns, which should be used for the purpose of redirection.

With the PKCE flow in `@supabase/ssr`, `signInWithOAuth` stores the code verifier in a cookie. When your `setAll` collects `Set-Cookie` headers into a `Headers` object, as in Remix, pass them on the redirect. Otherwise the browser never stores the code verifier and the callback exchange fails. In Next.js and SvelteKit, the framework's cookie API writes to the response for you, so the redirect needs nothing extra.

**Next.js:**

```ts
Expand Down Expand Up @@ -37,10 +39,14 @@ throw redirect(303, data.url)

```ts
import { redirect } from "@remix-run/node"; // or cloudflare/deno
// Your server client factory: createServerClient with a setAll that appends
// Set-Cookie to `headers`, returning both. See the PKCE flow's Server example.
import { createClient } from "~/lib/supabase.server";
...
const { supabase, headers } = createClient(request)
const { data } = await supabase.auth.signInWithOAuth({
provider: 'github',
})

return redirect(data.url)
return redirect(data.url, { headers })
```
1 change: 1 addition & 0 deletions apps/docs/public/humans.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Alex Hsu
Alexander Alexandrov
Alexander Korotkov
Ali Waseem
Alice Crosbie
Allan S
Amir Issaei
Amogh Rao
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ export const AddNewFactorModal = ({ visible, onClose }: AddNewFactorModalProps)
enabled: enableAuthRecoveryCodes,
})

const recoveryCodesGenerateMutation = useRecoveryCodesGenerateMutation()
const recoveryCodesGenerateMutation = useRecoveryCodesGenerateMutation({
onSettled: () => {
onClose()
setIsRecoveryCodesModalOpen(true)
},
})

const [isRecoveryCodesModalOpen, setIsRecoveryCodesModalOpen] = useState<boolean>(false)

Expand All @@ -57,15 +62,19 @@ export const AddNewFactorModal = ({ visible, onClose }: AddNewFactorModalProps)
visible={visible && Boolean(data)}
factorName={data?.friendly_name ?? ''}
factor={data as Extract<typeof data, { type: 'totp' }>}
isLoading={isEnrolling || (enableAuthRecoveryCodes && isRecoveryCodesStatusPending)}
isLoading={
isEnrolling ||
(enableAuthRecoveryCodes &&
(isRecoveryCodesStatusPending || recoveryCodesGenerateMutation.isPending))
}
onClose={async () => {
if (enableAuthRecoveryCodes) {
const { data: currentRecoveryCodesStatus } = await refetchRecoveryCodesStatus()
const shouldGenerateRecoveryCodes = currentRecoveryCodesStatus?.status === 'unenrolled'

if (shouldGenerateRecoveryCodes) {
recoveryCodesGenerateMutation.mutate({})
setIsRecoveryCodesModalOpen(true)
return
}
}
onClose()
Expand Down Expand Up @@ -223,7 +232,7 @@ const SecondStep = ({
title={`Verify new factor ${factorName}`}
confirmLabel="Confirm"
confirmLabelLoading="Confirming"
loading={isVerifying}
loading={isVerifying || isLoading}
onCancel={() => {
// If a factor has been created (but not verified), unenroll it. This will be run as a
// side effect so that it's not confusing to the user why the modal stays open while
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { RecoveryCodesModal } from './RecoveryCodesModal'
import { useRecoveryCodesGenerateMutation } from '@/data/recovery-codes/recovery-codes-generate-mutation'

export const GenerateRecoveryCodesModal = () => {
const recoveryCodesGenerateMutation = useRecoveryCodesGenerateMutation()
const recoveryCodesGenerateMutation = useRecoveryCodesGenerateMutation({
onSettled: () => setOpen(true),
})
const [open, setOpen] = useState(false)

return (
Expand All @@ -17,11 +19,14 @@ export const GenerateRecoveryCodesModal = () => {
description="Recovery codes are important to ensure you can recover your account if you loose access to your MFA."
actions={
<>
<span aria-live="polite" className="sr-only">
{recoveryCodesGenerateMutation.isPending ? 'Generating your recovery codes...' : ''}
</span>
<Button
onClick={() => {
setOpen(true)
recoveryCodesGenerateMutation.mutate({})
}}
loading={recoveryCodesGenerateMutation.isPending}
>
Generate recovery codes
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ export const RegenerateRecoveryCodesModal = () => {
const [showConfirm, setShowConfirm] = useState(false)
const [open, setOpen] = useState(false)

const recoveryCodesRegenerateMutation = useRecoveryCodesRegenerateMutation()
const recoveryCodesRegenerateMutation = useRecoveryCodesRegenerateMutation({
onSettled: () => {
setShowConfirm(false)
setOpen(true)
},
})

return (
<>
Expand All @@ -24,8 +29,6 @@ export const RegenerateRecoveryCodesModal = () => {
confirmLabel="Regenerate"
loading={recoveryCodesRegenerateMutation.isPending}
onConfirm={() => {
setShowConfirm(false)
setOpen(true)
recoveryCodesRegenerateMutation.mutate()
}}
onCancel={() => setShowConfirm(false)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const TOTPFactors = () => {
const totpFactors = data?.totp ?? []
const canAddApp = isSuccess && totpFactors.length < 2
const shouldShowLockoutWarning = isSuccess && totpFactors.length === 1
const shouldVerifyRecoveryCodes = enableAuthRecoveryCodes
const shouldVerifyRecoveryCodes = enableAuthRecoveryCodes && totpFactors.length > 0

const { data: recoveryCodesStatus } = useRecoveryCodesStatusQuery({
enabled: shouldVerifyRecoveryCodes,
Expand Down
48 changes: 33 additions & 15 deletions apps/studio/components/interfaces/Auth/AuditLogsForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { useFlag, useParams } from 'common'
import { useEffect } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
Expand All @@ -21,6 +21,8 @@ import { AlertError } from '@/components/ui/AlertError'
import { InlineLink } from '@/components/ui/InlineLink'
import { useAuthConfigQuery } from '@/data/auth/auth-config-query'
import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutation'
import { pickLogsQueryBuilder } from '@/data/logs/logs-endpoint'
import { safeSql } from '@/data/logs/safe-analytics-sql'
import { useTablesQuery } from '@/data/tables/tables-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
Expand All @@ -31,9 +33,36 @@ const schema = z.object({

const AUDIT_LOG_ENTRIES_TABLE = 'audit_log_entries'

const AUTH_AUDIT_LOGS_QUERY = safeSql`
select
cast(timestamp as datetime) as timestamp,
event_message,
metadata
from auth_audit_logs
limit 10
`

const AUTH_AUDIT_LOGS_QUERY_OTEL = safeSql`
select
timestamp,
event_message,
log_attributes
from logs
where source = 'auth_audit_logs'
order by timestamp desc
limit 10
`

export const AuditLogsForm = () => {
const { ref: projectRef } = useParams()
const useOtel = useFlag('otelLegacyLogs')
const { data: project } = useSelectedProjectQuery()
const authAuditLogsQuery = pickLogsQueryBuilder(
useOtel,
AUTH_AUDIT_LOGS_QUERY_OTEL,
AUTH_AUDIT_LOGS_QUERY
)
const authAuditLogsUrl = `/project/${projectRef}/logs/explorer?q=${encodeURIComponent(authAuditLogsQuery)}`

const { can: canUpdateConfig } = useAsyncCheckPermissions(
PermissionAction.UPDATE,
Expand Down Expand Up @@ -141,13 +170,7 @@ export const AuditLogsForm = () => {
table.
<br />
You can disable this to reduce disk usage while still accessing logs
through the{' '}
<InlineLink
href={`/project/${projectRef}/logs/explorer?q=select%0A++cast(timestamp+as+datetime)+as+timestamp%2C%0A++event_message%2C+metadata+%0Afrom+auth_audit_logs+%0Alimit+10%0A`}
>
Auth logs
</InlineLink>
.
through the <InlineLink href={authAuditLogsUrl}>Auth logs</InlineLink>.
</p>
}
>
Expand All @@ -169,13 +192,8 @@ export const AuditLogsForm = () => {
description={
<p>
Future audit logs will only appear in the project’s{' '}
<InlineLink
href={`/project/${projectRef}/logs/explorer?q=select%0A++cast(timestamp+as+datetime)+as+timestamp%2C%0A++event_message%2C+metadata+%0Afrom+auth_audit_logs+%0Alimit+10%0A`}
>
auth logs
</InlineLink>
. You are responsible for backing up, copying, or migrating existing data
from the{' '}
<InlineLink href={authAuditLogsUrl}>auth logs</InlineLink>. You are
responsible for backing up, copying, or migrating existing data from the{' '}
<code className="text-code-inline break-keep!">
{AUDIT_LOG_ENTRIES_TABLE}
</code>{' '}
Expand Down
Loading
Loading