The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: update audit log schema & UI (#45389)
Samir Ketemad666b950ff5a
diff --git a/apps/studio/components/interfaces/Account/AuditLogs.tsx b/apps/studio/components/interfaces/Account/AuditLogs.tsxindex a5078a28d7e..481f8eaebcf 100644--- a/apps/studio/components/interfaces/Account/AuditLogs.tsx+++ b/apps/studio/components/interfaces/Account/AuditLogs.tsx@@ -8,12 +8,17 @@ import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'import { TimestampInfo } from 'ui-patterns/TimestampInfo'import { LogsDatePicker } from '../Settings/Logs/Logs.DatePickers'+import { filterByProjects, sortAuditLogs } from './AuditLogs.utils'import { LogDetailsPanel } from '@/components/interfaces/AuditLogs/LogDetailsPanel'+import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'import Table from '@/components/to-be-cleaned/Table'import AlertError from '@/components/ui/AlertError'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { FilterPopover } from '@/components/ui/FilterPopover'-import type { AuditLog } from '@/data/organizations/organization-audit-logs-query'+import {+ TIMESTAMP_MICROS_PER_MS,+ type V2AuditLog,+} from '@/data/organizations/organization-audit-logs-query'import { useOrganizationsQuery } from '@/data/organizations/organizations-query'import { useProfileAuditLogsQuery } from '@/data/profile/profile-audit-logs-query'import { useProjectsInfiniteQuery } from '@/data/projects/projects-infinite-query'@@ -30,9 +35,9 @@ export const AuditLogs = () => {to: currentTime.toISOString(),})- const [selectedLog, setSelectedLog] = useState<AuditLog>()+ const [selectedLog, setSelectedLog] = useState<V2AuditLog>()const [filters, setFilters] = useState<{ projects: string[] }>({- projects: [], // project_ref[]+ projects: [],})const {@@ -69,21 +74,7 @@ export const AuditLogs = () => {)const logs = data?.result ?? []- const sortedLogs = logs- ?.sort((a, b) =>- dateSortDesc- ? Number(new Date(b.occurred_at)) - Number(new Date(a.occurred_at))- : Number(new Date(a.occurred_at)) - Number(new Date(b.occurred_at))- )- ?.filter((log) => {- if (filters.projects.length > 0) {- return filters.projects.includes(- log.target.metadata.project_ref || log.target.metadata.ref || ''- )- } else {- return log- }- })+ const sortedLogs = filterByProjects(sortAuditLogs(logs, dateSortDesc), filters.projects)// This feature depends on the subscription tier of the user. Free user can view logs up to 1 day// in the past. The API limits the logs to maximum of 1 day and 5 minutes so when the page is@@ -104,195 +95,209 @@ export const AuditLogs = () => {return (<>- <div className="space-y-4 flex flex-col pb-8">- <div className="flex flex-col md:flex-row md:items-center justify-between">- <div className="flex items-center space-x-2">- <p className="text-xs prose">Filter by</p>- <FilterPopover- name="Projects"- options={projects ?? []}- labelKey="name"- valueKey="ref"- activeOptions={filters.projects}- onSaveFilters={(values) => setFilters({ ...filters, projects: values })}- search={search}- setSearch={setSearch}- hasNextPage={hasNextPage}- isLoading={isLoadingProjects}- isFetching={isFetching}- isFetchingNextPage={isFetchingNextPage}- fetchNextPage={fetchNextPage}- />- <LogsDatePicker- hideWarnings- value={dateRange}- onSubmit={(value) => setDateRange(value)}- helpers={[- {- text: 'Last 1 hour',- calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),- calcTo: () => dayjs().toISOString(),- },- {- text: 'Last 3 hours',- calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),- calcTo: () => dayjs().toISOString(),- },-- {- text: 'Last 6 hours',- calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),- calcTo: () => dayjs().toISOString(),- },- {- text: 'Last 12 hours',- calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),- calcTo: () => dayjs().toISOString(),- },- {- text: 'Last 24 hours',- calcFrom: () => dayjs().subtract(1, 'day').toISOString(),- calcTo: () => dayjs().toISOString(),- },- ]}- />- {isSuccess && (- <>- <div className="h-[20px] border-r border-strong ml-4! mr-2!" />- <p className="prose text-xs">Viewing {sortedLogs.length} logs in total</p>- </>- )}- </div>- <Button- type="default"- disabled={isLoading || isRefetching}- icon={<RefreshCw className={isRefetching ? 'animate-spin' : ''} />}- onClick={() => refetch()}- >- {isRefetching ? 'Refreshing' : 'Refresh'}- </Button>- </div>-- {isLoading && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}-- {isError && <AlertError error={error} subject="Failed to retrieve audit logs" />}+ <ScaffoldContainer className="px-6 xl:px-10">+ <ScaffoldSection isFullWidth>+ <div className="space-y-4 flex flex-col">+ <div className="flex flex-col md:flex-row md:items-center justify-between">+ <div className="flex items-center space-x-2">+ <p className="text-xs prose">Filter by</p>+ <FilterPopover+ name="Projects"+ options={projects ?? []}+ labelKey="name"+ valueKey="ref"+ activeOptions={filters.projects}+ onSaveFilters={(values) => setFilters({ ...filters, projects: values })}+ search={search}+ setSearch={setSearch}+ hasNextPage={hasNextPage}+ isLoading={isLoadingProjects}+ isFetching={isFetching}+ isFetchingNextPage={isFetchingNextPage}+ fetchNextPage={fetchNextPage}+ />+ <LogsDatePicker+ hideWarnings+ value={dateRange}+ onSubmit={(value) => setDateRange(value)}+ helpers={[+ {+ text: 'Last 1 hour',+ calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),+ calcTo: () => dayjs().toISOString(),+ },+ {+ text: 'Last 3 hours',+ calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),+ calcTo: () => dayjs().toISOString(),+ },- {isSuccess && (- <>- {logs.length === 0 ? (- <div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">- <p className="prose text-sm">You do not have any audit logs available yet</p>+ {+ text: 'Last 6 hours',+ calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),+ calcTo: () => dayjs().toISOString(),+ },+ {+ text: 'Last 12 hours',+ calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),+ calcTo: () => dayjs().toISOString(),+ },+ {+ text: 'Last 24 hours',+ calcFrom: () => dayjs().subtract(1, 'day').toISOString(),+ calcTo: () => dayjs().toISOString(),+ },+ ]}+ />+ {isSuccess && (+ <>+ <div className="h-[20px] border-r border-strong !ml-4 !mr-2" />+ <p className="prose text-xs">Viewing {sortedLogs.length} logs in total</p>+ </>+ )}</div>- ) : logs.length > 0 && sortedLogs.length === 0 ? (- <div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">- <p className="prose text-sm">No audit logs found based on the filters applied</p>+ <Button+ type="default"+ disabled={isLoading || isRefetching}+ icon={<RefreshCw className={isRefetching ? 'animate-spin' : ''} />}+ onClick={() => refetch()}+ >+ {isRefetching ? 'Refreshing' : 'Refresh'}+ </Button>+ </div>++ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" /></div>- ) : (- <div className="overflow-hidden md:overflow-auto overflow-x-scroll">- <Table- head={[- <Table.th key="action" className="py-2">- Action- </Table.th>,- <Table.th key="target" className="py-2">- Target- </Table.th>,- <Table.th key="date" className="py-2">- <div className="flex items-center space-x-2">- <p>Date</p>- <ButtonTooltip- type="text"- className="px-1"- icon={- dateSortDesc ? (- <ArrowDown strokeWidth={1.5} size={14} />- ) : (- <ArrowUp strokeWidth={1.5} size={14} />- )- }- onClick={() => setDateSortDesc(!dateSortDesc)}- tooltip={{- content: {- side: 'bottom',- text: dateSortDesc ? 'Sort latest first' : 'Sort earliest first',- },- }}- />- </div>- </Table.th>,- <Table.th key="actions" className="py-2"></Table.th>,- ]}- body={- sortedLogs?.map((log) => {- const logProjectRef =- log.target.metadata.project_ref || log.target.metadata.ref- const logOrgSlug = log.target.metadata.org_slug || log.target.metadata.slug+ )}- const project = projects?.find((project) => project.ref === logProjectRef)- const organization = organizations?.find((org) => org.slug === logOrgSlug)+ {isError && <AlertError error={error} subject="Failed to retrieve audit logs" />}- const hasStatusCode = log.action.metadata[0]?.status !== undefined+ {isSuccess && (+ <>+ {logs.length === 0 ? (+ <div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">+ <p className="prose text-sm">You do not have any audit logs available yet</p>+ </div>+ ) : logs.length > 0 && sortedLogs.length === 0 ? (+ <div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">+ <p className="prose text-sm">+ No audit logs found based on the filters applied+ </p>+ </div>+ ) : (+ <div className="overflow-hidden md:overflow-auto overflow-x-scroll">+ <Table+ head={[+ <Table.th key="action" className="py-2">+ Action+ </Table.th>,+ <Table.th key="target" className="py-2">+ Target+ </Table.th>,+ <Table.th key="date" className="py-2">+ <div className="flex items-center space-x-2">+ <p>Date</p>+ <ButtonTooltip+ type="text"+ className="px-1"+ icon={+ dateSortDesc ? (+ <ArrowDown strokeWidth={1.5} size={14} />+ ) : (+ <ArrowUp strokeWidth={1.5} size={14} />+ )+ }+ onClick={() => setDateSortDesc(!dateSortDesc)}+ tooltip={{+ content: {+ side: 'bottom',+ text: dateSortDesc ? 'Sort latest first' : 'Sort earliest first',+ },+ }}+ />+ </div>+ </Table.th>,+ <Table.th key="actions" className="py-2"></Table.th>,+ ]}+ body={+ sortedLogs?.map((log) => {+ const project = projects?.find((p) => p.ref === log.project_ref)+ const organization = organizations?.find(+ (org) => org.slug === log.organization_slug+ )+ const isoTimestamp = dayjs(+ log.timestamp / TIMESTAMP_MICROS_PER_MS+ ).toISOString()- return (- <Table.tr- key={log.occurred_at}- onClick={() => setSelectedLog(log)}- className="cursor-pointer hover:bg-alternative! transition duration-100"- >- <Table.td className="max-w-[250px]">- <div className="flex items-center space-x-2">- {hasStatusCode && (- <p className="bg-surface-200 rounded-sm px-1 flex items-center justify-center text-xs font-mono border">- {log.action.metadata[0].status}- </p>- )}- <p className="truncate" title={log.action.name}>- {log.action.name}- </p>- </div>- </Table.td>- <Table.td>- <p- className="text-foreground-light max-w-[230px] truncate"- title={project?.name ?? organization?.name ?? '-'}+ return (+ <Table.tr+ key={log.request_id}+ onClick={() => setSelectedLog(log)}+ className="cursor-pointer hover:bg-alternative! transition duration-100">- {project?.name- ? 'Project: '- : organization?.name- ? 'Organization: '- : null}- {project?.name ?? organization?.name ?? '-'}- </p>- <p- className="text-foreground-light text-xs mt-0.5 truncate"- title={logProjectRef ?? logOrgSlug ?? ''}- >- {logProjectRef ? 'Ref: ' : logOrgSlug ? 'Slug: ' : null}- {logProjectRef ?? logOrgSlug}- </p>- </Table.td>- <Table.td>- <TimestampInfo className="text-sm" utcTimestamp={log.occurred_at} />- </Table.td>- <Table.td align="right">- <Button type="default">View details</Button>- </Table.td>- </Table.tr>- )- }) ?? []- }- />- </div>+ <Table.td className="max-w-[250px]">+ <div className="flex items-center space-x-2">+ <p className="bg-surface-200 rounded-sm px-1 flex items-center justify-center text-xs font-mono border">+ {log.action.status}+ </p>+ <p className="text-foreground-light text-xs font-mono">+ {log.action.method}+ </p>+ <p className="truncate" title={log.action.name}>+ {log.action.name}+ </p>+ </div>+ </Table.td>+ <Table.td>+ {project || organization ? (+ <>+ <p+ className="text-foreground-light max-w-[230px] truncate"+ title={project?.name ?? organization?.name}+ >+ {project?.name+ ? 'Project: '+ : organization?.name+ ? 'Organization: '+ : null}+ {project?.name ?? organization?.name}+ </p>+ <p+ className="text-foreground-light text-xs mt-0.5 truncate"+ title={log.project_ref ?? log.organization_slug ?? ''}+ >+ {log.project_ref ? 'Ref: ' : 'Slug: '}+ {log.project_ref ?? log.organization_slug}+ </p>+ </>+ ) : (+ <p className="text-foreground-light text-sm">+ {log.project_ref ?? log.organization_slug ?? '-'}+ </p>+ )}+ </Table.td>+ <Table.td>+ <TimestampInfo className="text-sm" utcTimestamp={isoTimestamp} />+ </Table.td>+ <Table.td align="right">+ <Button type="default">View details</Button>+ </Table.td>+ </Table.tr>+ )+ }) ?? []+ }+ />+ </div>+ )}+ </>)}- </>- )}- </div>+ </div>+ </ScaffoldSection>+ </ScaffoldContainer><LogDetailsPanel selectedLog={selectedLog} onClose={() => setSelectedLog(undefined)} /></>diff --git a/apps/studio/components/interfaces/Account/AuditLogs.utils.ts b/apps/studio/components/interfaces/Account/AuditLogs.utils.tsnew file mode 100644index 00000000000..081a6376427--- /dev/null+++ b/apps/studio/components/interfaces/Account/AuditLogs.utils.ts@@ -0,0 +1,12 @@+import type { V2AuditLog } from '@/data/organizations/organization-audit-logs-query'++export function sortAuditLogs(logs: V2AuditLog[], descending: boolean): V2AuditLog[] {+ return [...logs].sort((a, b) =>+ descending ? b.timestamp - a.timestamp : a.timestamp - b.timestamp+ )+}++export function filterByProjects(logs: V2AuditLog[], projectRefs: string[]): V2AuditLog[] {+ if (projectRefs.length === 0) return logs+ return logs.filter((log) => projectRefs.includes(log.project_ref ?? ''))+}diff --git a/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsx b/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsxindex ba635734072..7d66e81a246 100644--- a/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsx+++ b/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsx@@ -6,20 +6,28 @@ import {FormSectionContent,FormSectionLabel,} from '@/components/ui/Forms/FormSection'-import type { AuditLog } from '@/data/organizations/organization-audit-logs-query'+import {+ TIMESTAMP_MICROS_PER_MS,+ type V2AuditLog,+} from '@/data/organizations/organization-audit-logs-query'-export interface LogDetailsPanelProps {- selectedLog?: AuditLog+interface LogDetailsPanelProps {+ selectedLog?: V2AuditLogonClose: () => void}export const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps) => {+ const timestamp = selectedLog+ ? dayjs(selectedLog.timestamp / TIMESTAMP_MICROS_PER_MS).format('DD MMM YYYY, HH:mm:ss')+ : ''+ const timestampWithTz = selectedLog+ ? dayjs(selectedLog.timestamp / TIMESTAMP_MICROS_PER_MS).format('DD MMM YYYY, HH:mm:ss (ZZ)')+ : ''+return (<SidePanelsize="large"- header={`"${selectedLog?.action.name}" on ${dayjs(selectedLog?.occurred_at).format(- 'DD MMM YYYY, HH:mm:ss'- )}`}+ header={selectedLog ? `"${selectedLog.action.name}" on ${timestamp}` : ''}visible={selectedLog !== undefined}onCancel={onClose}cancelText="Close"@@ -30,9 +38,25 @@ export const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps)readOnlysize="small"label="Occurred at"- value={selectedLog?.occurred_at}- descriptionText={dayjs(selectedLog?.occurred_at).format('DD MMM YYYY, HH:mm:ss (ZZ)')}+ value={+ selectedLog+ ? dayjs(selectedLog.timestamp / TIMESTAMP_MICROS_PER_MS).toISOString()+ : ''+ }+ descriptionText={timestampWithTz}/>+ <Input readOnly size="small" label="Request ID" value={selectedLog?.request_id ?? ''} />+ {selectedLog?.organization_slug && (+ <Input+ readOnly+ size="small"+ label="Organization"+ value={selectedLog.organization_slug}+ />+ )}+ {selectedLog?.project_ref && (+ <Input readOnly size="small" label="Project ref" value={selectedLog.project_ref} />+ )}</FormSectionContent></FormSection>@@ -40,15 +64,32 @@ export const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps)<FormSection header={<FormSectionLabel>Actor</FormSectionLabel>}><FormSectionContent loading={false}>- <Input readOnly size="small" label="Actor ID" value={selectedLog?.actor.id} />- <Input.TextArea+ <InputreadOnlysize="small"- label="Metadata"- rows={5}- className="input-mono input-xs"- value={JSON.stringify(selectedLog?.actor.metadata, null, 2)}+ label="Token type"+ value={selectedLog?.actor.token_type ?? ''}/>+ {selectedLog?.actor.email && (+ <Input readOnly size="small" label="Email" value={selectedLog.actor.email} />+ )}+ {selectedLog?.actor.user_id && (+ <Input readOnly size="small" label="User ID" value={selectedLog.actor.user_id} />+ )}+ {selectedLog?.actor.ip && (+ <Input readOnly size="small" label="IP address" value={selectedLog.actor.ip} />+ )}+ {selectedLog?.actor.oauth_app_name && (+ <Input+ readOnly+ size="small"+ label="OAuth app"+ value={selectedLog.actor.oauth_app_name}+ />+ )}+ {selectedLog?.actor.app_name && (+ <Input readOnly size="small" label="App" value={selectedLog.actor.app_name} />+ )}</FormSectionContent></FormSection>@@ -56,31 +97,25 @@ export const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps)<FormSection header={<FormSectionLabel>Action</FormSectionLabel>}><FormSectionContent loading={false}>- <Input readOnly size="small" label="Name" value={selectedLog?.action.name} />- <Input.TextArea- readOnly- size="small"- label="Metadata"- rows={5}- className="input-mono input-xs"- value={JSON.stringify(selectedLog?.action.metadata, null, 2)}- />- </FormSectionContent>- </FormSection>-- <SidePanel.Separator />-- <FormSection header={<FormSectionLabel>Target</FormSectionLabel>}>- <FormSectionContent loading={false}>- <Input readOnly size="small" label="Name" value={selectedLog?.target.description} />- <Input.TextArea+ <Input readOnly size="small" label="Name" value={selectedLog?.action.name ?? ''} />+ <Input readOnly size="small" label="Method" value={selectedLog?.action.method ?? ''} />+ <Input readOnly size="small" label="Route" value={selectedLog?.action.route ?? ''} />+ <InputreadOnlysize="small"- label="Metadata"- rows={5}- className="input-mono input-xs"- value={JSON.stringify(selectedLog?.target.metadata, null, 2)}+ label="Status"+ value={String(selectedLog?.action.status ?? '')}/>+ {selectedLog?.action.metadata && (+ <Input.TextArea+ readOnly+ size="small"+ label="Metadata"+ rows={5}+ className="input-mono input-xs"+ value={JSON.stringify(selectedLog.action.metadata, null, 2)}+ />+ )}</FormSectionContent></FormSection></SidePanel>diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsxindex c3bada798f0..1d2a4711748 100644--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx@@ -15,6 +15,7 @@ import {} from 'ui'import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'+import { filterByProjects, filterByUsers, sortAuditLogs } from './AuditLogs.utils'import { LogDetailsPanel } from '@/components/interfaces/AuditLogs/LogDetailsPanel'import { LogsDatePicker } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'@@ -27,6 +28,7 @@ import { UpgradeToPro } from '@/components/ui/UpgradeToPro'import { useOrganizationRolesV2Query } from '@/data/organization-members/organization-roles-query'import {AuditLog,+ TIMESTAMP_MICROS_PER_MS,useOrganizationAuditLogsQuery,} from '@/data/organizations/organization-audit-logs-query'import { useOrganizationMembersQuery } from '@/data/organizations/organization-members-query'@@ -120,26 +122,10 @@ export const AuditLogs = () => {useMemo(() => projectsData?.pages.flatMap((page) => page.projects), [projectsData?.pages]) || []const logs = data?.result ?? []- const sortedLogs = logs- ?.sort((a, b) =>- dateSortDesc- ? Number(new Date(b.occurred_at)) - Number(new Date(a.occurred_at))- : Number(new Date(a.occurred_at)) - Number(new Date(b.occurred_at))- )- ?.filter((log) => {- if (filters.users.length > 0) {- return filters.users.includes(log.actor.id)- } else {- return log- }- })- ?.filter((log) => {- if (filters.projects.length > 0) {- return filters.projects.includes(log.target.metadata.ref || '')- } else {- return log- }- })+ const sortedLogs = filterByProjects(+ filterByUsers(sortAuditLogs(logs, dateSortDesc), filters.users),+ filters.projects+ )const shouldShowLoadingState =(isLoading && fetchStatus !== 'idle') || isLoadingPermissions || isLoadingEntitlements@@ -339,17 +325,13 @@ export const AuditLogs = () => {body={sortedLogs?.map((log) => {const user = (members ?? []).find(- (member) => member.gotrue_id === log.actor.id+ (member) => member.gotrue_id === log.actor.user_id)const role = roles.find((role) => user?.role_ids?.[0] === role.id)- const logProjectRef =- log.target.metadata.project_ref ?? log.target.metadata.ref- const logOrgSlug = log.target.metadata.org_slug ?? log.target.metadata.slug-- const project = projects?.find((project) => project.ref === logProjectRef)- const organization = organizations?.find((org) => org.slug === logOrgSlug)-- const hasStatusCode = log.action.metadata[0]?.status !== undefined+ const project = projects?.find((p) => p.ref === log.project_ref)+ const organization = organizations?.find(+ (org) => org.slug === log.organization_slug+ )const userIcon =user === undefined ? (<div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">@@ -371,7 +353,7 @@ export const AuditLogs = () => {return (<Table.tr- key={log.occurred_at}+ key={log.request_id}onClick={() => setSelectedLog(log)}className="cursor-pointer hover:bg-alternative! transition duration-100">@@ -379,7 +361,9 @@ export const AuditLogs = () => {<div className="flex items-center space-x-4"><div>{userIcon}</div><div>- <p className="text-foreground-light">{user?.username ?? '-'}</p>+ <p className="text-foreground-light">+ {user?.username ?? log.actor.email ?? '-'}+ </p>{role && (<p className="mt-0.5 text-xs text-foreground-light">{role?.name}@@ -390,38 +374,43 @@ export const AuditLogs = () => {</Table.td><Table.td className="max-w-[250px]"><div className="flex items-center space-x-2">- {hasStatusCode && (- <p className="bg-surface-200 rounded-sm px-1 flex items-center justify-center text-xs font-mono border">- {log.action.metadata[0].status}- </p>- )}+ <p className="bg-surface-200 rounded-sm px-1 flex items-center justify-center text-xs font-mono border">+ {log.action.status}+ </p>+ <p className="text-foreground-light text-xs font-mono">+ {log.action.method}+ </p><p className="truncate" title={log.action.name}>{log.action.name}</p></div></Table.td><Table.td>- <p- className="text-foreground-light max-w-[230px] truncate"- title={project?.name ?? organization?.name ?? '-'}- >- {project?.name- ? 'Project: '- : organization?.name- ? 'Organization: '- : null}- {project?.name ?? organization?.name ?? 'Unknown'}- </p>- <p- className="text-foreground-light text-xs mt-0.5 truncate"- title={logProjectRef ?? logOrgSlug ?? ''}- >- {logProjectRef ? 'Ref: ' : logOrgSlug ? 'Slug: ' : null}- {logProjectRef ?? logOrgSlug}- </p>+ {project || organization ? (+ <>+ <p+ className="text-foreground-light max-w-[230px] truncate"+ title={project?.name ?? organization?.name}+ >+ {project ? 'Project: ' : 'Organization: '}+ {project?.name ?? organization?.name}+ </p>+ <p className="text-foreground-light text-xs mt-0.5 truncate">+ {log.project_ref+ ? `Ref: ${log.project_ref}`+ : `Slug: ${log.organization_slug}`}+ </p>+ </>+ ) : (+ <p className="text-foreground-light text-sm">+ {log.project_ref ?? log.organization_slug ?? '-'}+ </p>+ )}</Table.td><Table.td>- {dayjs(log.occurred_at).format('DD MMM YYYY, HH:mm:ss')}+ {dayjs(log.timestamp / TIMESTAMP_MICROS_PER_MS).format(+ 'DD MMM YYYY, HH:mm:ss'+ )}</Table.td><Table.td align="right"><Button type="default">View details</Button>diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.tsindex d3f14bc0016..a1ed75507bd 100644--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts@@ -1,6 +1,23 @@import dayjs from 'dayjs'import { DatePickerToFrom } from '@/components/interfaces/Settings/Logs/Logs.types'+import type { V2AuditLog } from '@/data/organizations/organization-audit-logs-query'++export function sortAuditLogs(logs: V2AuditLog[], descending: boolean): V2AuditLog[] {+ return [...logs].sort((a, b) =>+ descending ? b.timestamp - a.timestamp : a.timestamp - b.timestamp+ )+}++export function filterByUsers(logs: V2AuditLog[], userIds: string[]): V2AuditLog[] {+ if (userIds.length === 0) return logs+ return logs.filter((log) => userIds.includes(log.actor.user_id ?? ''))+}++export function filterByProjects(logs: V2AuditLog[], projectRefs: string[]): V2AuditLog[] {+ if (projectRefs.length === 0) return logs+ return logs.filter((log) => projectRefs.includes(log.project_ref ?? ''))+}// [Joshen] Mainly to handle if a single date is selected - currently just for Audit Logs as// i'm on the fence if this logic should be within the DatePicker component itselfdiff --git a/apps/studio/data/organizations/organization-audit-logs-query.ts b/apps/studio/data/organizations/organization-audit-logs-query.tsindex 2737a6803e1..eea95980cab 100644--- a/apps/studio/data/organizations/organization-audit-logs-query.ts+++ b/apps/studio/data/organizations/organization-audit-logs-query.ts@@ -4,38 +4,39 @@ import { organizationKeys } from './keys'import { get, handleError } from '@/data/fetchers'import type { ResponseError, UseCustomQueryOptions } from '@/types'-export type AuditLog = {+// V2 audit log timestamps are returned in microseconds, not milliseconds.+// Divide by this constant before passing to dayjs/Date to get a valid date.+export const TIMESTAMP_MICROS_PER_MS = 1000++export type V2AuditLog = {+ organization_slug?: string+ project_ref?: string+ request_id: stringaction: {- metadata: {- method?: string- route?: string- status?: number- }[]name: string+ method: string+ route: string+ status: number+ metadata?: Record<string, unknown>}actor: {- id: string- type: 'user' | string- metadata: {- email?: string- ip?: string- tokenType?: string- }[]- }- target: {- description: string- metadata: {- org_slug?: string- project_ref?: string | null- ref?: string | null- slug?: string | null- }+ token_type: string+ token_hash?: string+ user_id?: string+ email?: string+ oauth_app_id?: string+ oauth_app_name?: string+ app_id?: string+ app_name?: string+ ip?: string}- occurred_at: string+ timestamp: number}+export type { V2AuditLog as AuditLog }+export type OrganizationAuditLogsResponse = {- result: AuditLog[]+ result: V2AuditLog[]retention_period: number}@@ -52,7 +53,7 @@ export async function getOrganizationAuditLogs(if (!slug) throw new Error('slug is required')const { data, error } = await get('/platform/organizations/{slug}/audit', {- params: { path: { slug }, query: { iso_timestamp_start, iso_timestamp_end } },+ params: { path: { slug }, query: { iso_timestamp_start, iso_timestamp_end, format: 'v2' } },signal,})diff --git a/apps/studio/data/profile/profile-audit-logs-query.ts b/apps/studio/data/profile/profile-audit-logs-query.tsindex d7934289eb6..900e12ba152 100644--- a/apps/studio/data/profile/profile-audit-logs-query.ts+++ b/apps/studio/data/profile/profile-audit-logs-query.ts@@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query'import { profileKeys } from './keys'import { get, handleError } from '@/data/fetchers'-import type { AuditLog } from '@/data/organizations/organization-audit-logs-query'+import { V2AuditLog } from '@/data/organizations/organization-audit-logs-query'import { IS_PLATFORM } from '@/lib/constants'import type { ResponseError, UseCustomQueryOptions } from '@/types'@@ -20,6 +20,7 @@ export async function getProfileAuditLogs(query: {iso_timestamp_start,iso_timestamp_end,+ format: 'v2',},},signal,@@ -31,7 +32,7 @@ export async function getProfileAuditLogs(export type ProfileAuditLogsError = ResponseErrorexport type ProfileAuditLogsData = {- result: AuditLog[]+ result: V2AuditLog[]retention_period: number}diff --git a/apps/studio/pages/account/audit.tsx b/apps/studio/pages/account/audit.tsxindex 71d8d8e0a16..9980adf7598 100644--- a/apps/studio/pages/account/audit.tsx+++ b/apps/studio/pages/account/audit.tsx@@ -1,4 +1,3 @@-import { PageContainer } from 'ui-patterns/PageContainer'import {PageHeader,PageHeaderDescription,@@ -16,7 +15,7 @@ import type { NextPageWithLayout } from '@/types'const Audit: NextPageWithLayout = () => {return (<>- <PageHeader size="small">+ <PageHeader size="default"><PageHeaderMeta><PageHeaderSummary><PageHeaderTitle>Audit Logs</PageHeaderTitle>@@ -26,9 +25,7 @@ const Audit: NextPageWithLayout = () => {</PageHeaderSummary></PageHeaderMeta></PageHeader>- <PageContainer size="small" className="mt-8">- <AuditLogs />- </PageContainer>+ <AuditLogs /></>)}diff --git a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.tsnew file mode 100644index 00000000000..7ea97248939--- /dev/null+++ b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts@@ -0,0 +1,132 @@+import dayjs from 'dayjs'+import { describe, expect, test } from 'vitest'++import {+ filterByProjects,+ filterByUsers,+ sortAuditLogs,+} from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'+import {+ TIMESTAMP_MICROS_PER_MS,+ type V2AuditLog,+} from '@/data/organizations/organization-audit-logs-query'++// Timestamps are in microseconds (e.g. 1777471903844000 = April 2026)+const TS_A = 1777471903844000+const TS_B = 1777471903845000+const TS_C = 1777471903846000++function makeLog(overrides: Partial<V2AuditLog> = {}): V2AuditLog {+ return {+ timestamp: TS_A,+ request_id: 'req-1',+ action: { name: 'test', method: 'GET', route: '/api/test', status: 200 },+ actor: { token_type: 'bearer' },+ ...overrides,+ }+}++const logA = makeLog({ timestamp: TS_A, request_id: 'req-a', project_ref: 'proj-1' })+const logB = makeLog({+ timestamp: TS_B,+ request_id: 'req-b',+ project_ref: 'proj-2',+ actor: { token_type: 'bearer', user_id: 'user-1' },+})+const logC = makeLog({+ timestamp: TS_C,+ request_id: 'req-c',+ actor: { token_type: 'bearer', user_id: 'user-2' },+})++describe('timestamp conversion (microseconds → milliseconds)', () => {+ test('dividing by 1000 produces a valid date', () => {+ expect(dayjs(TS_A / TIMESTAMP_MICROS_PER_MS).isValid()).toBe(true)+ })++ test('produces the correct year', () => {+ expect(dayjs(TS_A / TIMESTAMP_MICROS_PER_MS).year()).toBe(2026)+ })++ test('dayjs.unix on a microsecond value produces an invalid date', () => {+ // Guard: confirms the bug we fixed — dayjs.unix() treats the value as seconds,+ // overflowing JS Date's max and producing "Invalid Date"+ expect(dayjs.unix(TS_A).isValid()).toBe(false)+ })+})++describe('sortAuditLogs', () => {+ test('sorts descending (newest first)', () => {+ const result = sortAuditLogs([logA, logC, logB], true)+ expect(result.map((l) => l.request_id)).toEqual(['req-c', 'req-b', 'req-a'])+ })++ test('sorts ascending (oldest first)', () => {+ const result = sortAuditLogs([logC, logA, logB], false)+ expect(result.map((l) => l.request_id)).toEqual(['req-a', 'req-b', 'req-c'])+ })++ test('does not mutate the input array', () => {+ const input = [logC, logA]+ sortAuditLogs(input, true)+ expect(input[0].request_id).toBe('req-c')+ })++ test('returns empty array unchanged', () => {+ expect(sortAuditLogs([], true)).toEqual([])+ })++ test('handles a single log', () => {+ expect(sortAuditLogs([logA], true)).toEqual([logA])+ })+})++describe('filterByUsers', () => {+ test('returns all logs when filter list is empty', () => {+ expect(filterByUsers([logA, logB, logC], [])).toEqual([logA, logB, logC])+ })++ test('filters to matching user_id', () => {+ const result = filterByUsers([logA, logB, logC], ['user-1'])+ expect(result.map((l) => l.request_id)).toEqual(['req-b'])+ })++ test('filters to multiple user_ids', () => {+ const result = filterByUsers([logA, logB, logC], ['user-1', 'user-2'])+ expect(result.map((l) => l.request_id)).toEqual(['req-b', 'req-c'])+ })++ test('excludes logs with no user_id when filtering', () => {+ const result = filterByUsers([logA, logB], ['user-1'])+ expect(result.map((l) => l.request_id)).toEqual(['req-b'])+ })++ test('returns empty array when no logs match', () => {+ expect(filterByUsers([logA, logB, logC], ['user-unknown'])).toEqual([])+ })+})++describe('filterByProjects', () => {+ test('returns all logs when filter list is empty', () => {+ expect(filterByProjects([logA, logB, logC], [])).toEqual([logA, logB, logC])+ })++ test('filters to matching project_ref', () => {+ const result = filterByProjects([logA, logB, logC], ['proj-1'])+ expect(result.map((l) => l.request_id)).toEqual(['req-a'])+ })++ test('filters to multiple project_refs', () => {+ const result = filterByProjects([logA, logB, logC], ['proj-1', 'proj-2'])+ expect(result.map((l) => l.request_id)).toEqual(['req-a', 'req-b'])+ })++ test('excludes logs with no project_ref when filtering', () => {+ const result = filterByProjects([logA, logC], ['proj-1'])+ expect(result.map((l) => l.request_id)).toEqual(['req-a'])+ })++ test('returns empty array when no logs match', () => {+ expect(filterByProjects([logA, logB, logC], ['proj-unknown'])).toEqual([])+ })+})diff --git a/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.tsnew file mode 100644index 00000000000..86b1a30f501--- /dev/null+++ b/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts@@ -0,0 +1,83 @@+import dayjs from 'dayjs'+import { afterEach, describe, expect, test, vi } from 'vitest'++import { formatSelectedDateRange } from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'++// Pin "now" to a fixed point so date comparisons are deterministic+const NOW = dayjs('2024-06-15T14:30:00')++afterEach(() => {+ vi.useRealTimers()+})++function fakeNow() {+ vi.setSystemTime(NOW.toDate())+}++describe('formatSelectedDateRange', () => {+ test('two different dates: preserves current time on both ends', () => {+ fakeNow()+ const result = formatSelectedDateRange({+ from: '2024-06-10',+ to: '2024-06-14',+ })+ const from = dayjs(result.from)+ const to = dayjs(result.to)+ expect(from.date()).toBe(10)+ expect(to.date()).toBe(14)+ // Both should carry current H:M:S+ expect(from.hour()).toBe(NOW.hour())+ expect(to.hour()).toBe(NOW.hour())+ })++ test('single date matching today: from is set to 00:00:00', () => {+ fakeNow()+ const today = NOW.format('YYYY-MM-DD')+ const result = formatSelectedDateRange({ from: today, to: today })+ const from = dayjs(result.from)+ expect(from.hour()).toBe(0)+ expect(from.minute()).toBe(0)+ expect(from.second()).toBe(0)+ })++ test('single date matching today: to keeps current time', () => {+ fakeNow()+ const today = NOW.format('YYYY-MM-DD')+ const result = formatSelectedDateRange({ from: today, to: today })+ const to = dayjs(result.to)+ expect(to.hour()).toBe(NOW.hour())+ expect(to.minute()).toBe(NOW.minute())+ })++ test('single date in the past: to is set to 23:59:59', () => {+ fakeNow()+ const result = formatSelectedDateRange({+ from: '2024-06-01',+ to: '2024-06-01',+ })+ const to = dayjs(result.to)+ expect(to.hour()).toBe(23)+ expect(to.minute()).toBe(59)+ expect(to.second()).toBe(59)+ })++ test('single date in the past: from keeps current time', () => {+ fakeNow()+ const result = formatSelectedDateRange({+ from: '2024-06-01',+ to: '2024-06-01',+ })+ const from = dayjs(result.from)+ expect(from.hour()).toBe(NOW.hour())+ })++ test('output is in UTC ISO format', () => {+ fakeNow()+ const result = formatSelectedDateRange({+ from: '2024-06-10',+ to: '2024-06-14',+ })+ expect(result.from).toMatch(/Z$/)+ expect(result.to).toMatch(/Z$/)+ })+})