Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

auth report improvements (#39013)

Jordi Enricb5a638bfc61a
diff --git a/apps/studio/components/interfaces/Reports/Reports.utils.tsx b/apps/studio/components/interfaces/Reports/Reports.utils.tsx
index f0eef8b93ad..0be4bb73107 100644
--- a/apps/studio/components/interfaces/Reports/Reports.utils.tsx
+++ b/apps/studio/components/interfaces/Reports/Reports.utils.tsx
@@ -3,6 +3,12 @@ import dayjs from 'dayjs'
import useDbQuery, { DbQueryHook } from 'hooks/analytics/useDbQuery'
import useLogsQuery, { LogsQueryHook } from 'hooks/analytics/useLogsQuery'
import type { BaseQueries, PresetConfig, ReportQuery } from './Reports.types'
+import {
+ isUnixMicro,
+ unixMicroToIsoTimestamp,
+} from 'components/interfaces/Settings/Logs/Logs.utils'
+import { REPORT_STATUS_CODE_COLORS } from 'data/reports/report.utils'
+import { getHttpStatusCodeInfo } from 'lib/http-status-codes'
/**
* Converts a query params string to an object
@@ -73,3 +79,108 @@ export const formatTimestamp = (
return 'Invalid Date'
}
}
+
+/**
+ * Extracts distinct status codes from log data rows
+ */
+export function extractStatusCodesFromData(data: any[]): string[] {
+ const statusCodes = new Set<string>()
+
+ data.forEach((item: any) => {
+ if (item.status_code !== undefined && item.status_code !== null) {
+ statusCodes.add(String(item.status_code))
+ }
+ })
+
+ return Array.from(statusCodes).sort()
+}
+
+/**
+ * Generates chart attributes for status codes with labels and colors
+ */
+export function generateStatusCodeAttributes(statusCodes: string[]) {
+ return statusCodes.map((code) => ({
+ attribute: code,
+ label: `${code} ${getHttpStatusCodeInfo(parseInt(code, 10)).label}`,
+ color: REPORT_STATUS_CODE_COLORS[code] || REPORT_STATUS_CODE_COLORS.default,
+ }))
+}
+
+/**
+ * Pivots rows of { timestamp, status_code, count } into { timestamp, [status_code]: count }
+ * and normalizes timestamps to ISO strings (UTC), filling missing codes with 0 per timestamp
+ */
+export function transformStatusCodeData(data: any[], statusCodes: string[]) {
+ const pivotedData = data.reduce((acc: Record<string, any>, d: any) => {
+ const timestamp = isUnixMicro(d.timestamp)
+ ? unixMicroToIsoTimestamp(d.timestamp)
+ : dayjs.utc(d.timestamp).toISOString()
+ if (!acc[timestamp]) {
+ acc[timestamp] = { timestamp }
+ statusCodes.forEach((code) => {
+ acc[timestamp][code] = 0
+ })
+ }
+ const codeKey = String(d.status_code)
+ if (codeKey in acc[timestamp]) {
+ acc[timestamp][codeKey] = d.count
+ }
+ return acc
+ }, {})
+
+ return Object.values(pivotedData)
+}
+
+/**
+ * Extract distinct string values for a given field from data rows
+ */
+export function extractDistinctValuesFromData(data: any[], field: string): string[] {
+ const values = new Set<string>()
+ data.forEach((item: any) => {
+ if (item[field] !== undefined && item[field] !== null) {
+ values.add(String(item[field]))
+ }
+ })
+ return Array.from(values).sort()
+}
+
+/**
+ * Generates chart attributes from a list of category values
+ */
+export function generateCategoryAttributes(
+ values: string[],
+ labelResolver?: (v: string) => string
+) {
+ return values.map((v) => ({
+ attribute: v,
+ label: labelResolver ? labelResolver(v) : v,
+ }))
+}
+
+/**
+ * Pivot rows of { timestamp, [categoryField], count } into { timestamp, [category]: count }
+ */
+export function transformCategoricalCountData(
+ data: any[],
+ categoryField: string,
+ categories: string[]
+) {
+ const pivotedData = data.reduce((acc: Record<string, any>, d: any) => {
+ const timestamp = isUnixMicro(d.timestamp)
+ ? unixMicroToIsoTimestamp(d.timestamp)
+ : dayjs.utc(d.timestamp).toISOString()
+ if (!acc[timestamp]) {
+ acc[timestamp] = { timestamp }
+ categories.forEach((c) => {
+ acc[timestamp][c] = 0
+ })
+ }
+ const key = String(d[categoryField])
+ if (key in acc[timestamp]) {
+ acc[timestamp][key] = d.count
+ }
+ return acc
+ }, {})
+
+ return Object.values(pivotedData)
+}
diff --git a/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx b/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx
index 57c3c07f833..01f9ed5f004 100644
--- a/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx
+++ b/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx
@@ -117,6 +117,7 @@ export const ReportChartV2 = ({
) : (
<div className="w-full">
<ComposedChart
+ chartId={report.id}
attributes={dynamicAttributes}
data={filledChartData}
format={report.format ?? undefined}
diff --git a/apps/studio/components/interfaces/Reports/v2/ReportSectionHeader.tsx b/apps/studio/components/interfaces/Reports/v2/ReportSectionHeader.tsx
new file mode 100644
index 00000000000..c00b9d3046c
--- /dev/null
+++ b/apps/studio/components/interfaces/Reports/v2/ReportSectionHeader.tsx
@@ -0,0 +1,49 @@
+import { Link, Check } from 'lucide-react'
+import { useState } from 'react'
+
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { copyToClipboard } from 'ui'
+
+interface ReportSectionHeaderProps {
+ id: string
+ title: string
+ description: string
+}
+
+export const ReportSectionHeader = ({ id, title, description }: ReportSectionHeaderProps) => {
+ const [copiedLink, setCopiedLink] = useState<string | null>(null)
+
+ const copyLinkToClipboard = async () => {
+ // [jordi] We want to keep the existing query params (filters)
+ // But if the user has an anchor in the URL,
+ // we remove it and add the one for this section
+ // This is so the shared URL shows the exact same report as the one the user is on
+ const url = `${window.location.href.split('#')[0]}#${id}`
+ await copyToClipboard(url)
+ setCopiedLink(id)
+ setTimeout(() => setCopiedLink(null), 2000)
+ }
+
+ return (
+ <div className="flex flex-col gap-1 mb-4 group">
+ <div
+ className="flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity"
+ onClick={copyLinkToClipboard}
+ >
+ <h3 className="text-foreground text-lg font-medium">{title}</h3>
+ <ButtonTooltip
+ type="text"
+ icon={copiedLink === id ? <Check size={14} /> : <Link size={14} />}
+ className="w-7 h-7 opacity-0 group-hover:opacity-100 transition-opacity"
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: copiedLink === id ? 'Link copied!' : 'Copy link to section',
+ },
+ }}
+ />
+ </div>
+ <p className="text-foreground-light text-sm">{description}</p>
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/Charts/ChartHeader.tsx b/apps/studio/components/ui/Charts/ChartHeader.tsx
index 60b3e870c3e..86a83834146 100644
--- a/apps/studio/components/ui/Charts/ChartHeader.tsx
+++ b/apps/studio/components/ui/Charts/ChartHeader.tsx
@@ -15,6 +15,7 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { formatBytes } from 'lib/helpers'
import { numberFormatter } from './Charts.utils'
import { useChartHoverState } from './useChartHoverState'
+import { InfoTooltip } from 'ui-patterns/info-tooltip'
export interface ChartHeaderProps {
title?: string
@@ -41,6 +42,7 @@ export interface ChartHeaderProps {
isNetworkChart?: boolean
attributes?: any[]
sql?: string
+ titleTooltip?: string
}
export const ChartHeader = ({
@@ -68,6 +70,7 @@ export const ChartHeader = ({
isNetworkChart = false,
attributes,
sql,
+ titleTooltip,
}: ChartHeaderProps) => {
const { hoveredIndex, isHovered, isCurrentChart, setHover, clearHover } = useChartHoverState(
syncId || 'default'
@@ -162,9 +165,12 @@ export const ChartHeader = ({
const chartTitle = (
<div className="flex flex-row items-center gap-x-2">
- <h3 className={'text-foreground-lighter ' + (minimalHeader ? 'text-xs' : 'text-sm')}>
- {title}
- </h3>
+ <div className="flex flex-row items-center gap-x-2">
+ <h3 className={'text-foreground-lighter ' + (minimalHeader ? 'text-xs' : 'text-sm')}>
+ {title}
+ </h3>
+ {titleTooltip && <InfoTooltip>{titleTooltip}</InfoTooltip>}
+ </div>
{docsUrl && (
<ButtonTooltip
type="text"
diff --git a/apps/studio/components/ui/Charts/ChartHighlightActions.tsx b/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
index 7a66eaef0bc..8a0be73774f 100644
--- a/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
+++ b/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
@@ -19,6 +19,7 @@ export type ChartHighlightActionContext = {
start: string
end: string
clear: () => void
+ chartId?: string
}
export type ChartHighlightAction = {
@@ -34,10 +35,12 @@ export const ChartHighlightActions = ({
chartHighlight,
updateDateRange,
actions,
+ chartId,
}: {
chartHighlight?: ChartHighlight
updateDateRange?: UpdateDateRange
actions?: ChartHighlightAction[]
+ chartId?: string
}) => {
const { left: selectedRangeStart, right: selectedRangeEnd, clearHighlight } = chartHighlight ?? {}
const [isOpen, setIsOpen] = useState(!!chartHighlight?.popoverPosition)
@@ -48,7 +51,7 @@ export const ChartHighlightActions = ({
const ctx: ChartHighlightActionContext | undefined =
selectedRangeStart && selectedRangeEnd && clearHighlight
- ? { start: selectedRangeStart, end: selectedRangeEnd, clear: clearHighlight }
+ ? { start: selectedRangeStart, end: selectedRangeEnd, clear: clearHighlight, chartId }
: undefined
const defaultActions: ChartHighlightAction[] = useMemo(() => {
@@ -110,7 +113,7 @@ export const ChartHighlightActions = ({
<DropdownMenuItem asChild key={action.id} disabled={disabled} className={cn('group')}>
<button
disabled={disabled}
- onClick={() => ctx && action.onSelect(ctx)}
+ onClick={() => ctx && action.onSelect({ ...ctx })}
className="w-full flex items-center gap-1.5"
>
{action.icon}
diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsx
index 8177227a80e..94ef08ac6f9 100644
--- a/apps/studio/components/ui/Charts/ComposedChart.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx
@@ -39,6 +39,7 @@ import { ChartHighlight } from './useChartHighlight'
import { useChartHoverState } from './useChartHoverState'
export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
+ chartId?: string
attributes: MultiAttribute[]
yAxisKey: string
xAxisKey: string
@@ -68,6 +69,7 @@ export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
}
export function ComposedChart({
+ chartId,
data,
attributes,
yAxisKey,
@@ -103,6 +105,7 @@ export function ComposedChart({
docsUrl,
sql,
highlightActions,
+ titleTooltip,
}: ComposedChartProps) {
const { resolvedTheme } = useTheme()
const { hoveredIndex, syncTooltip, setHover, clearHover } = useChartHoverState(
@@ -302,6 +305,7 @@ export function ComposedChart({
className={className}
attribute={title}
format={format}
+ titleTooltip={titleTooltip}
/>
)
}
@@ -312,6 +316,7 @@ export function ComposedChart({
hideHighlightedValue={hideHighlightedValue}
title={title}
format={format}
+ titleTooltip={titleTooltip}
customDateFormat={customDateFormat}
highlightedValue={formatHighlightedValue(resolvedHighlightedValue)}
highlightedLabel={resolvedHighlightedLabel}
@@ -498,6 +503,7 @@ export function ComposedChart({
chartHighlight={chartHighlight}
updateDateRange={updateDateRange}
actions={highlightActions}
+ chartId={chartId}
/>
</Container>
{data && (
diff --git a/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx b/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx
index 93bb8102bb9..3cf4e0d6f9d 100644
--- a/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx
+++ b/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx
@@ -13,6 +13,7 @@ interface NoDataPlaceholderProps {
className?: string
size: Parameters<typeof useChartSize>[0]
isFullHeight?: boolean
+ titleTooltip?: string
}
const NoDataPlaceholder = ({
attribute,
@@ -22,13 +23,19 @@ const NoDataPlaceholder = ({
className = '',
size,
isFullHeight = false,
+ titleTooltip,
}: NoDataPlaceholderProps) => {
const { minHeight } = useChartSize(size)
return (
<div className={cn(isFullHeight && 'h-full')}>
{attribute !== undefined && (
- <ChartHeader title={attribute} format={format} highlightedValue={0} />
+ <ChartHeader
+ title={attribute}
+ format={format}
+ highlightedValue={0}
+ titleTooltip={titleTooltip}
+ />
)}
<div
className={cn(
diff --git a/apps/studio/data/reports/v2/auth.config.ts b/apps/studio/data/reports/v2/auth.config.ts
index 89b0d8d267b..0c5b3b9b047 100644
--- a/apps/studio/data/reports/v2/auth.config.ts
+++ b/apps/studio/data/reports/v2/auth.config.ts
@@ -5,15 +5,30 @@ import { ReportConfig, ReportDataProviderAttribute } from './reports.types'
import { NumericFilter } from 'components/interfaces/Reports/v2/ReportsNumericFilter'
import { fetchLogs } from 'data/reports/report.utils'
import z from 'zod'
+import {
+ extractStatusCodesFromData,
+ generateStatusCodeAttributes,
+ transformCategoricalCountData,
+ transformStatusCodeData,
+} from 'components/interfaces/Reports/Reports.utils'
+import { AUTH_ERROR_CODES } from 'common/constants/auth-error-codes'
+
+const AUTH_ERROR_CODE_LIST = Object.entries(AUTH_ERROR_CODES).map(([key, value]) => ({
+ key,
+ description: value.description,
+}))
const METRIC_KEYS = [
'ActiveUsers',
'SignInAttempts',
'PasswordResetRequests',
'TotalSignUps',
- 'SignInLatency',
- 'SignUpLatency',
+ 'SignInProcessingTimeBasic',
+ 'SignInProcessingTimePercentiles',
+ 'SignUpProcessingTimeBasic',
+ 'SignUpProcessingTimePercentiles',
'ErrorsByStatus',
+ 'ErrorsByAuthCode',
]
type MetricKey = (typeof METRIC_KEYS)[number]
@@ -22,28 +37,35 @@ const AUTH_REPORT_SQL: Record<
MetricKey,
(interval: AnalyticsInterval, filters?: AuthReportFilters) => string
> = {
- ActiveUsers: (interval) => {
+ ActiveUsers: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
return `
--active-users
select
timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(f.event_message, "$.provider"), \'unknown\') as provider,' : ''}
count(distinct json_value(f.event_message, "$.auth_event.actor_id")) as count
from auth_logs f
where json_value(f.event_message, "$.auth_event.action") in (
'login', 'user_signedup', 'token_refreshed', 'user_modified',
'user_recovery_requested', 'user_reauthenticate_requested'
)
- group by timestamp
- order by timestamp desc
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
`
},
- SignInAttempts: (interval) => {
+ SignInAttempts: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
return `
--sign-in-attempts
SELECT
timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(event_message, "$.provider"), \'unknown\') as provider,' : ''}
CASE
WHEN JSON_VALUE(event_message, "$.provider") IS NOT NULL
AND JSON_VALUE(event_message, "$.provider") != ''
@@ -61,78 +83,130 @@ const AUTH_REPORT_SQL: Record<
WHERE
JSON_VALUE(event_message, "$.action") = 'login'
AND JSON_VALUE(event_message, "$.metering") = "true"
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
GROUP BY
- timestamp, login_type_provider
+ timestamp, login_type_provider${groupByProvider ? ', provider' : ''}
ORDER BY
- timestamp desc, login_type_provider
+ timestamp desc, login_type_provider${groupByProvider ? ', provider' : ''}
`
},
- PasswordResetRequests: (interval) => {
+ PasswordResetRequests: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
return `
--password-reset-requests
select
timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(f.event_message, "$.provider"), \'unknown\') as provider,' : ''}
count(*) as count
from auth_logs f
where json_value(f.event_message, "$.auth_event.action") = 'user_recovery_requested'
- group by timestamp
- order by timestamp desc
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
`
},
- TotalSignUps: (interval) => {
+ TotalSignUps: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
return `
--total-signups
select
timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(event_message, "$.provider"), \'unknown\') as provider,' : ''}
count(*) as count
from auth_logs
where json_value(event_message, "$.auth_event.action") = 'user_signedup'
- group by timestamp
- order by timestamp desc
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
+ `
+ },
+ SignInProcessingTimeBasic: (interval, filters) => {
+ const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
+ return `
+ --signin-processing-time-basic
+ select
+ timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(event_message, "$.provider"), \'unknown\') as provider,' : ''}
+ count(*) as count,
+ round(avg(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as avg_processing_time_ms,
+ round(min(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as min_processing_time_ms,
+ round(max(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as max_processing_time_ms
+ from auth_logs
+ where json_value(event_message, "$.auth_event.action") = 'login'
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
`
},
- SignInLatency: (interval) => {
+ SignInProcessingTimePercentiles: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
return `
- --signin-latency
+ --signin-processing-time-percentiles
select
timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(event_message, "$.provider"), \'unknown\') as provider,' : ''}
count(*) as count,
- round(avg(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as avg_latency_ms,
- round(min(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as min_latency_ms,
- round(max(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as max_latency_ms,
- round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(50)] / 1000000, 2) as p50_latency_ms,
- round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(95)] / 1000000, 2) as p95_latency_ms,
- round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(99)] / 1000000, 2) as p99_latency_ms
+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(50)] / 1000000, 2) as p50_processing_time_ms,
+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(95)] / 1000000, 2) as p95_processing_time_ms,
+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(99)] / 1000000, 2) as p99_processing_time_ms
from auth_logs
where json_value(event_message, "$.auth_event.action") = 'login'
- group by timestamp
- order by timestamp desc
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
`
},
- SignUpLatency: (interval) => {
+ SignUpProcessingTimeBasic: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
return `
- --signup-latency
+ --signup-processing-time-basic
select
timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(event_message, "$.provider"), \'unknown\') as provider,' : ''}
count(*) as count,
- round(avg(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as avg_latency_ms,
- round(min(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as min_latency_ms,
- round(max(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as max_latency_ms,
- round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(50)] / 1000000, 2) as p50_latency_ms,
- round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(95)] / 1000000, 2) as p95_latency_ms,
- round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(99)] / 1000000, 2) as p99_latency_ms
+ round(avg(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as avg_processing_time_ms,
+ round(min(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as min_processing_time_ms,
+ round(max(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as max_processing_time_ms
from auth_logs
where json_value(event_message, "$.auth_event.action") = 'user_signedup'
- group by timestamp
- order by timestamp desc
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
`
},
- ErrorsByStatus: (interval) => {
+ SignUpProcessingTimePercentiles: (interval, filters) => {
const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = filterToWhereClause(filters)
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
+ return `
+ --signup-processing-time-percentiles
+ select
+ timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${groupByProvider ? 'COALESCE(JSON_VALUE(event_message, "$.provider"), \'unknown\') as provider,' : ''}
+ count(*) as count,
+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(50)] / 1000000, 2) as p50_processing_time_ms,
+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(95)] / 1000000, 2) as p95_processing_time_ms,
+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(99)] / 1000000, 2) as p99_processing_time_ms
+ from auth_logs
+ where json_value(event_message, "$.auth_event.action") = 'user_signedup'
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp${groupByProvider ? ', provider' : ''}
+ order by timestamp desc${groupByProvider ? ', provider' : ''}
+ `
+ },
+ ErrorsByStatus: (interval, filters) => {
+ const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = edgeLogsFilterToWhereClause(filters)
return `
--auth-errors-by-status
select
@@ -143,23 +217,157 @@ const AUTH_REPORT_SQL: Record<
cross join unnest(metadata) as m
cross join unnest(m.request) as request
cross join unnest(m.response) as response
+ cross join unnest(response.headers) as h
where path like '%auth/v1%'
and response.status_code >= 400 and response.status_code <= 599
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
group by timestamp, status_code
order by timestamp desc
`
},
+ ErrorsByAuthCode: (interval, filters) => {
+ const granularity = analyticsIntervalToGranularity(interval)
+ const whereClause = edgeLogsFilterToWhereClause(filters)
+ return `
+ --auth-errors-by-code
+ select
+ timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ count(*) as count,
+ h.x_sb_error_code as error_code
+ from edge_logs
+ cross join unnest(metadata) as m
+ cross join unnest(m.request) as request
+ cross join unnest(m.response) as response
+ cross join unnest(response.headers) as h
+ where path like '%auth/v1%'
+ and response.status_code >= 400 and response.status_code <= 599
+ ${whereClause ? `AND ${whereClause.replace(/^WHERE\s+/, '')}` : ''}
+ group by timestamp, error_code
+ order by timestamp desc
+ `
+ },
}
type AuthReportFilters = {
- status_code: NumericFilter | null
+ status_code?: NumericFilter | null
+ provider?: string[] | null
}
function filterToWhereClause(filters?: AuthReportFilters): string {
- if (!filters) return ''
- return ``
+ const whereClauses: string[] = []
+
+ if (filters?.status_code) {
+ whereClauses.push(
+ `response.status_code ${filters.status_code.operator} ${filters.status_code.value}`
+ )
+ }
+
+ if (filters?.provider && filters.provider.length > 0) {
+ const providerList = filters.provider.map((p) => `'${p}'`).join(', ')
+ whereClauses.push(`JSON_VALUE(event_message, "$.provider") IN (${providerList})`)
+ }
+
+ return whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : ''
+}
+
+function edgeLogsFilterToWhereClause(filters?: AuthReportFilters): string {
+ const whereClauses: string[] = []
+
+ if (filters?.status_code) {
+ whereClauses.push(
+ `response.status_code ${filters.status_code.operator} ${filters.status_code.value}`
+ )
+ }
+
+ return whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : ''
}
+export const AUTH_ERROR_CODE_VALUES: string[] = [
+ 'anonymous_provider_disabled',
+ 'bad_code_verifier',
+ 'bad_json',
+ 'bad_jwt',
+ 'bad_oauth_callback',
+ 'bad_oauth_state',
+ 'captcha_failed',
+ 'conflict',
+ 'email_address_invalid',
+ 'email_address_not_authorized',
+ 'email_conflict_identity_not_deletable',
+ 'email_exists',
+ 'email_not_confirmed',
+ 'email_provider_disabled',
+ 'flow_state_expired',
+ 'flow_state_not_found',
+ 'hook_payload_invalid_content_type',
+ 'hook_payload_over_size_limit',
+ 'hook_timeout',
+ 'hook_timeout_after_retry',
+ 'identity_already_exists',
+ 'identity_not_found',
+ 'insufficient_aal',
+ 'invalid_credentials',
+ 'invite_not_found',
+ 'manual_linking_disabled',
+ 'mfa_challenge_expired',
+ 'mfa_factor_name_conflict',
+ 'mfa_factor_not_found',
+ 'mfa_ip_address_mismatch',
+ 'mfa_phone_enroll_not_enabled',
+ 'mfa_phone_verify_not_enabled',
+ 'mfa_totp_enroll_not_enabled',
+ 'mfa_totp_verify_not_enabled',
+ 'mfa_verification_failed',
+ 'mfa_verification_rejected',
+ 'mfa_verified_factor_exists',
+ 'mfa_web_authn_enroll_not_enabled',
+ 'mfa_web_authn_verify_not_enabled',
+ 'no_authorization',
+ 'not_admin',
+ 'oauth_provider_not_supported',
+ 'otp_disabled',
+ 'otp_expired',
+ 'over_email_send_rate_limit',
+ 'over_request_rate_limit',
+ 'over_sms_send_rate_limit',
+ 'phone_exists',
+ 'phone_not_confirmed',
+ 'phone_provider_disabled',
+ 'provider_disabled',
+ 'provider_email_needs_verification',
+ 'reauthentication_needed',
+ 'reauthentication_not_valid',
+ 'refresh_token_already_used',
+ 'refresh_token_not_found',
+ 'request_timeout',
+ 'same_password',
+ 'saml_assertion_no_email',
+ 'saml_assertion_no_user_id',
+ 'saml_entity_id_mismatch',
+ 'saml_idp_already_exists',
+ 'saml_idp_not_found',
+ 'saml_metadata_fetch_failed',
+ 'saml_provider_disabled',
+ 'saml_relay_state_expired',
+ 'saml_relay_state_not_found',
+ 'session_expired',
+ 'session_not_found',
+ 'signup_disabled',
+ 'single_identity_not_deletable',
+ 'sms_send_failed',
+ 'sso_domain_already_exists',
+ 'sso_provider_not_found',
+ 'too_many_enrolled_mfa_factors',
+ 'unexpected_audience',
+ 'unexpected_failure',
+ 'user_already_exists',
+ 'user_banned',
+ 'user_not_found',
+ 'user_sso_managed',
+ 'validation_failed',
+ 'weak_password',
+]
+
/**
* Transforms raw analytics data into a chart-ready format by ensuring data consistency and completeness.
*
@@ -175,7 +383,8 @@ function filterToWhereClause(filters?: AuthReportFilters): string {
*/
export function defaultAuthReportFormatter(
rawData: unknown,
- attributes: ReportDataProviderAttribute[]
+ attributes: ReportDataProviderAttribute[],
+ groupByProvider = false
) {
const chartAttributes = attributes
@@ -194,44 +403,99 @@ export function defaultAuthReportFormatter(
if (!result) return { data: undefined, chartAttributes }
- const timestamps = new Set<string>(result.map((p: any) => String(p.timestamp)))
- const data = Array.from(timestamps)
- .sort()
- .map((timestamp) => {
- const point: any = { timestamp }
+ if (groupByProvider) {
+ // Group by provider - create separate attributes for each provider
+ const providers = new Set<string>()
+ result.forEach((p: any) => {
+ if (p.provider) {
+ providers.add(p.provider)
+ }
+ })
+
+ const providerAttributes: ReportDataProviderAttribute[] = []
+ providers.forEach((provider) => {
chartAttributes.forEach((attr) => {
- point[attr.attribute] = 0
+ providerAttributes.push({
+ ...attr,
+ attribute: `${attr.attribute}_${provider}`,
+ label: `${attr.label} (${provider})`,
+ })
})
- const matchingPoints = result.filter((p: any) => String(p.timestamp) === timestamp)
+ })
- matchingPoints.forEach((p: any) => {
+ const timestamps = new Set<string>(result.map((p: any) => String(p.timestamp)))
+ const data = Array.from(timestamps)
+ .sort()
+ .map((timestamp) => {
+ const point: any = { timestamp }
+ providerAttributes.forEach((attr) => {
+ point[attr.attribute] = 0
+ })
+ const matchingPoints = result.filter((p: any) => String(p.timestamp) === timestamp)
+
+ matchingPoints.forEach((p: any) => {
+ providerAttributes.forEach((attr) => {
+ const baseAttribute = attr.attribute.split('_').slice(0, -1).join('_')
+ const provider = attr.attribute.split('_').slice(-1)[0]
+
+ if (p.provider !== provider) return
+
+ const valueFromField =
+ typeof p[baseAttribute] === 'number'
+ ? p[baseAttribute]
+ : typeof p.count === 'number'
+ ? p.count
+ : undefined
+
+ if (typeof valueFromField === 'number') {
+ point[attr.attribute] = (point[attr.attribute] ?? 0) + valueFromField
+ }
+ })
+ })
+ return point
+ })
+ return { data, chartAttributes: providerAttributes }
+ } else {
+ // Original logic for non-provider grouping
+ const timestamps = new Set<string>(result.map((p: any) => String(p.timestamp)))
+ const data = Array.from(timestamps)
+ .sort()
+ .map((timestamp) => {
+ const point: any = { timestamp }
chartAttributes.forEach((attr) => {
- // Optional dimension filters used by some reports
- if ('login_type_provider' in (attr as any)) {
- if (p.login_type_provider !== (attr as any).login_type_provider) return
- }
- if ('providerType' in (attr as any)) {
- if (p.provider !== (attr as any).providerType) return
- }
-
- const valueFromField =
- typeof p[attr.attribute] === 'number'
- ? p[attr.attribute]
- : typeof p.count === 'number'
- ? p.count
- : undefined
-
- if (typeof valueFromField === 'number') {
- point[attr.attribute] = (point[attr.attribute] ?? 0) + valueFromField
- }
+ point[attr.attribute] = 0
+ })
+ const matchingPoints = result.filter((p: any) => String(p.timestamp) === timestamp)
+
+ matchingPoints.forEach((p: any) => {
+ chartAttributes.forEach((attr) => {
+ // Optional dimension filters used by some reports
+ if ('login_type_provider' in (attr as any)) {
+ if (p.login_type_provider !== (attr as any).login_type_provider) return
+ }
+ if ('providerType' in (attr as any)) {
+ if (p.provider !== (attr as any).providerType) return
+ }
+
+ const valueFromField =
+ typeof p[attr.attribute] === 'number'
+ ? p[attr.attribute]
+ : typeof p.count === 'number'
+ ? p.count
+ : undefined
+
+ if (typeof valueFromField === 'number') {
+ point[attr.attribute] = (point[attr.attribute] ?? 0) + valueFromField
+ }
+ })
})
+ return point
})
- return point
- })
- return { data, chartAttributes }
+ return { data, chartAttributes }
+ }
}
-export const createAuthReportConfig = ({
+export const createUsageReportConfig = ({
projectRef,
startDate,
endDate,
@@ -243,144 +507,205 @@ export const createAuthReportConfig = ({
endDate: string
interval: AnalyticsInterval
filters: AuthReportFilters
-}): ReportConfig<AuthReportFilters>[] => [
- {
- id: 'active-user',
- label: 'Active Users',
- valuePrecision: 0,
- hide: false,
- showTooltip: true,
- showLegend: false,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'line',
- titleTooltip: 'The total number of active users over time.',
- availableIn: ['free', 'pro', 'team', 'enterprise'],
- dataProvider: async () => {
- const attributes = [
- { attribute: 'ActiveUsers', provider: 'logs', label: 'Active Users', enabled: true },
- ]
+}): ReportConfig<AuthReportFilters>[] => {
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
- const sql = AUTH_REPORT_SQL.ActiveUsers(interval, filters)
+ return [
+ {
+ id: 'active-user',
+ label: 'Active Users',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: false,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of active users over time.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ { attribute: 'ActiveUsers', provider: 'logs', label: 'Active Users', enabled: true },
+ ]
- const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const sql = AUTH_REPORT_SQL.ActiveUsers(interval, filters)
+
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
},
- },
- {
- id: 'sign-in-attempts',
- label: 'Sign In Attempts by Type',
- valuePrecision: 0,
- hide: false,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'line',
- titleTooltip: 'The total number of sign in attempts by type.',
- availableIn: ['free', 'pro', 'team', 'enterprise'],
- dataProvider: async () => {
- const attributes = [
- {
- attribute: 'SignInAttempts',
- provider: 'logs',
- label: 'Password',
- login_type_provider: 'password',
- enabled: true,
- },
- {
- attribute: 'SignInAttempts',
- provider: 'logs',
- label: 'PKCE',
- login_type_provider: 'pkce',
- enabled: true,
- },
- {
- attribute: 'SignInAttempts',
- provider: 'logs',
- label: 'Refresh Token',
- login_type_provider: 'token',
- enabled: true,
- },
- {
- attribute: 'SignInAttempts',
- provider: 'logs',
- label: 'ID Token',
- login_type_provider: 'id_token',
- enabled: true,
- },
- ]
-
- const sql = AUTH_REPORT_SQL.SignInAttempts(interval, filters)
- const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
+ {
+ id: 'sign-in-attempts',
+ label: 'Sign In Attempts by Type',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of sign in attempts by type.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'SignInAttempts',
+ provider: 'logs',
+ label: 'Password',
+ login_type_provider: 'password',
+ enabled: true,
+ },
+ {
+ attribute: 'SignInAttempts',
+ provider: 'logs',
+ label: 'PKCE',
+ login_type_provider: 'pkce',
+ enabled: true,
+ },
+ {
+ attribute: 'SignInAttempts',
+ provider: 'logs',
+ label: 'Refresh Token',
+ login_type_provider: 'token',
+ enabled: true,
+ },
+ {
+ attribute: 'SignInAttempts',
+ provider: 'logs',
+ label: 'ID Token',
+ login_type_provider: 'id_token',
+ enabled: true,
+ },
+ ]
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ const sql = AUTH_REPORT_SQL.SignInAttempts(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
+
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
},
- },
- {
- id: 'signups',
- label: 'Sign Ups',
- valuePrecision: 0,
- hide: false,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'line',
- titleTooltip: 'The total number of sign ups.',
- availableIn: ['free', 'pro', 'team', 'enterprise'],
- dataProvider: async () => {
- const attributes = [
- {
- attribute: 'TotalSignUps',
- provider: 'logs',
- label: 'Sign Ups',
- enabled: true,
- },
- ]
-
- const sql = AUTH_REPORT_SQL.TotalSignUps(interval, filters)
- const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
+ {
+ id: 'signups',
+ label: 'Sign Ups',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of sign ups.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'TotalSignUps',
+ provider: 'logs',
+ label: 'Sign Ups',
+ enabled: true,
+ },
+ ]
+
+ const sql = AUTH_REPORT_SQL.TotalSignUps(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
},
- },
+ {
+ id: 'password-reset-requests',
+ label: 'Password Reset Requests',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of password reset requests.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'PasswordResetRequests',
+ provider: 'logs',
+ label: 'Password Reset Requests',
+ enabled: true,
+ },
+ ]
+
+ const sql = AUTH_REPORT_SQL.PasswordResetRequests(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
+
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
+ },
+ ]
+}
+
+export const createErrorsReportConfig = ({
+ projectRef,
+ startDate,
+ endDate,
+ interval,
+ filters,
+}: {
+ projectRef: string
+ startDate: string
+ endDate: string
+ interval: AnalyticsInterval
+ filters: AuthReportFilters
+}): ReportConfig<AuthReportFilters>[] => [
{
id: 'auth-errors',
label: 'API Gateway Auth Errors',
valuePrecision: 0,
hide: false,
showTooltip: true,
- showLegend: false,
+ showLegend: true,
showMaxValue: false,
hideChartType: false,
defaultChartStyle: 'line',
titleTooltip: 'The total number of auth errors by status code from the API Gateway.',
availableIn: ['free', 'pro', 'team', 'enterprise'],
dataProvider: async () => {
- const attributes = [
- {
- attribute: 'ErrorsByStatus',
- provider: 'logs',
- label: 'Auth Errors',
- },
- ]
-
const sql = AUTH_REPORT_SQL.ErrorsByStatus(interval, filters)
const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ if (!rawData?.result) return { data: [] }
+
+ const statusCodes = extractStatusCodesFromData(rawData.result)
+ const attributes = generateStatusCodeAttributes(statusCodes)
+ const data = transformStatusCodeData(rawData.result, statusCodes)
+
+ return { data, attributes, query: sql }
},
},
{
- id: 'password-reset-requests',
- label: 'Password Reset Requests',
+ id: 'auth-errors-by-code',
+ label: 'Auth Errors by Code',
valuePrecision: 0,
hide: false,
showTooltip: true,
@@ -388,127 +713,235 @@ export const createAuthReportConfig = ({
showMaxValue: false,
hideChartType: false,
defaultChartStyle: 'line',
- titleTooltip: 'The total number of password reset requests.',
+ titleTooltip:
+ 'The total number of auth errors by Supabase Auth error code from the API Gateway.',
availableIn: ['free', 'pro', 'team', 'enterprise'],
dataProvider: async () => {
- const attributes = [
- {
- attribute: 'PasswordResetRequests',
- provider: 'logs',
- label: 'Password Reset Requests',
- enabled: true,
- },
- ]
-
- const sql = AUTH_REPORT_SQL.PasswordResetRequests(interval, filters)
+ const sql = AUTH_REPORT_SQL.ErrorsByAuthCode(interval, filters)
const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ if (!rawData?.result) return { data: [] }
+
+ const categories = rawData.result
+ .map((r: any) => r.error_code)
+ .filter((v: any) => v !== null && v !== undefined)
+ const distinct = Array.from(new Set(categories)).sort()
+
+ const attributes = distinct.map((c: string) => ({
+ attribute: c,
+ label: c,
+ tooltip: AUTH_ERROR_CODE_LIST.find((e) => e.key === c)?.description,
+ }))
+
+ const data = rawData.result.map((point: any) => ({
+ ...point,
+ timestamp: point.timestamp,
+ }))
+
+ const pivoted = transformCategoricalCountData(rawData.result, 'error_code', distinct)
+
+ return { data: pivoted, attributes, query: sql }
},
},
- {
- id: 'sign-in-latency',
- label: 'Sign In Latency',
- valuePrecision: 2,
- hide: false,
- hideHighlightedValue: true,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'line',
- titleTooltip: 'The average latency for sign in operations by grant type.',
- availableIn: ['pro', 'team', 'enterprise'],
- dataProvider: async () => {
- const attributes = [
- {
- attribute: 'avg_latency_ms',
- label: 'Avg. Latency (ms)',
- },
- {
- attribute: 'max_latency_ms',
- label: 'Max. Latency (ms)',
- },
- {
- attribute: 'min_latency_ms',
- label: 'Min. Latency (ms)',
- },
- {
- attribute: 'p50_latency_ms',
- label: 'P50 Latency (ms)',
- },
- {
- attribute: 'p95_latency_ms',
- label: 'P95 Latency (ms)',
- },
- {
- attribute: 'p99_latency_ms',
- label: 'P99 Latency (ms)',
- },
- {
- attribute: 'request_count',
- label: 'Request Count',
- },
- ]
-
- const sql = AUTH_REPORT_SQL.SignInLatency(interval, filters)
- const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
+]
+
+export const createLatencyReportConfig = ({
+ projectRef,
+ startDate,
+ endDate,
+ interval,
+ filters,
+}: {
+ projectRef: string
+ startDate: string
+ endDate: string
+ interval: AnalyticsInterval
+ filters: AuthReportFilters
+}): ReportConfig<AuthReportFilters>[] => {
+ const groupByProvider = Boolean(filters?.provider && filters.provider.length > 0)
+
+ return [
+ {
+ id: 'sign-in-processing-time-basic',
+ label: 'Sign In Processing Time',
+ valuePrecision: 2,
+ hide: false,
+ hideHighlightedValue: true,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip:
+ 'Basic processing time metrics for sign in operations within the auth server (excludes network latency).',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'avg_processing_time_ms',
+ label: 'Avg. Processing Time (ms)',
+ },
+ {
+ attribute: 'min_processing_time_ms',
+ label: 'Min. Processing Time (ms)',
+ },
+ {
+ attribute: 'max_processing_time_ms',
+ label: 'Max. Processing Time (ms)',
+ },
+ ]
+
+ const sql = AUTH_REPORT_SQL.SignInProcessingTimeBasic(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
},
- },
- {
- id: 'sign-up-latency',
- label: 'Sign Up Latency',
- valuePrecision: 2,
- hide: false,
- hideHighlightedValue: true,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'line',
- titleTooltip: 'The average latency for sign up operations by provider.',
- availableIn: ['pro', 'team', 'enterprise'],
- dataProvider: async () => {
- const attributes = [
- {
- attribute: 'avg_latency_ms',
- label: 'Avg. Latency (ms)',
- },
- {
- attribute: 'max_latency_ms',
- label: 'Max. Latency (ms)',
- },
- {
- attribute: 'min_latency_ms',
- label: 'Min. Latency (ms)',
- },
- {
- attribute: 'p50_latency_ms',
- label: 'P50 Latency (ms)',
- },
- {
- attribute: 'p95_latency_ms',
- label: 'P95 Latency (ms)',
- },
- {
- attribute: 'p99_latency_ms',
- label: 'P99 Latency (ms)',
- },
- {
- attribute: 'request_count',
- label: 'Request Count',
- },
- ]
-
- const sql = AUTH_REPORT_SQL.SignUpLatency(interval, filters)
- const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
- const transformedData = defaultAuthReportFormatter(rawData, attributes)
+ {
+ id: 'sign-in-processing-time-percentiles',
+ label: 'Sign In Processing Time Percentiles',
+ valuePrecision: 2,
+ hide: false,
+ hideHighlightedValue: true,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip:
+ 'Percentile processing time metrics for sign in operations within the auth server (excludes network latency).',
+ availableIn: ['pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'p50_processing_time_ms',
+ label: 'P50 Processing Time (ms)',
+ },
+ {
+ attribute: 'p95_processing_time_ms',
+ label: 'P95 Processing Time (ms)',
+ },
+ {
+ attribute: 'p99_processing_time_ms',
+ label: 'P99 Processing Time (ms)',
+ },
+ ]
+
+ const sql = AUTH_REPORT_SQL.SignInProcessingTimePercentiles(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
- return { data: transformedData.data, attributes: transformedData.chartAttributes, query: sql }
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
},
- },
+ {
+ id: 'sign-up-processing-time-basic',
+ label: 'Sign Up Processing Time',
+ valuePrecision: 2,
+ hide: false,
+ hideHighlightedValue: true,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip:
+ 'Basic processing time metrics for sign up operations within the auth server (excludes network latency).',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'avg_processing_time_ms',
+ label: 'Avg. Processing Time (ms)',
+ },
+ {
+ attribute: 'min_processing_time_ms',
+ label: 'Min. Processing Time (ms)',
+ },
+ {
+ attribute: 'max_processing_time_ms',
+ label: 'Max. Processing Time (ms)',
+ },
+ ]
+
+ const sql = AUTH_REPORT_SQL.SignUpProcessingTimeBasic(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
+
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
+ },
+ {
+ id: 'sign-up-processing-time-percentiles',
+ label: 'Sign Up Processing Time Percentiles',
+ valuePrecision: 2,
+ hide: false,
+ hideHighlightedValue: true,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip:
+ 'Percentile processing time metrics for sign up operations within the auth server (excludes network latency).',
+ availableIn: ['pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const attributes = [
+ {
+ attribute: 'p50_processing_time_ms',
+ label: 'P50 Processing Time (ms)',
+ },
+ {
+ attribute: 'p95_processing_time_ms',
+ label: 'P95 Processing Time (ms)',
+ },
+ {
+ attribute: 'p99_processing_time_ms',
+ label: 'P99 Processing Time (ms)',
+ },
+ ]
+
+ const sql = AUTH_REPORT_SQL.SignUpProcessingTimePercentiles(interval, filters)
+ const rawData = await fetchLogs(projectRef, sql, startDate, endDate)
+ const transformedData = defaultAuthReportFormatter(rawData, attributes, groupByProvider)
+
+ return {
+ data: transformedData.data,
+ attributes: transformedData.chartAttributes,
+ query: sql,
+ }
+ },
+ },
+ ]
+}
+
+export const createAuthReportConfig = ({
+ projectRef,
+ startDate,
+ endDate,
+ interval,
+ filters,
+}: {
+ projectRef: string
+ startDate: string
+ endDate: string
+ interval: AnalyticsInterval
+ filters: AuthReportFilters
+}): ReportConfig<AuthReportFilters>[] => [
+ ...createUsageReportConfig({ projectRef, startDate, endDate, interval, filters }),
+ ...createErrorsReportConfig({ projectRef, startDate, endDate, interval, filters }),
+ ...createLatencyReportConfig({ projectRef, startDate, endDate, interval, filters }),
]
diff --git a/apps/studio/data/reports/v2/edge-functions.config.ts b/apps/studio/data/reports/v2/edge-functions.config.ts
index 40f78efd1d2..15fef6c6454 100644
--- a/apps/studio/data/reports/v2/edge-functions.config.ts
+++ b/apps/studio/data/reports/v2/edge-functions.config.ts
@@ -6,15 +6,16 @@ import {
} from 'components/interfaces/Settings/Logs/Logs.utils'
import type { AnalyticsInterval } from 'data/analytics/constants'
import { get } from 'data/fetchers'
-import {
- analyticsIntervalToGranularity,
- REPORT_STATUS_CODE_COLORS,
-} from 'data/reports/report.utils'
-import { getHttpStatusCodeInfo } from 'lib/http-status-codes'
+import { analyticsIntervalToGranularity } from 'data/reports/report.utils'
import { ReportConfig } from './reports.types'
import { NumericFilter } from 'components/interfaces/Reports/v2/ReportsNumericFilter'
import { SelectFilters } from 'components/interfaces/Reports/v2/ReportsSelectFilter'
import { fetchLogs } from 'data/reports/report.utils'
+import {
+ extractStatusCodesFromData,
+ generateStatusCodeAttributes,
+ transformStatusCodeData,
+} from 'components/interfaces/Reports/Reports.utils'
type EdgeFunctionReportFilters = {
status_code: NumericFilter | null
@@ -152,49 +153,6 @@ order by
},
}
-export function extractStatusCodesFromData(data: any[]): string[] {
- const statusCodes = new Set<string>()
-
- data.forEach((item: any) => {
- if (item.status_code) {
- statusCodes.add(String(item.status_code))
- }
- })
-
- return Array.from(statusCodes).sort()
-}
-
-export function generateStatusCodeAttributes(statusCodes: string[]) {
- return statusCodes.map((code) => ({
- attribute: code,
- label: `${code} ${getHttpStatusCodeInfo(parseInt(code)).label}`,
- color: REPORT_STATUS_CODE_COLORS[code] || REPORT_STATUS_CODE_COLORS.default,
- }))
-}
-
-/**
- * Converts a list of { timestamp, status_code, count }
- * to a list of { timestamp, [status_code]: count }
- * That we can pass to the chart for rendering
- */
-export function transformStatusCodeData(data: any[], statusCodes: string[]) {
- const pivotedData = data.reduce((acc: Record<string, any>, d: any) => {
- const timestamp = isUnixMicro(d.timestamp)
- ? unixMicroToIsoTimestamp(d.timestamp)
- : dayjs.utc(d.timestamp).toISOString()
- if (!acc[timestamp]) {
- acc[timestamp] = { timestamp }
- statusCodes.forEach((code) => {
- acc[timestamp][code] = 0
- })
- }
- acc[timestamp][d.status_code] = d.count
- return acc
- }, {})
-
- return Object.values(pivotedData)
-}
-
/**
* Transforms raw invocation data by normalizing timestamps and adding function names
* @param data - Raw data from the database
diff --git a/apps/studio/data/reports/v2/edge-functions.test.tsx b/apps/studio/data/reports/v2/edge-functions.test.tsx
index d02f656d39c..c7d60954abd 100644
--- a/apps/studio/data/reports/v2/edge-functions.test.tsx
+++ b/apps/studio/data/reports/v2/edge-functions.test.tsx
@@ -1,12 +1,14 @@
import { describe, expect, it } from 'vitest'
import {
- extractStatusCodesFromData,
- generateStatusCodeAttributes,
- transformStatusCodeData,
transformInvocationData,
aggregateInvocationsByTimestamp,
filterToWhereClause,
} from './edge-functions.config'
+import {
+ extractStatusCodesFromData,
+ generateStatusCodeAttributes,
+ transformStatusCodeData,
+} from 'components/interfaces/Reports/Reports.utils'
const defaultFilters = {
status_code: null,
diff --git a/apps/studio/pages/project/[ref]/reports/auth.tsx b/apps/studio/pages/project/[ref]/reports/auth.tsx
index e077eb62bfc..6d153cadc0e 100644
--- a/apps/studio/pages/project/[ref]/reports/auth.tsx
+++ b/apps/studio/pages/project/[ref]/reports/auth.tsx
@@ -2,9 +2,10 @@ import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { ArrowRight, LogsIcon, RefreshCw } from 'lucide-react'
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { ReportChartV2 } from 'components/interfaces/Reports/v2/ReportChartV2'
+import { ReportSectionHeader } from 'components/interfaces/Reports/v2/ReportSectionHeader'
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
@@ -20,10 +21,23 @@ import { useSharedAPIReport } from 'components/interfaces/Reports/SharedAPIRepor
import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'
import { useReportDateRange } from 'hooks/misc/useReportDateRange'
import type { NextPageWithLayout } from 'types'
-import { createAuthReportConfig } from 'data/reports/v2/auth.config'
+import {
+ createUsageReportConfig,
+ createErrorsReportConfig,
+ createLatencyReportConfig,
+} from 'data/reports/v2/auth.config'
import { ReportSettings } from 'components/ui/Charts/ReportSettings'
import type { ChartHighlightAction } from 'components/ui/Charts/ChartHighlightActions'
import { useRouter } from 'next/router'
+import {
+ ReportsNumericFilter,
+ numericFilterSchema,
+} from 'components/interfaces/Reports/v2/ReportsNumericFilter'
+import {
+ ReportsSelectFilter,
+ selectFilterSchema,
+} from 'components/interfaces/Reports/v2/ReportsSelectFilter'
+import { useQueryState, parseAsJson } from 'nuqs'
const AuthReport: NextPageWithLayout = () => {
return (
@@ -76,12 +90,69 @@ const AuthUsage = () => {
const queryClient = useQueryClient()
const [isRefreshing, setIsRefreshing] = useState(false)
- const authReportConfig = createAuthReportConfig({
+ const [monitoringStatusCodeFilter, setMonitoringStatusCodeFilter] = useQueryState(
+ 'monitoring_status_code',
+ parseAsJson(numericFilterSchema.parse)
+ )
+
+ const [usageProviderFilter, setUsageProviderFilter] = useQueryState(
+ 'usage_provider',
+ parseAsJson(selectFilterSchema.parse)
+ )
+
+ const providerOptions = [
+ { label: 'Email', value: 'email' },
+ { label: 'Google', value: 'google' },
+ { label: 'Apple', value: 'apple' },
+ { label: 'Phone', value: 'phone' },
+ { label: 'Discord', value: 'discord' },
+ { label: 'Azure', value: 'azure' },
+ { label: 'GitHub', value: 'github' },
+ { label: 'Kakao', value: 'kakao' },
+ { label: 'TOTP', value: 'totp' },
+ { label: 'Twitter', value: 'twitter' },
+ { label: 'SAML', value: 'saml' },
+ { label: 'Recovery', value: 'recovery' },
+ { label: 'SSO/SAML', value: 'sso/saml' },
+ { label: 'Magic Link', value: 'magiclink' },
+ { label: 'Keycloak', value: 'keycloak' },
+ { label: 'Facebook', value: 'facebook' },
+ { label: 'Twitch', value: 'twitch' },
+ { label: 'LinkedIn OIDC', value: 'linkedin_oidc' },
+ { label: 'Spotify', value: 'spotify' },
+ { label: 'Email Change', value: 'email_change' },
+ { label: 'Snapchat', value: 'snapchat' },
+ { label: 'WorkOS', value: 'workos' },
+ { label: 'Notion', value: 'notion' },
+ { label: 'Slack OIDC', value: 'slack_oidc' },
+ { label: 'Figma', value: 'figma' },
+ { label: 'GitLab', value: 'gitlab' },
+ { label: 'LinkedIn', value: 'linkedin' },
+ { label: 'Zoom', value: 'zoom' },
+ ]
+
+ const usageReportConfig = createUsageReportConfig({
+ projectRef: ref || '',
+ startDate: selectedDateRange?.period_start?.date,
+ endDate: selectedDateRange?.period_end?.date,
+ interval: selectedDateRange?.interval,
+ filters: { provider: usageProviderFilter },
+ })
+
+ const errorsReportConfig = createErrorsReportConfig({
projectRef: ref || '',
startDate: selectedDateRange?.period_start?.date,
endDate: selectedDateRange?.period_end?.date,
interval: selectedDateRange?.interval,
- filters: { status_code: null },
+ filters: { status_code: monitoringStatusCodeFilter },
+ })
+
+ const latencyReportConfig = createLatencyReportConfig({
+ projectRef: ref || '',
+ startDate: selectedDateRange?.period_start?.date,
+ endDate: selectedDateRange?.period_end?.date,
+ interval: selectedDateRange?.interval,
+ filters: {},
})
const onRefreshReport = async () => {
@@ -100,8 +171,15 @@ const AuthUsage = () => {
id: 'api-gateway-logs',
label: 'Open in API Gateway Logs',
icon: <LogsIcon size={12} />,
- onSelect: ({ start, end, clear }) => {
- const url = `/project/${ref}/logs/edge-logs?its=${start}&ite=${end}&f={"product":{"auth":true}}`
+ onSelect: ({ start, end, clear, chartId }) => {
+ let url = `/project/${ref}/logs/edge-logs?its=${start}&ite=${end}`
+
+ if (chartId?.includes('errors')) {
+ url += `&f={"product":{"auth":true},"status_code":{"error":true,"warning":true}}`
+ } else {
+ url += `&f={"product":{"auth":true}}`
+ }
+
router.push(url)
},
},
@@ -121,17 +199,17 @@ const AuthUsage = () => {
<ReportHeader title="Auth" showDatabaseSelector={false} />
<ReportStickyNav
content={
- <>
- <ButtonTooltip
- type="default"
- disabled={isRefreshing}
- icon={<RefreshCw className={isRefreshing ? 'animate-spin' : ''} />}
- className="w-7"
- tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}
- onClick={onRefreshReport}
- />
- <ReportSettings chartId={chartSyncId} />
- <div className="flex items-center gap-3">
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <ButtonTooltip
+ type="default"
+ disabled={isRefreshing}
+ icon={<RefreshCw className={isRefreshing ? 'animate-spin' : ''} />}
+ className="w-7"
+ tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}
+ onClick={onRefreshReport}
+ />
+ <ReportSettings chartId={chartSyncId} />
<LogsDatePicker
onSubmit={handleDatePickerChange}
value={datePickerValue}
@@ -158,46 +236,127 @@ const AuthUsage = () => {
</div>
)}
</div>
- </>
+ </div>
}
>
- {authReportConfig.map((metric, i) => (
- <ReportChartV2
- key={`${metric.id}`}
- report={metric}
- projectRef={ref!}
- interval={selectedDateRange.interval}
- startDate={selectedDateRange?.period_start?.date}
- endDate={selectedDateRange?.period_end?.date}
- updateDateRange={updateDateRange}
- syncId={chartSyncId}
- filters={{
- status_code: null,
- }}
- highlightActions={highlightActions}
- />
- ))}
- <div>
- <div className="mb-4">
- <h5 className="text-foreground mb-2">Auth API Gateway</h5>
- <ReportFilterBar
- filters={filters}
- onAddFilter={addFilter}
- onRemoveFilters={removeFilters}
- isLoading={isLoadingData || isRefetching}
- hideDatepicker={true}
- datepickerHelpers={datePickerHelpers}
- selectedProduct={'auth'}
- showDatabaseSelector={false}
+ <div className="mt-8 flex flex-col gap-8 pb-24">
+ <div className="flex flex-col gap-4" id="usage">
+ <div>
+ <ReportSectionHeader
+ id="usage"
+ title="Usage"
+ description="Monitor user activity, sign-ins, sign-ups, and password reset requests to understand how users interact with your authentication system."
+ />
+ <ReportsSelectFilter
+ label="Provider"
+ options={providerOptions}
+ value={usageProviderFilter || []}
+ onChange={setUsageProviderFilter}
+ isLoading={isRefreshing}
+ showSearch={true}
+ />
+ </div>
+ <div className="grid md:grid-cols-2 gap-4">
+ {usageReportConfig.map((metric) => (
+ <ReportChartV2
+ key={`${metric.id}`}
+ report={metric}
+ projectRef={ref!}
+ interval={selectedDateRange.interval}
+ startDate={selectedDateRange?.period_start?.date}
+ endDate={selectedDateRange?.period_end?.date}
+ updateDateRange={updateDateRange}
+ syncId={chartSyncId}
+ filters={{ provider: usageProviderFilter }}
+ highlightActions={highlightActions}
+ />
+ ))}
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-4" id="monitoring">
+ <div>
+ <ReportSectionHeader
+ id="monitoring"
+ title="Monitoring"
+ description="Track authentication errors by status code and error type to identify issues and improve user experience."
+ />
+
+ <ReportsNumericFilter
+ label="Status Code"
+ value={monitoringStatusCodeFilter}
+ onChange={setMonitoringStatusCodeFilter}
+ defaultOperator="="
+ isLoading={isRefreshing}
+ />
+ </div>
+ <div className="grid md:grid-cols-2 gap-4">
+ {errorsReportConfig.map((metric) => (
+ <ReportChartV2
+ key={`${metric.id}`}
+ report={metric}
+ projectRef={ref!}
+ interval={selectedDateRange.interval}
+ startDate={selectedDateRange?.period_start?.date}
+ endDate={selectedDateRange?.period_end?.date}
+ updateDateRange={updateDateRange}
+ syncId={chartSyncId}
+ filters={{ status_code: monitoringStatusCodeFilter }}
+ highlightActions={highlightActions}
+ />
+ ))}
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-4" id="performance">
+ <ReportSectionHeader
+ id="performance"
+ title="Performance"
+ description="Monitor sign-in and sign-up performance metrics including average, percentiles, and request counts to ensure optimal authentication speed."
+ />
+ <div className="grid md:grid-cols-2 gap-4">
+ {latencyReportConfig.map((metric) => (
+ <ReportChartV2
+ key={`${metric.id}`}
+ report={metric}
+ projectRef={ref!}
+ interval={selectedDateRange.interval}
+ startDate={selectedDateRange?.period_start?.date}
+ endDate={selectedDateRange?.period_end?.date}
+ updateDateRange={updateDateRange}
+ syncId={chartSyncId}
+ filters={{}}
+ highlightActions={highlightActions}
+ />
+ ))}
+ </div>
+ </div>
+ <div>
+ <div className="mb-4 space-y-4">
+ <ReportSectionHeader
+ id="auth-api-gateway"
+ title="Auth API Gateway"
+ description="Monitor user activity, sign-ins, sign-ups, and password reset requests to understand how users interact with your authentication system."
+ />
+ <ReportFilterBar
+ filters={filters}
+ onAddFilter={addFilter}
+ onRemoveFilters={removeFilters}
+ isLoading={isLoadingData || isRefetching}
+ hideDatepicker={true}
+ datepickerHelpers={datePickerHelpers}
+ selectedProduct={'auth'}
+ showDatabaseSelector={false}
+ />
+ </div>
+ <SharedAPIReport
+ data={data}
+ error={error}
+ isLoading={isLoading}
+ isRefetching={isRefetching}
+ sql={sql}
/>
</div>
- <SharedAPIReport
- data={data}
- error={error}
- isLoading={isLoading}
- isRefetching={isRefetching}
- sql={sql}
- />
</div>
</ReportStickyNav>
</>
diff --git a/packages/common/constants/auth-error-codes.ts b/packages/common/constants/auth-error-codes.ts
new file mode 100644
index 00000000000..835083bcbbd
--- /dev/null
+++ b/packages/common/constants/auth-error-codes.ts
@@ -0,0 +1,250 @@
+export const AUTH_ERROR_CODES = {
+ anonymous_provider_disabled: {
+ description: 'Anonymous sign-ins are disabled.',
+ },
+ bad_code_verifier: {
+ description:
+ 'Returned from the PKCE flow where the provided code verifier does not match the expected one. Indicates a bug in the implementation of the client library.',
+ },
+ bad_json: {
+ description: 'Usually used when the HTTP body of the request is not valid JSON.',
+ },
+ bad_oauth_callback: {
+ description:
+ 'OAuth callback from provider to Auth does not have all the required attributes (state). Indicates an issue with the OAuth provider or client library implementation.',
+ },
+ bad_oauth_state: {
+ description:
+ 'OAuth state (data echoed back by the OAuth provider to Supabase Auth) is not in the correct format. Indicates an issue with the OAuth provider integration.',
+ },
+ captcha_failed: {
+ description:
+ 'CAPTCHA challenge could not be verified with the CAPTCHA provider. Check your CAPTCHA integration.',
+ },
+ conflict: {
+ description:
+ 'General database conflict, such as concurrent requests on resources that should not be modified concurrently. Can often occur when you have too many session refresh requests firing off at the same time for a user.',
+ },
+ email_address_invalid: {
+ description:
+ 'Example and test domains are currently not supported. Use a different email address.',
+ },
+ email_address_not_authorized: {
+ description:
+ 'Email sending is not allowed for this address as your project is using the default SMTP service. Set up a custom SMTP provider to send to external addresses.',
+ },
+ email_conflict_identity_not_deletable: {
+ description:
+ "Unlinking this identity causes the user's account to change to an email address which is already used by another user account.",
+ },
+ email_not_confirmed: {
+ description: 'Signing in is not allowed for this user as the email address is not confirmed.',
+ },
+ email_provider_disabled: {
+ description: 'Signups are disabled for email and password.',
+ },
+ flow_state_expired: {
+ description:
+ 'PKCE flow state to which the API request relates has expired. Ask the user to sign in again.',
+ },
+ flow_state_not_found: {
+ description:
+ 'PKCE flow state no longer exists or was destroyed by a previous request. Ask the user to sign in again.',
+ },
+ hook_payload_invalid_content_type: {
+ description: 'Payload from Auth does not have a valid Content-Type header.',
+ },
+ hook_payload_over_size_limit: {
+ description: 'Payload from Auth exceeds maximum size limit.',
+ },
+ hook_timeout: {
+ description: 'Unable to reach hook within maximum time allocated.',
+ },
+ hook_timeout_after_retry: {
+ description: 'Unable to reach hook after maximum number of retries.',
+ },
+ identity_already_exists: {
+ description: 'The identity to which the API relates is already linked to a user.',
+ },
+ identity_not_found: {
+ description:
+ 'Identity to which the API call relates does not exist, such as when an identity is unlinked or deleted.',
+ },
+ insufficient_aal: {
+ description:
+ 'The user must have a higher Authenticator Assurance Level to call this API. Ask them to solve an MFA challenge.',
+ },
+ invalid_credentials: {
+ description: 'Login credentials or grant type not recognized.',
+ },
+ manual_linking_disabled: {
+ description:
+ 'Calling the supabase.auth.linkUser() and related APIs is not enabled on the Auth server.',
+ },
+ mfa_challenge_expired: {
+ description: 'Responding to an MFA challenge took too long. Request a new challenge.',
+ },
+ mfa_factor_name_conflict: {
+ description: 'MFA factors for a single user should not have the same friendly name.',
+ },
+ mfa_factor_not_found: {
+ description: 'MFA factor no longer exists.',
+ },
+ mfa_ip_address_mismatch: {
+ description:
+ 'The enrollment process for MFA factors must begin and end with the same IP address.',
+ },
+ mfa_phone_enroll_not_enabled: {
+ description: 'Enrollment of MFA Phone factors is disabled.',
+ },
+ mfa_phone_verify_not_enabled: {
+ description: 'Login via Phone factors and verification of new Phone factors is disabled.',
+ },
+ mfa_totp_enroll_not_enabled: {
+ description: 'Enrollment of MFA TOTP factors is disabled.',
+ },
+ mfa_totp_verify_not_enabled: {
+ description: 'Login via TOTP factors and verification of new TOTP factors is disabled.',
+ },
+ mfa_verification_failed: {
+ description: 'MFA challenge could not be verified due to a wrong TOTP code.',
+ },
+ mfa_verification_rejected: {
+ description: 'Further MFA verification is rejected due to a hook decision.',
+ },
+ mfa_verified_factor_exists: {
+ description: 'Verified phone factor already exists for a user. Unenroll it to continue.',
+ },
+ mfa_web_authn_enroll_not_enabled: {
+ description: 'Enrollment of MFA Web Authn factors is disabled.',
+ },
+ mfa_web_authn_verify_not_enabled: {
+ description: 'Login via WebAuthn factors and verification of new WebAuthn factors is disabled.',
+ },
+ no_authorization: {
+ description: 'This HTTP request requires an Authorization header, which is missing.',
+ },
+ oauth_provider_not_supported: {
+ description: 'Using an OAuth provider which is disabled on the Auth server.',
+ },
+ otp_disabled: {
+ description: 'Sign in with OTPs (magic link, email OTP) is disabled.',
+ },
+ otp_expired: {
+ description: 'OTP code has expired. Ask the user to sign in again.',
+ },
+ over_email_send_rate_limit: {
+ description: 'Too many emails have been sent to this address. Ask the user to wait.',
+ },
+ over_request_rate_limit: {
+ description:
+ 'Too many requests have been sent by this client. Ask the user to try again later.',
+ },
+ over_sms_send_rate_limit: {
+ description: 'Too many SMS messages have been sent to this phone number. Ask the user to wait.',
+ },
+ phone_not_confirmed: {
+ description: 'Signing in is not allowed for this user as the phone number is not confirmed.',
+ },
+ phone_provider_disabled: {
+ description: 'Signups are disabled for phone and password.',
+ },
+ provider_disabled: {
+ description: 'OAuth provider is disabled for use. Check configuration.',
+ },
+ provider_email_needs_verification: {
+ description: 'OAuth provider does not verify emails. A verification email has been sent.',
+ },
+ reauthentication_needed: {
+ description: 'A user must reauthenticate to change their password.',
+ },
+ reauthentication_not_valid: {
+ description: 'Reauthentication failed. The code is incorrect.',
+ },
+ refresh_token_already_used: {
+ description: 'Refresh token has been revoked and is outside the reuse interval.',
+ },
+ refresh_token_not_found: {
+ description: 'Session containing the refresh token not found.',
+ },
+ request_timeout: {
+ description: 'Processing the request took too long. Retry the request.',
+ },
+ same_password: {
+ description: 'New password must be different from the current password.',
+ },
+ saml_assertion_no_email: {
+ description: 'SAML assertion did not contain an email address.',
+ },
+ saml_assertion_no_user_id: {
+ description: 'SAML assertion did not contain a required user ID (NameID).',
+ },
+ saml_entity_id_mismatch: {
+ description:
+ 'Entity ID in SAML update does not match the database. Create a new provider instead.',
+ },
+ saml_idp_already_exists: {
+ description: 'SAML identity provider already exists.',
+ },
+ saml_idp_not_found: {
+ description: 'SAML identity provider not found.',
+ },
+ saml_metadata_fetch_failed: {
+ description: 'Failed to fetch metadata from the provided URL for SAML provider.',
+ },
+ saml_provider_disabled: {
+ description: 'Enterprise SSO with SAML 2.0 is not enabled on the Auth server.',
+ },
+ saml_relay_state_expired: {
+ description: 'SAML relay state expired. Ask the user to sign in again.',
+ },
+ saml_relay_state_not_found: {
+ description: 'SAML relay state no longer exists. Ask the user to sign in again.',
+ },
+ session_expired: {
+ description: 'Session has expired due to inactivity or time limit.',
+ },
+ session_not_found: {
+ description: 'Session no longer exists. Possibly deleted or user signed out.',
+ },
+ signup_disabled: {
+ description: 'Sign ups (new account creation) are disabled on the server.',
+ },
+ single_identity_not_deletable: {
+ description:
+ 'Every user must have at least one identity attached. Cannot delete the only identity.',
+ },
+ sms_send_failed: {
+ description: 'Sending an SMS message failed. Check SMS provider configuration.',
+ },
+ sso_domain_already_exists: {
+ description: 'Only one SSO domain can be registered per identity provider.',
+ },
+ sso_provider_not_found: {
+ description: 'SSO provider not found. Check the signInWithSSO arguments.',
+ },
+ too_many_enrolled_mfa_factors: {
+ description: 'A user can only have a limited number of enrolled MFA factors.',
+ },
+ unexpected_audience: {
+ description: "The request's X-JWT-AUD claim does not match the JWT's audience.",
+ },
+ unexpected_failure: {
+ description: 'Auth service is degraded or a bug occurred without a specific reason.',
+ },
+ user_already_exists: {
+ description: 'User with this email or phone cannot be created again as it already exists.',
+ },
+ user_banned: {
+ description: 'User is banned until the banned_until field is cleared.',
+ },
+ user_sso_managed: {
+ description: 'Certain fields of an SSO user cannot be updated, like email.',
+ },
+ validation_failed: {
+ description: 'Provided parameters are not in the expected format.',
+ },
+ weak_password: {
+ description: 'Password does not meet the required strength criteria.',
+ },
+}